Annotation of loncom/lond, revision 1.572

1.1       albertel    1: #!/usr/bin/perl
                      2: # The LearningOnline Network
                      3: # lond "LON Daemon" Server (port "LOND" 5663)
1.60      www         4: #
1.572   ! raeburn     5: # $Id: lond,v 1.571 2021/12/21 13:57:47 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.572   ! raeburn    68: my $VERSION='$Revision: 1.571 $'; #' 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},
1.566     raeburn   216:                autovalidateinstcrosslist => {remote => 1, enroll => 1},
1.567     raeburn   217:                autoinstsecreformat => {remote => 1, enroll => 1},
1.525     raeburn   218:                changeuserauth => {remote => 1, domroles => 1},
                    219:                chatretr => {remote => 1, enroll => 1},
                    220:                chatsend => {remote => 1, enroll => 1},
                    221:                courseiddump => {remote => 1, domroles => 1, enroll => 1},
                    222:                courseidput => {remote => 1, domroles => 1, enroll => 1},
                    223:                courseidputhash => {remote => 1, domroles => 1, enroll => 1},
                    224:                courselastaccess => {remote => 1, domroles => 1, enroll => 1},
1.561     raeburn   225:                coursesessions => {institutiononly => 1},
1.525     raeburn   226:                currentauth => {remote => 1, domroles => 1, enroll => 1},
                    227:                currentdump => {remote => 1, enroll => 1},
                    228:                currentversion => {remote=> 1, content => 1},
                    229:                dcmaildump => {remote => 1, domroles => 1},
                    230:                dcmailput => {remote => 1, domroles => 1},
                    231:                del => {remote => 1, domroles => 1, enroll => 1, content => 1},
1.551     raeburn   232:                delbalcookie => {institutiononly => 1},
1.560     raeburn   233:                delusersession => {institutiononly => 1},
1.525     raeburn   234:                deldom => {remote => 1, domroles => 1}, # not currently used
                    235:                devalidatecache => {institutiononly => 1},
                    236:                domroleput => {remote => 1, enroll => 1},
                    237:                domrolesdump => {remote => 1, catalog => 1},
                    238:                du => {remote => 1, enroll => 1},
                    239:                du2 => {remote => 1, enroll => 1},
                    240:                dump => {remote => 1, enroll => 1, domroles => 1},
                    241:                edit => {institutiononly => 1},  #not used currently
1.568     raeburn   242:                edump => {remote => 1, enroll => 1, domroles => 1},
1.525     raeburn   243:                eget => {remote => 1, domroles => 1, enroll => 1}, #not used currently
1.536     raeburn   244:                egetdom => {remote => 1, domroles => 1, enroll => 1, },
1.553     raeburn   245:                ekey => {anywhere => 1},
1.525     raeburn   246:                exit => {anywhere => 1},
                    247:                fetchuserfile => {remote => 1, enroll => 1},
                    248:                get => {remote => 1, domroles => 1, enroll => 1},
                    249:                getdom => {anywhere => 1},
                    250:                home => {anywhere => 1},
                    251:                iddel => {remote => 1, enroll => 1},
                    252:                idget => {remote => 1, enroll => 1},
                    253:                idput => {remote => 1, domroles => 1, enroll => 1},
                    254:                inc => {remote => 1, enroll => 1},
                    255:                init => {anywhere => 1},
                    256:                inst_usertypes => {remote => 1, domroles => 1, enroll => 1},
                    257:                instemailrules => {remote => 1, domroles => 1},
                    258:                instidrulecheck => {remote => 1, domroles => 1,},
                    259:                instidrules => {remote => 1, domroles => 1,},
                    260:                instrulecheck => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1},
                    261:                instselfcreatecheck => {institutiononly => 1},
                    262:                instuserrules => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1},
                    263:                keys => {remote => 1,},
                    264:                load => {anywhere => 1},
                    265:                log => {anywhere => 1},
                    266:                ls => {remote => 1, enroll => 1, content => 1,},
                    267:                ls2 => {remote => 1, enroll => 1, content => 1,},
                    268:                ls3 => {remote => 1, enroll => 1, content => 1,},
1.572   ! raeburn   269:                lti => {institutiononly => 1},
1.525     raeburn   270:                makeuser => {remote => 1, enroll => 1, domroles => 1,},
                    271:                mkdiruserfile => {remote => 1, enroll => 1,},
                    272:                newput => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1,},
                    273:                passwd => {remote => 1},
                    274:                ping => {anywhere => 1},
                    275:                pong => {anywhere => 1},
                    276:                pushfile => {manageronly => 1},
                    277:                put => {remote => 1, enroll => 1, domroles => 1, msg => 1, content => 1, shared => 1},
                    278:                putdom => {remote => 1, domroles => 1,},
                    279:                putstore => {remote => 1, enroll => 1},
                    280:                queryreply => {anywhere => 1},
                    281:                querysend => {anywhere => 1},
1.535     raeburn   282:                querysend_activitylog => {remote => 1},
                    283:                querysend_allusers => {remote => 1, domroles => 1},
                    284:                querysend_courselog => {remote => 1},
                    285:                querysend_fetchenrollment => {remote => 1},
                    286:                querysend_getinstuser => {remote => 1},
                    287:                querysend_getmultinstusers => {remote => 1},
                    288:                querysend_instdirsearch => {remote => 1, domroles => 1, coaurem => 1},
                    289:                querysend_institutionalphotos => {remote => 1},
                    290:                querysend_portfolio_metadata => {remote => 1, content => 1},
                    291:                querysend_userlog => {remote => 1, domroles => 1},
                    292:                querysend_usersearch => {remote => 1, enroll => 1, coaurem => 1},
1.525     raeburn   293:                quit => {anywhere => 1},
                    294:                readlonnetglobal => {institutiononly => 1},
                    295:                reinit => {manageronly => 1}, #not used currently
                    296:                removeuserfile => {remote => 1, enroll => 1},
                    297:                renameuserfile => {remote => 1,},
                    298:                restore => {remote => 1, enroll => 1, reqcrs => 1,},
                    299:                rolesdel => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
                    300:                rolesput => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
1.527     raeburn   301:                servercerts => {institutiononly => 1},
1.528     raeburn   302:                serverdistarch => {anywhere => 1},
1.525     raeburn   303:                serverhomeID => {anywhere => 1},
                    304:                serverloncaparev => {anywhere => 1},
                    305:                servertimezone => {remote => 1, enroll => 1},
                    306:                setannounce => {remote => 1, domroles => 1},
                    307:                sethost => {anywhere => 1},
                    308:                store => {remote => 1, enroll => 1, reqcrs => 1,},
                    309:                studentphoto => {remote => 1, enroll => 1},
                    310:                sub => {content => 1,},
1.552     raeburn   311:                tmpdel => {institutiononly => 1},
                    312:                tmpget => {institutiononly => 1},
                    313:                tmpput => {remote => 1, othcoau => 1},
1.525     raeburn   314:                tokenauthuserfile => {anywhere => 1},
                    315:                unsub => {content => 1,},
                    316:                update => {shared => 1},
1.564     raeburn   317:                updatebalcookie => {institutiononly => 1},
1.525     raeburn   318:                updateclickers => {remote => 1},
                    319:                userhassession => {anywhere => 1},
                    320:                userload => {anywhere => 1},
                    321:                version => {anywhere => 1}, #not used
                    322:             );
                    323: 
                    324: #
1.207     foxr      325: #   Statistics that are maintained and dislayed in the status line.
                    326: #
1.212     foxr      327: my $Transactions = 0;		# Number of attempted transactions.
                    328: my $Failures     = 0;		# Number of transcations failed.
1.207     foxr      329: 
                    330: #   ResetStatistics: 
                    331: #      Resets the statistics counters:
                    332: #
                    333: sub ResetStatistics {
                    334:     $Transactions = 0;
                    335:     $Failures     = 0;
                    336: }
                    337: 
1.200     matthew   338: #------------------------------------------------------------------------
                    339: #
                    340: #   LocalConnection
                    341: #     Completes the formation of a locally authenticated connection.
                    342: #     This function will ensure that the 'remote' client is really the
                    343: #     local host.  If not, the connection is closed, and the function fails.
                    344: #     If so, initcmd is parsed for the name of a file containing the
                    345: #     IDEA session key.  The fie is opened, read, deleted and the session
                    346: #     key returned to the caller.
                    347: #
                    348: # Parameters:
                    349: #   $Socket      - Socket open on client.
                    350: #   $initcmd     - The full text of the init command.
                    351: #
                    352: # Returns:
                    353: #     IDEA session key on success.
                    354: #     undef on failure.
                    355: #
                    356: sub LocalConnection {
                    357:     my ($Socket, $initcmd) = @_;
1.373     albertel  358:     Debug("Attempting local connection: $initcmd client: $clientip");
1.277     albertel  359:     if($clientip ne "127.0.0.1") {
1.200     matthew   360: 	&logthis('<font color="red"> LocalConnection rejecting non local: '
1.373     albertel  361: 		 ."$clientip ne 127.0.0.1 </font>");
1.200     matthew   362: 	close $Socket;
                    363: 	return undef;
1.224     foxr      364:     }  else {
1.200     matthew   365: 	chomp($initcmd);	# Get rid of \n in filename.
                    366: 	my ($init, $type, $name) = split(/:/, $initcmd);
                    367: 	Debug(" Init command: $init $type $name ");
                    368: 
                    369: 	# Require that $init = init, and $type = local:  Otherwise
                    370: 	# the caller is insane:
                    371: 
                    372: 	if(($init ne "init") && ($type ne "local")) {
                    373: 	    &logthis('<font color = "red"> LocalConnection: caller is insane! '
                    374: 		     ."init = $init, and type = $type </font>");
                    375: 	    close($Socket);;
                    376: 	    return undef;
                    377: 		
                    378: 	}
                    379: 	#  Now get the key filename:
                    380: 
                    381: 	my $IDEAKey = lonlocal::ReadKeyFile($name);
                    382: 	return $IDEAKey;
                    383:     }
                    384: }
                    385: #------------------------------------------------------------------------------
                    386: #
                    387: #  SSLConnection
                    388: #   Completes the formation of an ssh authenticated connection. The
                    389: #   socket is promoted to an ssl socket.  If this promotion and the associated
                    390: #   certificate exchange are successful, the IDEA key is generated and sent
                    391: #   to the remote peer via the SSL tunnel. The IDEA key is also returned to
                    392: #   the caller after the SSL tunnel is torn down.
                    393: #
                    394: # Parameters:
                    395: #   Name              Type             Purpose
                    396: #   $Socket          IO::Socket::INET  Plaintext socket.
                    397: #
                    398: # Returns:
                    399: #    IDEA key on success.
                    400: #    undef on failure.
                    401: #
                    402: sub SSLConnection {
                    403:     my $Socket   = shift;
                    404: 
                    405:     Debug("SSLConnection: ");
                    406:     my $KeyFile         = lonssl::KeyFile();
                    407:     if(!$KeyFile) {
                    408: 	my $err = lonssl::LastError();
                    409: 	&logthis("<font color=\"red\"> CRITICAL"
                    410: 		 ."Can't get key file $err </font>");
                    411: 	return undef;
                    412:     }
                    413:     my ($CACertificate,
                    414: 	$Certificate) = lonssl::CertificateFile();
                    415: 
                    416: 
                    417:     # If any of the key, certificate or certificate authority 
                    418:     # certificate filenames are not defined, this can't work.
                    419: 
                    420:     if((!$Certificate) || (!$CACertificate)) {
                    421: 	my $err = lonssl::LastError();
                    422: 	&logthis("<font color=\"red\"> CRITICAL"
                    423: 		 ."Can't get certificates: $err </font>");
                    424: 
                    425: 	return undef;
                    426:     }
                    427:     Debug("Key: $KeyFile CA: $CACertificate Cert: $Certificate");
                    428: 
                    429:     # Indicate to our peer that we can procede with
                    430:     # a transition to ssl authentication:
                    431: 
                    432:     print $Socket "ok:ssl\n";
                    433: 
                    434:     Debug("Approving promotion -> ssl");
                    435:     #  And do so:
                    436: 
1.545     raeburn   437:     my $CRLFile;
                    438:     unless ($crlchecked{$clientname}) {
                    439:         $CRLFile = lonssl::CRLFile();
                    440:         $crlchecked{$clientname} = 1;
                    441:     }
                    442: 
1.200     matthew   443:     my $SSLSocket = lonssl::PromoteServerSocket($Socket,
                    444: 						$CACertificate,
                    445: 						$Certificate,
1.544     raeburn   446: 						$KeyFile,
1.545     raeburn   447: 						$clientname,
1.546     raeburn   448:                                                 $CRLFile,
                    449:                                                 $clientversion);
1.200     matthew   450:     if(! ($SSLSocket) ) {	# SSL socket promotion failed.
                    451: 	my $err = lonssl::LastError();
                    452: 	&logthis("<font color=\"red\"> CRITICAL "
                    453: 		 ."SSL Socket promotion failed: $err </font>");
                    454: 	return undef;
                    455:     }
                    456:     Debug("SSL Promotion successful");
                    457: 
                    458:     # 
                    459:     #  The only thing we'll use the socket for is to send the IDEA key
                    460:     #  to the peer:
                    461: 
                    462:     my $Key = lonlocal::CreateCipherKey();
                    463:     print $SSLSocket "$Key\n";
                    464: 
                    465:     lonssl::Close($SSLSocket); 
                    466: 
                    467:     Debug("Key exchange complete: $Key");
                    468: 
                    469:     return $Key;
                    470: }
                    471: #
                    472: #     InsecureConnection: 
                    473: #        If insecure connections are allowd,
                    474: #        exchange a challenge with the client to 'validate' the
                    475: #        client (not really, but that's the protocol):
                    476: #        We produce a challenge string that's sent to the client.
                    477: #        The client must then echo the challenge verbatim to us.
                    478: #
                    479: #  Parameter:
                    480: #      Socket      - Socket open on the client.
                    481: #  Returns:
                    482: #      1           - success.
                    483: #      0           - failure (e.g.mismatch or insecure not allowed).
                    484: #
                    485: sub InsecureConnection {
                    486:     my $Socket  =  shift;
                    487: 
                    488:     #   Don't even start if insecure connections are not allowed.
1.532     raeburn   489:     #   return 0 if Insecure connections not allowed.
                    490:     #
                    491:     if (ref($secureconf{'connfrom'}) eq 'HASH') {
                    492:         if ($clientsamedom) {
                    493:             if ($secureconf{'connfrom'}{'dom'} eq 'req') {
                    494:                 return 0;
                    495:             } 
                    496:         } elsif ($clientsameinst) {
                    497:             if ($secureconf{'connfrom'}{'intdom'} eq 'req') {
                    498:                 return 0;
                    499:             }
                    500:         } else {
                    501:             if ($secureconf{'connfrom'}{'other'} eq 'req') {
                    502:                 return 0;
                    503:             }
                    504:         }
                    505:     } elsif (!$perlvar{londAllowInsecure}) {
1.200     matthew   506: 	return 0;
                    507:     }
                    508: 
                    509:     #   Fabricate a challenge string and send it..
                    510: 
                    511:     my $challenge = "$$".time;	# pid + time.
                    512:     print $Socket "$challenge\n";
                    513:     &status("Waiting for challenge reply");
                    514: 
                    515:     my $answer = <$Socket>;
                    516:     $answer    =~s/\W//g;
                    517:     if($challenge eq $answer) {
                    518: 	return 1;
1.224     foxr      519:     } else {
1.200     matthew   520: 	logthis("<font color='blue'>WARNING client did not respond to challenge</font>");
                    521: 	&status("No challenge reqply");
                    522: 	return 0;
                    523:     }
                    524:     
                    525: 
                    526: }
1.251     foxr      527: #
                    528: #   Safely execute a command (as long as it's not a shel command and doesn
                    529: #   not require/rely on shell escapes.   The function operates by doing a
                    530: #   a pipe based fork and capturing stdout and stderr  from the pipe.
                    531: #
                    532: # Formal Parameters:
                    533: #     $line                    - A line of text to be executed as a command.
                    534: # Returns:
                    535: #     The output from that command.  If the output is multiline the caller
                    536: #     must know how to split up the output.
                    537: #
                    538: #
                    539: sub execute_command {
                    540:     my ($line)    = @_;
                    541:     my @words     = split(/\s/, $line);	# Bust the command up into words.
                    542:     my $output    = "";
                    543: 
                    544:     my $pid = open(CHILD, "-|");
                    545:     
                    546:     if($pid) {			# Parent process
                    547: 	Debug("In parent process for execute_command");
                    548: 	my @data = <CHILD>;	# Read the child's outupt...
                    549: 	close CHILD;
                    550: 	foreach my $output_line (@data) {
                    551: 	    Debug("Adding $output_line");
                    552: 	    $output .= $output_line; # Presumably has a \n on it.
                    553: 	}
                    554: 
                    555:     } else {			# Child process
                    556: 	close (STDERR);
                    557: 	open  (STDERR, ">&STDOUT");# Combine stderr, and stdout...
                    558: 	exec(@words);		# won't return.
                    559:     }
                    560:     return $output;
                    561: }
                    562: 
1.200     matthew   563: 
1.140     foxr      564: #   GetCertificate: Given a transaction that requires a certificate,
                    565: #   this function will extract the certificate from the transaction
                    566: #   request.  Note that at this point, the only concept of a certificate
                    567: #   is the hostname to which we are connected.
                    568: #
                    569: #   Parameter:
                    570: #      request   - The request sent by our client (this parameterization may
                    571: #                  need to change when we really use a certificate granting
                    572: #                  authority.
                    573: #
                    574: sub GetCertificate {
                    575:     my $request = shift;
                    576: 
                    577:     return $clientip;
                    578: }
1.161     foxr      579: 
1.178     foxr      580: #
                    581: #   Return true if client is a manager.
                    582: #
                    583: sub isManager {
                    584:     return (($ConnectionType eq "manager") || ($ConnectionType eq "both"));
                    585: }
                    586: #
                    587: #   Return tru if client can do client functions
                    588: #
                    589: sub isClient {
                    590:     return (($ConnectionType eq "client") || ($ConnectionType eq "both"));
                    591: }
1.161     foxr      592: 
                    593: 
1.156     foxr      594: #
                    595: #   ReadManagerTable: Reads in the current manager table. For now this is
                    596: #                     done on each manager authentication because:
                    597: #                     - These authentications are not frequent
                    598: #                     - This allows dynamic changes to the manager table
                    599: #                       without the need to signal to the lond.
                    600: #
                    601: sub ReadManagerTable {
                    602: 
1.412     foxr      603:     &Debug("Reading manager table");
1.156     foxr      604:     #   Clean out the old table first..
                    605: 
1.166     foxr      606:    foreach my $key (keys %managers) {
                    607:       delete $managers{$key};
                    608:    }
                    609: 
                    610:    my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
                    611:    if (!open (MANAGERS, $tablename)) {
1.473     raeburn   612:        my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
                    613:        if (&Apache::lonnet::is_LC_dns($hostname)) {
1.472     raeburn   614:            &logthis('<font color="red">No manager table.  Nobody can manage!!</font>');
                    615:        }
                    616:        return;
1.166     foxr      617:    }
                    618:    while(my $host = <MANAGERS>) {
                    619:       chomp($host);
                    620:       if ($host =~ "^#") {                  # Comment line.
                    621:          next;
                    622:       }
1.368     albertel  623:       if (!defined &Apache::lonnet::get_host_ip($host)) { # This is a non cluster member
1.161     foxr      624: 	    #  The entry is of the form:
                    625: 	    #    cluname:hostname
                    626: 	    #  cluname - A 'cluster hostname' is needed in order to negotiate
                    627: 	    #            the host key.
                    628: 	    #  hostname- The dns name of the host.
                    629: 	    #
1.166     foxr      630:           my($cluname, $dnsname) = split(/:/, $host);
                    631:           
                    632:           my $ip = gethostbyname($dnsname);
                    633:           if(defined($ip)) {                 # bad names don't deserve entry.
                    634:             my $hostip = inet_ntoa($ip);
                    635:             $managers{$hostip} = $cluname;
                    636:             logthis('<font color="green"> registering manager '.
                    637:                     "$dnsname as $cluname with $hostip </font>\n");
                    638:          }
                    639:       } else {
                    640:          logthis('<font color="green"> existing host'." $host</font>\n");
1.472     raeburn   641:          $managers{&Apache::lonnet::get_host_ip($host)} = $host;  # Use info from cluster tab if cluster memeber
1.166     foxr      642:       }
                    643:    }
1.156     foxr      644: }
1.140     foxr      645: 
                    646: #
                    647: #  ValidManager: Determines if a given certificate represents a valid manager.
                    648: #                in this primitive implementation, the 'certificate' is
                    649: #                just the connecting loncapa client name.  This is checked
                    650: #                against a valid client list in the configuration.
                    651: #
                    652: #                  
                    653: sub ValidManager {
                    654:     my $certificate = shift; 
                    655: 
1.163     foxr      656:     return isManager;
1.140     foxr      657: }
                    658: #
1.143     foxr      659: #  CopyFile:  Called as part of the process of installing a 
                    660: #             new configuration file.  This function copies an existing
                    661: #             file to a backup file.
                    662: # Parameters:
                    663: #     oldfile  - Name of the file to backup.
                    664: #     newfile  - Name of the backup file.
                    665: # Return:
                    666: #     0   - Failure (errno has failure reason).
                    667: #     1   - Success.
                    668: #
                    669: sub CopyFile {
1.192     foxr      670: 
                    671:     my ($oldfile, $newfile) = @_;
1.143     foxr      672: 
1.281     matthew   673:     if (! copy($oldfile,$newfile)) {
                    674:         return 0;
1.143     foxr      675:     }
1.281     matthew   676:     chmod(0660, $newfile);
                    677:     return 1;
1.143     foxr      678: }
1.157     foxr      679: #
                    680: #  Host files are passed out with externally visible host IPs.
                    681: #  If, for example, we are behind a fire-wall or NAT host, our 
                    682: #  internally visible IP may be different than the externally
                    683: #  visible IP.  Therefore, we always adjust the contents of the
                    684: #  host file so that the entry for ME is the IP that we believe
                    685: #  we have.  At present, this is defined as the entry that
                    686: #  DNS has for us.  If by some chance we are not able to get a
                    687: #  DNS translation for us, then we assume that the host.tab file
                    688: #  is correct.  
                    689: #    BUGBUGBUG - in the future, we really should see if we can
                    690: #       easily query the interface(s) instead.
                    691: # Parameter(s):
                    692: #     contents    - The contents of the host.tab to check.
                    693: # Returns:
                    694: #     newcontents - The adjusted contents.
                    695: #
                    696: #
                    697: sub AdjustHostContents {
                    698:     my $contents  = shift;
                    699:     my $adjusted;
                    700:     my $me        = $perlvar{'lonHostID'};
                    701: 
1.354     albertel  702:     foreach my $line (split(/\n/,$contents)) {
1.472     raeburn   703: 	if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/) ||
                    704:              ($line =~ /^\s*\^/))) {
1.157     foxr      705: 	    chomp($line);
                    706: 	    my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
                    707: 	    if ($id eq $me) {
1.354     albertel  708: 		my $ip = gethostbyname($name);
                    709: 		my $ipnew = inet_ntoa($ip);
                    710: 		$ip = $ipnew;
1.157     foxr      711: 		#  Reconstruct the host line and append to adjusted:
                    712: 		
1.354     albertel  713: 		my $newline = "$id:$domain:$role:$name:$ip";
                    714: 		if($maxcon ne "") { # Not all hosts have loncnew tuning params
                    715: 		    $newline .= ":$maxcon:$idleto:$mincon";
                    716: 		}
                    717: 		$adjusted .= $newline."\n";
1.157     foxr      718: 		
1.354     albertel  719: 	    } else {		# Not me, pass unmodified.
                    720: 		$adjusted .= $line."\n";
                    721: 	    }
1.157     foxr      722: 	} else {                  # Blank or comment never re-written.
                    723: 	    $adjusted .= $line."\n";	# Pass blanks and comments as is.
                    724: 	}
1.354     albertel  725:     }
                    726:     return $adjusted;
1.157     foxr      727: }
1.143     foxr      728: #
                    729: #   InstallFile: Called to install an administrative file:
1.412     foxr      730: #       - The file is created int a temp directory called <name>.tmp
                    731: #       - lcinstall file is called to install the file.
                    732: #         since the web app has no direct write access to the table directory
1.143     foxr      733: #
                    734: #  Parameters:
                    735: #       Name of the file
                    736: #       File Contents.
                    737: #  Return:
                    738: #      nonzero - success.
                    739: #      0       - failure and $! has an errno.
1.412     foxr      740: # Assumptions:
                    741: #    File installtion is a relatively infrequent
1.143     foxr      742: #
                    743: sub InstallFile {
1.192     foxr      744: 
                    745:     my ($Filename, $Contents) = @_;
1.412     foxr      746: #     my $TempFile = $Filename.".tmp";
                    747:     my $exedir = $perlvar{'lonDaemons'};
                    748:     my $tmpdir = $exedir.'/tmp/';
                    749:     my $TempFile = $tmpdir."TempTableFile.tmp";
1.143     foxr      750: 
                    751:     #  Open the file for write:
                    752: 
                    753:     my $fh = IO::File->new("> $TempFile"); # Write to temp.
                    754:     if(!(defined $fh)) {
                    755: 	&logthis('<font color="red"> Unable to create '.$TempFile."</font>");
                    756: 	return 0;
                    757:     }
                    758:     #  write the contents of the file:
                    759: 
                    760:     print $fh ($Contents); 
                    761:     $fh->close;			# In case we ever have a filesystem w. locking
                    762: 
1.412     foxr      763:     chmod(0664, $TempFile);	# Everyone can write it.
                    764: 
                    765:     # Use lcinstall file to put the file in the table directory...
                    766: 
                    767:     &Debug("Opening pipe to $exedir/lcinstallfile $TempFile $Filename");
                    768:     my $pf = IO::File->new("| $exedir/lcinstallfile   $TempFile $Filename > $exedir/logs/lcinstallfile.log");
                    769:     close $pf;
                    770:     my $err = $?;
                    771:     &Debug("Status is $err");
                    772:     if ($err != 0) {
                    773: 	my $msg = $err;
                    774: 	if ($err < @installerrors) {
                    775: 	    $msg = $installerrors[$err];
                    776: 	}
                    777: 	&logthis("Install failed for table file $Filename : $msg");
                    778: 	return 0;
                    779:     }
                    780: 
                    781:     # Remove the temp file:
1.143     foxr      782: 
1.412     foxr      783:     unlink($TempFile);
1.143     foxr      784: 
                    785:     return 1;
                    786: }
1.200     matthew   787: 
                    788: 
1.169     foxr      789: #
                    790: #   ConfigFileFromSelector: converts a configuration file selector
1.411     foxr      791: #                 into a configuration file pathname.
1.472     raeburn   792: #                 Supports the following file selectors: 
                    793: #                 hosts, domain, dns_hosts, dns_domain  
1.411     foxr      794: #
1.169     foxr      795: #
                    796: #  Parameters:
                    797: #      selector  - Configuration file selector.
                    798: #  Returns:
                    799: #      Full path to the file or undef if the selector is invalid.
                    800: #
                    801: sub ConfigFileFromSelector {
                    802:     my $selector   = shift;
                    803:     my $tablefile;
                    804: 
1.549     raeburn   805:     if ($selector eq 'loncapaCAcrl') {
                    806:         my $tabledir = $perlvar{'lonCertificateDirectory'};
                    807:         if (-d $tabledir) {
                    808:             $tablefile =  $tabledir.'/'.$selector.'.pem';
                    809:         }
                    810:     } else {
                    811:         my $tabledir = $perlvar{'lonTabDir'}.'/';
                    812:         if (($selector eq "hosts") || ($selector eq "domain") || 
                    813:             ($selector eq "dns_hosts") || ($selector eq "dns_domain")) {
                    814: 	    $tablefile =  $tabledir.$selector.'.tab';
                    815:         }
1.169     foxr      816:     }
                    817:     return $tablefile;
                    818: }
1.143     foxr      819: #
1.141     foxr      820: #   PushFile:  Called to do an administrative push of a file.
                    821: #              - Ensure the file being pushed is one we support.
                    822: #              - Backup the old file to <filename.saved>
                    823: #              - Separate the contents of the new file out from the
                    824: #                rest of the request.
                    825: #              - Write the new file.
                    826: #  Parameter:
                    827: #     Request - The entire user request.  This consists of a : separated
                    828: #               string pushfile:tablename:contents.
                    829: #     NOTE:  The contents may have :'s in it as well making things a bit
                    830: #            more interesting... but not much.
                    831: #  Returns:
                    832: #     String to send to client ("ok" or "refused" if bad file).
                    833: #
                    834: sub PushFile {
1.510     raeburn   835:     my $request = shift;
1.141     foxr      836:     my ($command, $filename, $contents) = split(":", $request, 3);
1.412     foxr      837:     &Debug("PushFile");
1.141     foxr      838:     
1.549     raeburn   839:     #  At this point in time, pushes for only the following tables and
                    840:     #  CRL file are supported:
1.141     foxr      841:     #   hosts.tab  ($filename eq host).
                    842:     #   domain.tab ($filename eq domain).
1.472     raeburn   843:     #   dns_hosts.tab ($filename eq dns_host).
1.554     raeburn   844:     #   dns_domain.tab ($filename eq dns_domain).
                    845:     #   loncapaCAcrl.pem ($filename eq loncapaCAcrl).
1.141     foxr      846:     # Construct the destination filename or reject the request.
                    847:     #
                    848:     # lonManage is supposed to ensure this, however this session could be
                    849:     # part of some elaborate spoof that managed somehow to authenticate.
                    850:     #
                    851: 
1.169     foxr      852: 
                    853:     my $tablefile = ConfigFileFromSelector($filename);
                    854:     if(! (defined $tablefile)) {
1.141     foxr      855: 	return "refused";
                    856:     }
1.412     foxr      857: 
1.157     foxr      858:     #  If the file being pushed is the host file, we adjust the entry for ourself so that the
                    859:     #  IP will be our current IP as looked up in dns.  Note this is only 99% good as it's possible
                    860:     #  to conceive of conditions where we don't have a DNS entry locally.  This is possible in a 
                    861:     #  network sense but it doesn't make much sense in a LonCAPA sense so we ignore (for now)
                    862:     #  that possibilty.
                    863: 
                    864:     if($filename eq "host") {
                    865: 	$contents = AdjustHostContents($contents);
1.549     raeburn   866:     } elsif (($filename eq 'dns_host') || ($filename eq 'dns_domain') ||
                    867:              ($filename eq 'loncapaCAcrl')) {
1.510     raeburn   868:         if ($contents eq '') {
                    869:             &logthis('<font color="red"> Pushfile: unable to install '
                    870:                     .$tablefile." - no data received from push. </font>");
                    871:             return 'error: push had no data';
                    872:         }
                    873:         if (&Apache::lonnet::get_host_ip($clientname)) {
                    874:             my $clienthost = &Apache::lonnet::hostname($clientname);
                    875:             if ($managers{$clientip} eq $clientname) {
                    876:                 my $clientprotocol = $Apache::lonnet::protocol{$clientname};
                    877:                 $clientprotocol = 'http' if ($clientprotocol ne 'https');
1.549     raeburn   878:                 my $url;
                    879:                 if ($filename eq 'loncapaCAcrl') {
                    880:                     $url = '/adm/dns/loncapaCRL';
                    881:                 } else {
                    882:                     $url = '/adm/'.$filename;
                    883:                     $url =~ s{_}{/};
                    884:                 }
1.510     raeburn   885:                 my $request=new HTTP::Request('GET',"$clientprotocol://$clienthost$url");
1.523     raeburn   886:                 my $response = LONCAPA::LWPReq::makerequest($clientname,$request,'',\%perlvar,60,0);
1.510     raeburn   887:                 if ($response->is_error()) {
                    888:                     &logthis('<font color="red"> Pushfile: unable to install '
                    889:                             .$tablefile." - error attempting to pull data. </font>");
                    890:                     return 'error: pull failed';
                    891:                 } else {
                    892:                     my $result = $response->content;
                    893:                     chomp($result);
                    894:                     unless ($result eq $contents) {
                    895:                         &logthis('<font color="red"> Pushfile: unable to install '
                    896:                                 .$tablefile." - pushed data and pulled data differ. </font>");
                    897:                         my $pushleng = length($contents);
                    898:                         my $pullleng = length($result);
                    899:                         if ($pushleng != $pullleng) {
                    900:                             return "error: $pushleng vs $pullleng bytes";
                    901:                         } else {
                    902:                             return "error: mismatch push and pull";
                    903:                         }
                    904:                     }
                    905:                 }
                    906:             }
                    907:         }
1.157     foxr      908:     }
                    909: 
1.141     foxr      910:     #  Install the new file:
                    911: 
1.412     foxr      912:     &logthis("Installing new $tablefile contents:\n$contents");
1.143     foxr      913:     if(!InstallFile($tablefile, $contents)) {
                    914: 	&logthis('<font color="red"> Pushfile: unable to install '
1.145     foxr      915: 	 .$tablefile." $! </font>");
1.143     foxr      916: 	return "error:$!";
1.224     foxr      917:     } else {
1.143     foxr      918: 	&logthis('<font color="green"> Installed new '.$tablefile
1.473     raeburn   919: 		 ." - transaction by: $clientname ($clientip)</font>");
1.472     raeburn   920:         my $adminmail = $perlvar{'lonAdmEMail'};
                    921:         my $admindom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                    922:         if ($admindom ne '') {
                    923:             my %domconfig =
                    924:                 &Apache::lonnet::get_dom('configuration',['contacts'],$admindom);
                    925:             if (ref($domconfig{'contacts'}) eq 'HASH') {
                    926:                 if ($domconfig{'contacts'}{'adminemail'} ne '') {
                    927:                     $adminmail = $domconfig{'contacts'}{'adminemail'};
                    928:                 }
                    929:             }
                    930:         }
                    931:         if ($adminmail =~ /^[^\@]+\@[^\@]+$/) {
                    932:             my $msg = new Mail::Send;
                    933:             $msg->to($adminmail);
                    934:             $msg->subject('LON-CAPA DNS update on '.$perlvar{'lonHostID'});
                    935:             $msg->add('Content-type','text/plain; charset=UTF-8');
                    936:             if (my $fh = $msg->open()) {
                    937:                 print $fh 'Update to '.$tablefile.' from Cluster Manager '.
1.473     raeburn   938:                           "$clientname ($clientip)\n";
1.472     raeburn   939:                 $fh->close;
                    940:             }
                    941:         }
1.143     foxr      942:     }
                    943: 
1.141     foxr      944:     #  Indicate success:
                    945:  
                    946:     return "ok";
                    947: 
                    948: }
1.145     foxr      949: 
                    950: #
                    951: #  Called to re-init either lonc or lond.
                    952: #
                    953: #  Parameters:
                    954: #    request   - The full request by the client.  This is of the form
                    955: #                reinit:<process>  
                    956: #                where <process> is allowed to be either of 
                    957: #                lonc or lond
                    958: #
                    959: #  Returns:
                    960: #     The string to be sent back to the client either:
                    961: #   ok         - Everything worked just fine.
                    962: #   error:why  - There was a failure and why describes the reason.
                    963: #
                    964: #
                    965: sub ReinitProcess {
                    966:     my $request = shift;
                    967: 
1.146     foxr      968: 
                    969:     # separate the request (reinit) from the process identifier and
                    970:     # validate it producing the name of the .pid file for the process.
                    971:     #
                    972:     #
                    973:     my ($junk, $process) = split(":", $request);
1.147     foxr      974:     my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
1.146     foxr      975:     if($process eq 'lonc') {
                    976: 	$processpidfile = $processpidfile."lonc.pid";
1.147     foxr      977: 	if (!open(PIDFILE, "< $processpidfile")) {
                    978: 	    return "error:Open failed for $processpidfile";
                    979: 	}
                    980: 	my $loncpid = <PIDFILE>;
                    981: 	close(PIDFILE);
                    982: 	logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
                    983: 		."</font>");
                    984: 	kill("USR2", $loncpid);
1.146     foxr      985:     } elsif ($process eq 'lond') {
1.147     foxr      986: 	logthis('<font color="red"> Reinitializing self (lond) </font>');
                    987: 	&UpdateHosts;			# Lond is us!!
1.146     foxr      988:     } else {
                    989: 	&logthis('<font color="yellow" Invalid reinit request for '.$process
                    990: 		 ."</font>");
                    991: 	return "error:Invalid process identifier $process";
                    992:     }
1.145     foxr      993:     return 'ok';
                    994: }
1.168     foxr      995: #   Validate a line in a configuration file edit script:
                    996: #   Validation includes:
                    997: #     - Ensuring the command is valid.
                    998: #     - Ensuring the command has sufficient parameters
                    999: #   Parameters:
                   1000: #     scriptline - A line to validate (\n has been stripped for what it's worth).
1.167     foxr     1001: #
1.168     foxr     1002: #   Return:
                   1003: #      0     - Invalid scriptline.
                   1004: #      1     - Valid scriptline
                   1005: #  NOTE:
                   1006: #     Only the command syntax is checked, not the executability of the
                   1007: #     command.
                   1008: #
                   1009: sub isValidEditCommand {
                   1010:     my $scriptline = shift;
                   1011: 
                   1012:     #   Line elements are pipe separated:
                   1013: 
                   1014:     my ($command, $key, $newline)  = split(/\|/, $scriptline);
                   1015:     &logthis('<font color="green"> isValideditCommand checking: '.
                   1016: 	     "Command = '$command', Key = '$key', Newline = '$newline' </font>\n");
                   1017:     
                   1018:     if ($command eq "delete") {
                   1019: 	#
                   1020: 	#   key with no newline.
                   1021: 	#
                   1022: 	if( ($key eq "") || ($newline ne "")) {
                   1023: 	    return 0;		# Must have key but no newline.
                   1024: 	} else {
                   1025: 	    return 1;		# Valid syntax.
                   1026: 	}
1.169     foxr     1027:     } elsif ($command eq "replace") {
1.168     foxr     1028: 	#
                   1029: 	#   key and newline:
                   1030: 	#
                   1031: 	if (($key eq "") || ($newline eq "")) {
                   1032: 	    return 0;
                   1033: 	} else {
                   1034: 	    return 1;
                   1035: 	}
1.169     foxr     1036:     } elsif ($command eq "append") {
                   1037: 	if (($key ne "") && ($newline eq "")) {
                   1038: 	    return 1;
                   1039: 	} else {
                   1040: 	    return 0;
                   1041: 	}
1.168     foxr     1042:     } else {
                   1043: 	return 0;		# Invalid command.
                   1044:     }
                   1045:     return 0;			# Should not get here!!!
                   1046: }
1.169     foxr     1047: #
                   1048: #   ApplyEdit - Applies an edit command to a line in a configuration 
                   1049: #               file.  It is the caller's responsiblity to validate the
                   1050: #               edit line.
                   1051: #   Parameters:
                   1052: #      $directive - A single edit directive to apply.  
                   1053: #                   Edit directives are of the form:
                   1054: #                  append|newline      - Appends a new line to the file.
                   1055: #                  replace|key|newline - Replaces the line with key value 'key'
                   1056: #                  delete|key          - Deletes the line with key value 'key'.
                   1057: #      $editor   - A config file editor object that contains the
                   1058: #                  file being edited.
                   1059: #
                   1060: sub ApplyEdit {
1.192     foxr     1061: 
                   1062:     my ($directive, $editor) = @_;
1.169     foxr     1063: 
                   1064:     # Break the directive down into its command and its parameters
                   1065:     # (at most two at this point.  The meaning of the parameters, if in fact
                   1066:     #  they exist depends on the command).
                   1067: 
                   1068:     my ($command, $p1, $p2) = split(/\|/, $directive);
                   1069: 
                   1070:     if($command eq "append") {
                   1071: 	$editor->Append($p1);	          # p1 - key p2 null.
                   1072:     } elsif ($command eq "replace") {
                   1073: 	$editor->ReplaceLine($p1, $p2);   # p1 - key p2 = newline.
                   1074:     } elsif ($command eq "delete") {
                   1075: 	$editor->DeleteLine($p1);         # p1 - key p2 null.
                   1076:     } else {			          # Should not get here!!!
                   1077: 	die "Invalid command given to ApplyEdit $command"
                   1078:     }
                   1079: }
                   1080: #
                   1081: # AdjustOurHost:
                   1082: #           Adjusts a host file stored in a configuration file editor object
                   1083: #           for the true IP address of this host. This is necessary for hosts
                   1084: #           that live behind a firewall.
                   1085: #           Those hosts have a publicly distributed IP of the firewall, but
                   1086: #           internally must use their actual IP.  We assume that a given
                   1087: #           host only has a single IP interface for now.
                   1088: # Formal Parameters:
                   1089: #     editor   - The configuration file editor to adjust.  This
                   1090: #                editor is assumed to contain a hosts.tab file.
                   1091: # Strategy:
                   1092: #    - Figure out our hostname.
                   1093: #    - Lookup the entry for this host.
                   1094: #    - Modify the line to contain our IP
                   1095: #    - Do a replace for this host.
                   1096: sub AdjustOurHost {
                   1097:     my $editor        = shift;
                   1098: 
                   1099:     # figure out who I am.
                   1100: 
                   1101:     my $myHostName    = $perlvar{'lonHostID'}; # LonCAPA hostname.
                   1102: 
                   1103:     #  Get my host file entry.
                   1104: 
                   1105:     my $ConfigLine    = $editor->Find($myHostName);
                   1106:     if(! (defined $ConfigLine)) {
                   1107: 	die "AdjustOurHost - no entry for me in hosts file $myHostName";
                   1108:     }
                   1109:     # figure out my IP:
                   1110:     #   Use the config line to get my hostname.
                   1111:     #   Use gethostbyname to translate that into an IP address.
                   1112:     #
1.338     albertel 1113:     my ($id,$domain,$role,$name,$maxcon,$idleto,$mincon) = split(/:/,$ConfigLine);
1.169     foxr     1114:     #
                   1115:     #  Reassemble the config line from the elements in the list.
                   1116:     #  Note that if the loncnew items were not present before, they will
                   1117:     #  be now even if they would be empty
                   1118:     #
                   1119:     my $newConfigLine = $id;
1.338     albertel 1120:     foreach my $item ($domain, $role, $name, $maxcon, $idleto, $mincon) {
1.169     foxr     1121: 	$newConfigLine .= ":".$item;
                   1122:     }
                   1123:     #  Replace the line:
                   1124: 
                   1125:     $editor->ReplaceLine($id, $newConfigLine);
                   1126:     
                   1127: }
                   1128: #
                   1129: #   ReplaceConfigFile:
                   1130: #              Replaces a configuration file with the contents of a
                   1131: #              configuration file editor object.
                   1132: #              This is done by:
                   1133: #              - Copying the target file to <filename>.old
                   1134: #              - Writing the new file to <filename>.tmp
                   1135: #              - Moving <filename.tmp>  -> <filename>
                   1136: #              This laborious process ensures that the system is never without
                   1137: #              a configuration file that's at least valid (even if the contents
                   1138: #              may be dated).
                   1139: #   Parameters:
                   1140: #        filename   - Name of the file to modify... this is a full path.
                   1141: #        editor     - Editor containing the file.
                   1142: #
                   1143: sub ReplaceConfigFile {
1.192     foxr     1144:     
                   1145:     my ($filename, $editor) = @_;
1.168     foxr     1146: 
1.169     foxr     1147:     CopyFile ($filename, $filename.".old");
                   1148: 
                   1149:     my $contents  = $editor->Get(); # Get the contents of the file.
                   1150: 
                   1151:     InstallFile($filename, $contents);
                   1152: }
1.168     foxr     1153: #   
                   1154: #
                   1155: #   Called to edit a configuration table  file
1.167     foxr     1156: #   Parameters:
                   1157: #      request           - The entire command/request sent by lonc or lonManage
                   1158: #   Return:
                   1159: #      The reply to send to the client.
1.168     foxr     1160: #
1.167     foxr     1161: sub EditFile {
                   1162:     my $request = shift;
                   1163: 
                   1164:     #  Split the command into it's pieces:  edit:filetype:script
                   1165: 
1.339     albertel 1166:     my ($cmd, $filetype, $script) = split(/:/, $request,3);	# : in script
1.167     foxr     1167: 
                   1168:     #  Check the pre-coditions for success:
                   1169: 
1.339     albertel 1170:     if($cmd != "edit") {	# Something is amiss afoot alack.
1.167     foxr     1171: 	return "error:edit request detected, but request != 'edit'\n";
                   1172:     }
                   1173:     if( ($filetype ne "hosts")  &&
                   1174: 	($filetype ne "domain")) {
                   1175: 	return "error:edit requested with invalid file specifier: $filetype \n";
                   1176:     }
                   1177: 
                   1178:     #   Split the edit script and check it's validity.
1.168     foxr     1179: 
                   1180:     my @scriptlines = split(/\n/, $script);  # one line per element.
                   1181:     my $linecount   = scalar(@scriptlines);
                   1182:     for(my $i = 0; $i < $linecount; $i++) {
                   1183: 	chomp($scriptlines[$i]);
                   1184: 	if(!isValidEditCommand($scriptlines[$i])) {
                   1185: 	    return "error:edit with bad script line: '$scriptlines[$i]' \n";
                   1186: 	}
                   1187:     }
1.145     foxr     1188: 
1.167     foxr     1189:     #   Execute the edit operation.
1.169     foxr     1190:     #   - Create a config file editor for the appropriate file and 
                   1191:     #   - execute each command in the script:
                   1192:     #
                   1193:     my $configfile = ConfigFileFromSelector($filetype);
                   1194:     if (!(defined $configfile)) {
                   1195: 	return "refused\n";
                   1196:     }
                   1197:     my $editor = ConfigFileEdit->new($configfile);
1.167     foxr     1198: 
1.169     foxr     1199:     for (my $i = 0; $i < $linecount; $i++) {
                   1200: 	ApplyEdit($scriptlines[$i], $editor);
                   1201:     }
                   1202:     # If the file is the host file, ensure that our host is
                   1203:     # adjusted to have our ip:
                   1204:     #
                   1205:     if($filetype eq "host") {
                   1206: 	AdjustOurHost($editor);
                   1207:     }
                   1208:     #  Finally replace the current file with our file.
                   1209:     #
                   1210:     ReplaceConfigFile($configfile, $editor);
1.167     foxr     1211: 
                   1212:     return "ok\n";
                   1213: }
1.207     foxr     1214: 
1.255     foxr     1215: #   read_profile
                   1216: #
                   1217: #   Returns a set of specific entries from a user's profile file.
                   1218: #   this is a utility function that is used by both get_profile_entry and
                   1219: #   get_profile_entry_encrypted.
                   1220: #
                   1221: # Parameters:
                   1222: #    udom       - Domain in which the user exists.
                   1223: #    uname      - User's account name (loncapa account)
                   1224: #    namespace  - The profile namespace to open.
                   1225: #    what       - A set of & separated queries.
                   1226: # Returns:
                   1227: #    If all ok: - The string that needs to be shipped back to the user.
                   1228: #    If failure - A string that starts with error: followed by the failure
                   1229: #                 reason.. note that this probabyl gets shipped back to the
                   1230: #                 user as well.
                   1231: #
                   1232: sub read_profile {
                   1233:     my ($udom, $uname, $namespace, $what) = @_;
                   1234:     
                   1235:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   1236: 				 &GDBM_READER());
                   1237:     if ($hashref) {
                   1238:         my @queries=split(/\&/,$what);
1.440     raeburn  1239:         if ($namespace eq 'roles') {
                   1240:             @queries = map { &unescape($_); } @queries; 
                   1241:         }
1.255     foxr     1242:         my $qresult='';
                   1243: 	
                   1244: 	for (my $i=0;$i<=$#queries;$i++) {
                   1245: 	    $qresult.="$hashref->{$queries[$i]}&";    # Presumably failure gives empty string.
                   1246: 	}
                   1247: 	$qresult=~s/\&$//;              # Remove trailing & from last lookup.
1.311     albertel 1248: 	if (&untie_user_hash($hashref)) {
1.255     foxr     1249: 	    return $qresult;
                   1250: 	} else {
                   1251: 	    return "error: ".($!+0)." untie (GDBM) Failed";
                   1252: 	}
                   1253:     } else {
                   1254: 	if ($!+0 == 2) {
                   1255: 	    return "error:No such file or GDBM reported bad block error";
                   1256: 	} else {
                   1257: 	    return "error: ".($!+0)." tie (GDBM) Failed";
                   1258: 	}
                   1259:     }
                   1260: 
                   1261: }
1.214     foxr     1262: #--------------------- Request Handlers --------------------------------------------
                   1263: #
1.215     foxr     1264: #   By convention each request handler registers itself prior to the sub 
                   1265: #   declaration:
1.214     foxr     1266: #
                   1267: 
1.216     foxr     1268: #++
                   1269: #
1.214     foxr     1270: #  Handles ping requests.
                   1271: #  Parameters:
                   1272: #      $cmd    - the actual keyword that invoked us.
                   1273: #      $tail   - the tail of the request that invoked us.
                   1274: #      $replyfd- File descriptor connected to the client
                   1275: #  Implicit Inputs:
                   1276: #      $currenthostid - Global variable that carries the name of the host we are
                   1277: #                       known as.
                   1278: #  Returns:
                   1279: #      1       - Ok to continue processing.
                   1280: #      0       - Program should exit.
                   1281: #  Side effects:
                   1282: #      Reply information is sent to the client.
                   1283: sub ping_handler {
                   1284:     my ($cmd, $tail, $client) = @_;
                   1285:     Debug("$cmd $tail $client .. $currenthostid:");
                   1286:    
1.387     albertel 1287:     Reply( $client,\$currenthostid,"$cmd:$tail");
1.214     foxr     1288:    
                   1289:     return 1;
                   1290: }
                   1291: &register_handler("ping", \&ping_handler, 0, 1, 1);       # Ping unencoded, client or manager.
                   1292: 
1.216     foxr     1293: #++
1.215     foxr     1294: #
                   1295: # Handles pong requests.  Pong replies with our current host id, and
                   1296: #                         the results of a ping sent to us via our lonc.
                   1297: #
                   1298: # Parameters:
                   1299: #      $cmd    - the actual keyword that invoked us.
                   1300: #      $tail   - the tail of the request that invoked us.
                   1301: #      $replyfd- File descriptor connected to the client
                   1302: #  Implicit Inputs:
                   1303: #      $currenthostid - Global variable that carries the name of the host we are
                   1304: #                       connected to.
                   1305: #  Returns:
                   1306: #      1       - Ok to continue processing.
                   1307: #      0       - Program should exit.
                   1308: #  Side effects:
                   1309: #      Reply information is sent to the client.
                   1310: sub pong_handler {
                   1311:     my ($cmd, $tail, $replyfd) = @_;
                   1312: 
1.365     albertel 1313:     my $reply=&Apache::lonnet::reply("ping",$clientname);
1.215     foxr     1314:     &Reply( $replyfd, "$currenthostid:$reply\n", "$cmd:$tail"); 
                   1315:     return 1;
                   1316: }
                   1317: &register_handler("pong", \&pong_handler, 0, 1, 1);       # Pong unencoded, client or manager
                   1318: 
1.216     foxr     1319: #++
                   1320: #      Called to establish an encrypted session key with the remote client.
                   1321: #      Note that with secure lond, in most cases this function is never
                   1322: #      invoked.  Instead, the secure session key is established either
                   1323: #      via a local file that's locked down tight and only lives for a short
                   1324: #      time, or via an ssl tunnel...and is generated from a bunch-o-random
                   1325: #      bits from /dev/urandom, rather than the predictable pattern used by
                   1326: #      by this sub.  This sub is only used in the old-style insecure
                   1327: #      key negotiation.
                   1328: # Parameters:
                   1329: #      $cmd    - the actual keyword that invoked us.
                   1330: #      $tail   - the tail of the request that invoked us.
                   1331: #      $replyfd- File descriptor connected to the client
                   1332: #  Implicit Inputs:
                   1333: #      $currenthostid - Global variable that carries the name of the host
                   1334: #                       known as.
1.448     raeburn  1335: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.216     foxr     1336: #  Returns:
                   1337: #      1       - Ok to continue processing.
                   1338: #      0       - Program should exit.
                   1339: #  Implicit Outputs:
                   1340: #      Reply information is sent to the client.
                   1341: #      $cipher is set with a reference to a new IDEA encryption object.
                   1342: #
                   1343: sub establish_key_handler {
                   1344:     my ($cmd, $tail, $replyfd) = @_;
                   1345: 
                   1346:     my $buildkey=time.$$.int(rand 100000);
                   1347:     $buildkey=~tr/1-6/A-F/;
                   1348:     $buildkey=int(rand 100000).$buildkey.int(rand 100000);
                   1349:     my $key=$currenthostid.$clientname;
                   1350:     $key=~tr/a-z/A-Z/;
                   1351:     $key=~tr/G-P/0-9/;
                   1352:     $key=~tr/Q-Z/0-9/;
                   1353:     $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
                   1354:     $key=substr($key,0,32);
                   1355:     my $cipherkey=pack("H32",$key);
                   1356:     $cipher=new IDEA $cipherkey;
1.387     albertel 1357:     &Reply($replyfd, \$buildkey, "$cmd:$tail"); 
1.216     foxr     1358:    
                   1359:     return 1;
                   1360: 
                   1361: }
                   1362: &register_handler("ekey", \&establish_key_handler, 0, 1,1);
                   1363: 
1.217     foxr     1364: #     Handler for the load command.  Returns the current system load average
                   1365: #     to the requestor.
                   1366: #
                   1367: # Parameters:
                   1368: #      $cmd    - the actual keyword that invoked us.
                   1369: #      $tail   - the tail of the request that invoked us.
                   1370: #      $replyfd- File descriptor connected to the client
                   1371: #  Implicit Inputs:
                   1372: #      $currenthostid - Global variable that carries the name of the host
                   1373: #                       known as.
1.448     raeburn  1374: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.217     foxr     1375: #  Returns:
                   1376: #      1       - Ok to continue processing.
                   1377: #      0       - Program should exit.
                   1378: #  Side effects:
                   1379: #      Reply information is sent to the client.
                   1380: sub load_handler {
                   1381:     my ($cmd, $tail, $replyfd) = @_;
                   1382: 
1.463     foxr     1383: 
                   1384: 
1.217     foxr     1385:    # Get the load average from /proc/loadavg and calculate it as a percentage of
                   1386:    # the allowed load limit as set by the perl global variable lonLoadLim
                   1387: 
                   1388:     my $loadavg;
                   1389:     my $loadfile=IO::File->new('/proc/loadavg');
                   1390:    
                   1391:     $loadavg=<$loadfile>;
                   1392:     $loadavg =~ s/\s.*//g;                      # Extract the first field only.
                   1393:    
                   1394:     my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
                   1395: 
1.387     albertel 1396:     &Reply( $replyfd, \$loadpercent, "$cmd:$tail");
1.217     foxr     1397:    
                   1398:     return 1;
                   1399: }
1.263     albertel 1400: &register_handler("load", \&load_handler, 0, 1, 0);
1.217     foxr     1401: 
                   1402: #
                   1403: #   Process the userload request.  This sub returns to the client the current
                   1404: #  user load average.  It can be invoked either by clients or managers.
                   1405: #
                   1406: # Parameters:
                   1407: #      $cmd    - the actual keyword that invoked us.
                   1408: #      $tail   - the tail of the request that invoked us.
                   1409: #      $replyfd- File descriptor connected to the client
                   1410: #  Implicit Inputs:
                   1411: #      $currenthostid - Global variable that carries the name of the host
                   1412: #                       known as.
1.448     raeburn  1413: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.217     foxr     1414: #  Returns:
                   1415: #      1       - Ok to continue processing.
                   1416: #      0       - Program should exit
                   1417: # Implicit inputs:
                   1418: #     whatever the userload() function requires.
                   1419: #  Implicit outputs:
                   1420: #     the reply is written to the client.
                   1421: #
                   1422: sub user_load_handler {
                   1423:     my ($cmd, $tail, $replyfd) = @_;
                   1424: 
1.365     albertel 1425:     my $userloadpercent=&Apache::lonnet::userload();
1.387     albertel 1426:     &Reply($replyfd, \$userloadpercent, "$cmd:$tail");
1.217     foxr     1427:     
                   1428:     return 1;
                   1429: }
1.263     albertel 1430: &register_handler("userload", \&user_load_handler, 0, 1, 0);
1.217     foxr     1431: 
1.218     foxr     1432: #   Process a request for the authorization type of a user:
                   1433: #   (userauth).
                   1434: #
                   1435: # Parameters:
                   1436: #      $cmd    - the actual keyword that invoked us.
                   1437: #      $tail   - the tail of the request that invoked us.
                   1438: #      $replyfd- File descriptor connected to the client
                   1439: #  Returns:
                   1440: #      1       - Ok to continue processing.
                   1441: #      0       - Program should exit
                   1442: # Implicit outputs:
                   1443: #    The user authorization type is written to the client.
                   1444: #
                   1445: sub user_authorization_type {
                   1446:     my ($cmd, $tail, $replyfd) = @_;
                   1447:    
                   1448:     my $userinput = "$cmd:$tail";
                   1449:    
                   1450:     #  Pull the domain and username out of the command tail.
1.222     foxr     1451:     # and call get_auth_type to determine the authentication type.
1.218     foxr     1452:    
                   1453:     my ($udom,$uname)=split(/:/,$tail);
1.222     foxr     1454:     my $result = &get_auth_type($udom, $uname);
1.218     foxr     1455:     if($result eq "nouser") {
                   1456: 	&Failure( $replyfd, "unknown_user\n", $userinput);
                   1457:     } else {
                   1458: 	#
1.222     foxr     1459: 	# We only want to pass the second field from get_auth_type
1.218     foxr     1460: 	# for ^krb.. otherwise we'll be handing out the encrypted
                   1461: 	# password for internals e.g.
                   1462: 	#
                   1463: 	my ($type,$otherinfo) = split(/:/,$result);
                   1464: 	if($type =~ /^krb/) {
                   1465: 	    $type = $result;
1.269     raeburn  1466: 	} else {
                   1467:             $type .= ':';
                   1468:         }
1.387     albertel 1469: 	&Reply( $replyfd, \$type, $userinput);
1.218     foxr     1470:     }
                   1471:   
                   1472:     return 1;
                   1473: }
                   1474: &register_handler("currentauth", \&user_authorization_type, 1, 1, 0);
                   1475: 
                   1476: #   Process a request by a manager to push a hosts or domain table 
                   1477: #   to us.  We pick apart the command and pass it on to the subs
                   1478: #   that already exist to do this.
                   1479: #
                   1480: # Parameters:
                   1481: #      $cmd    - the actual keyword that invoked us.
                   1482: #      $tail   - the tail of the request that invoked us.
                   1483: #      $client - File descriptor connected to the client
                   1484: #  Returns:
                   1485: #      1       - Ok to continue processing.
                   1486: #      0       - Program should exit
                   1487: # Implicit Output:
                   1488: #    a reply is written to the client.
                   1489: sub push_file_handler {
                   1490:     my ($cmd, $tail, $client) = @_;
1.412     foxr     1491:     &Debug("In push file handler");
1.218     foxr     1492:     my $userinput = "$cmd:$tail";
                   1493: 
                   1494:     # At this time we only know that the IP of our partner is a valid manager
                   1495:     # the code below is a hook to do further authentication (e.g. to resolve
                   1496:     # spoofing).
                   1497: 
                   1498:     my $cert = &GetCertificate($userinput);
1.412     foxr     1499:     if(&ValidManager($cert)) {
                   1500: 	&Debug("Valid manager: $client");
1.218     foxr     1501: 
                   1502: 	# Now presumably we have the bona fides of both the peer host and the
                   1503: 	# process making the request.
                   1504:       
                   1505: 	my $reply = &PushFile($userinput);
1.387     albertel 1506: 	&Reply($client, \$reply, $userinput);
1.218     foxr     1507: 
                   1508:     } else {
1.412     foxr     1509: 	&logthis("push_file_handler $client is not valid");
1.218     foxr     1510: 	&Failure( $client, "refused\n", $userinput);
                   1511:     } 
1.219     foxr     1512:     return 1;
1.218     foxr     1513: }
                   1514: &register_handler("pushfile", \&push_file_handler, 1, 0, 1);
                   1515: 
1.399     raeburn  1516: # The du_handler routine should be considered obsolete and is retained
                   1517: # for communication with legacy servers.  Please see the du2_handler.
1.243     banghart 1518: #
1.399     raeburn  1519: #   du  - list the disk usage of a directory recursively. 
1.243     banghart 1520: #    
                   1521: #   note: stolen code from the ls file handler
                   1522: #   under construction by Rick Banghart 
                   1523: #    .
                   1524: # Parameters:
                   1525: #    $cmd        - The command that dispatched us (du).
                   1526: #    $ududir     - The directory path to list... I'm not sure what this
                   1527: #                  is relative as things like ls:. return e.g.
                   1528: #                  no_such_dir.
                   1529: #    $client     - Socket open on the client.
                   1530: # Returns:
                   1531: #     1 - indicating that the daemon should not disconnect.
                   1532: # Side Effects:
                   1533: #   The reply is written to  $client.
                   1534: #
                   1535: sub du_handler {
                   1536:     my ($cmd, $ududir, $client) = @_;
1.339     albertel 1537:     ($ududir) = split(/:/,$ududir); # Make 'telnet' testing easier.
1.251     foxr     1538:     my $userinput = "$cmd:$ududir";
                   1539: 
1.245     albertel 1540:     if ($ududir=~/\.\./ || $ududir!~m|^/home/httpd/|) {
                   1541: 	&Failure($client,"refused\n","$cmd:$ududir");
                   1542: 	return 1;
                   1543:     }
1.249     foxr     1544:     #  Since $ududir could have some nasties in it,
                   1545:     #  we will require that ududir is a valid
                   1546:     #  directory.  Just in case someone tries to
                   1547:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
                   1548:     #  etc.
                   1549:     #
                   1550:     if (-d $ududir) {
1.292     albertel 1551: 	my $total_size=0;
                   1552: 	my $code=sub { 
                   1553: 	    if ($_=~/\.\d+\./) { return;} 
                   1554: 	    if ($_=~/\.meta$/) { return;}
1.362     albertel 1555: 	    if (-d $_)         { return;}
1.292     albertel 1556: 	    $total_size+=(stat($_))[7];
                   1557: 	};
1.295     raeburn  1558: 	chdir($ududir);
1.292     albertel 1559: 	find($code,$ududir);
                   1560: 	$total_size=int($total_size/1024);
1.387     albertel 1561: 	&Reply($client,\$total_size,"$cmd:$ududir");
1.249     foxr     1562:     } else {
1.251     foxr     1563: 	&Failure($client, "bad_directory:$ududir\n","$cmd:$ududir"); 
1.249     foxr     1564:     }
1.243     banghart 1565:     return 1;
                   1566: }
                   1567: &register_handler("du", \&du_handler, 0, 1, 0);
1.218     foxr     1568: 
1.399     raeburn  1569: # Please also see the du_handler, which is obsoleted by du2. 
                   1570: # du2_handler differs from du_handler in that required path to directory
                   1571: # provided by &propath() is prepended in the handler instead of on the 
                   1572: # client side.
1.239     foxr     1573: #
1.399     raeburn  1574: #   du2  - list the disk usage of a directory recursively.
                   1575: #
                   1576: # Parameters:
                   1577: #    $cmd        - The command that dispatched us (du).
                   1578: #    $tail       - The tail of the request that invoked us.
                   1579: #                  $tail is a : separated list of the following:
                   1580: #                   - $ududir - directory path to list (before prepending)
                   1581: #                   - $getpropath = 1 if &propath() should prepend
                   1582: #                   - $uname - username to use for &propath or user dir
                   1583: #                   - $udom - domain to use for &propath or user dir
                   1584: #                   All are escaped.
                   1585: #    $client     - Socket open on the client.
                   1586: # Returns:
                   1587: #     1 - indicating that the daemon should not disconnect.
                   1588: # Side Effects:
                   1589: #   The reply is written to $client.
                   1590: #
                   1591: 
                   1592: sub du2_handler {
                   1593:     my ($cmd, $tail, $client) = @_;
                   1594:     my ($ududir,$getpropath,$uname,$udom) = map { &unescape($_) } (split(/:/, $tail));
                   1595:     my $userinput = "$cmd:$tail";
                   1596:     if (($ududir=~/\.\./) || (($ududir!~m|^/home/httpd/|) && (!$getpropath))) {
                   1597:         &Failure($client,"refused\n","$cmd:$tail");
                   1598:         return 1;
                   1599:     }
                   1600:     if ($getpropath) {
                   1601:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
                   1602:             $ududir = &propath($udom,$uname).'/'.$ududir;
                   1603:         } else {
                   1604:             &Failure($client,"refused\n","$cmd:$tail");
                   1605:             return 1;
                   1606:         }
                   1607:     }
                   1608:     #  Since $ududir could have some nasties in it,
                   1609:     #  we will require that ududir is a valid
                   1610:     #  directory.  Just in case someone tries to
                   1611:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
                   1612:     #  etc.
                   1613:     #
                   1614:     if (-d $ududir) {
                   1615:         my $total_size=0;
                   1616:         my $code=sub {
                   1617:             if ($_=~/\.\d+\./) { return;}
                   1618:             if ($_=~/\.meta$/) { return;}
                   1619:             if (-d $_)         { return;}
                   1620:             $total_size+=(stat($_))[7];
                   1621:         };
                   1622:         chdir($ududir);
                   1623:         find($code,$ududir);
                   1624:         $total_size=int($total_size/1024);
                   1625:         &Reply($client,\$total_size,"$cmd:$ududir");
                   1626:     } else {
                   1627:         &Failure($client, "bad_directory:$ududir\n","$cmd:$tail");
                   1628:     }
                   1629:     return 1;
                   1630: }
                   1631: &register_handler("du2", \&du2_handler, 0, 1, 0);
                   1632: 
                   1633: #
                   1634: # The ls_handler routine should be considered obsolete and is retained
                   1635: # for communication with legacy servers.  Please see the ls3_handler.
1.280     matthew  1636: #
1.239     foxr     1637: #   ls  - list the contents of a directory.  For each file in the
                   1638: #    selected directory the filename followed by the full output of
                   1639: #    the stat function is returned.  The returned info for each
                   1640: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1641: #
                   1642: #    If the requested path contains /../ or is:
                   1643: #
                   1644: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1645: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1646: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1647: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
                   1648: #    or is:
                   1649: #
1.538     raeburn  1650: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1651: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1652: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1653: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
1.529     raeburn  1654: #
                   1655: #    the response will be "refused".
                   1656: #
1.239     foxr     1657: # Parameters:
                   1658: #    $cmd        - The command that dispatched us (ls).
                   1659: #    $ulsdir     - The directory path to list... I'm not sure what this
                   1660: #                  is relative as things like ls:. return e.g.
                   1661: #                  no_such_dir.
                   1662: #    $client     - Socket open on the client.
                   1663: # Returns:
                   1664: #     1 - indicating that the daemon should not disconnect.
                   1665: # Side Effects:
                   1666: #   The reply is written to  $client.
                   1667: #
                   1668: sub ls_handler {
1.280     matthew  1669:     # obsoleted by ls2_handler
1.239     foxr     1670:     my ($cmd, $ulsdir, $client) = @_;
                   1671: 
                   1672:     my $userinput = "$cmd:$ulsdir";
                   1673: 
                   1674:     my $obs;
                   1675:     my $rights;
                   1676:     my $ulsout='';
                   1677:     my $ulsfn;
1.529     raeburn  1678:     if ($ulsdir =~m{/\.\./}) {
                   1679:         &Failure($client,"refused\n",$userinput);
                   1680:         return 1;
                   1681:     }
1.239     foxr     1682:     if (-e $ulsdir) {
                   1683: 	if(-d $ulsdir) {
1.539     raeburn  1684:             unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1685:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
1.529     raeburn  1686:                 &Failure($client,"refused\n",$userinput);
                   1687:                 return 1;
                   1688:             }
1.239     foxr     1689: 	    if (opendir(LSDIR,$ulsdir)) {
                   1690: 		while ($ulsfn=readdir(LSDIR)) {
1.291     albertel 1691: 		    undef($obs);
                   1692: 		    undef($rights); 
1.239     foxr     1693: 		    my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1694: 		    #We do some obsolete checking here
                   1695: 		    if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   1696: 			open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1697: 			my @obsolete=<FILE>;
                   1698: 			foreach my $obsolete (@obsolete) {
1.301     www      1699: 			    if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
1.239     foxr     1700: 			    if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
                   1701: 			}
                   1702: 		    }
                   1703: 		    $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
                   1704: 		    if($obs eq '1') { $ulsout.="&1"; }
                   1705: 		    else { $ulsout.="&0"; }
                   1706: 		    if($rights eq '1') { $ulsout.="&1:"; }
                   1707: 		    else { $ulsout.="&0:"; }
                   1708: 		}
                   1709: 		closedir(LSDIR);
                   1710: 	    }
                   1711: 	} else {
1.539     raeburn  1712:             unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1713:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
1.529     raeburn  1714:                 &Failure($client,"refused\n",$userinput);
                   1715:                 return 1;
                   1716:             }
1.239     foxr     1717: 	    my @ulsstats=stat($ulsdir);
                   1718: 	    $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1719: 	}
                   1720:     } else {
                   1721: 	$ulsout='no_such_dir';
                   1722:     }
                   1723:     if ($ulsout eq '') { $ulsout='empty'; }
1.387     albertel 1724:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1.239     foxr     1725:     
                   1726:     return 1;
                   1727: 
                   1728: }
                   1729: &register_handler("ls", \&ls_handler, 0, 1, 0);
                   1730: 
1.399     raeburn  1731: # The ls2_handler routine should be considered obsolete and is retained
                   1732: # for communication with legacy servers.  Please see the ls3_handler.
                   1733: # Please also see the ls_handler, which was itself obsoleted by ls2.
1.280     matthew  1734: # ls2_handler differs from ls_handler in that it escapes its return 
                   1735: # values before concatenating them together with ':'s.
                   1736: #
                   1737: #   ls2  - list the contents of a directory.  For each file in the
                   1738: #    selected directory the filename followed by the full output of
                   1739: #    the stat function is returned.  The returned info for each
                   1740: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1741: #
                   1742: #    If the requested path contains /../ or is:
                   1743: #
                   1744: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1745: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1746: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1747: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
                   1748: #    or is:
                   1749: #
1.538     raeburn  1750: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1751: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1752: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1753: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
1.529     raeburn  1754: #
                   1755: #    the response will be "refused".
                   1756: #
1.280     matthew  1757: # Parameters:
                   1758: #    $cmd        - The command that dispatched us (ls).
                   1759: #    $ulsdir     - The directory path to list... I'm not sure what this
                   1760: #                  is relative as things like ls:. return e.g.
                   1761: #                  no_such_dir.
                   1762: #    $client     - Socket open on the client.
                   1763: # Returns:
                   1764: #     1 - indicating that the daemon should not disconnect.
                   1765: # Side Effects:
                   1766: #   The reply is written to  $client.
                   1767: #
                   1768: sub ls2_handler {
                   1769:     my ($cmd, $ulsdir, $client) = @_;
                   1770: 
                   1771:     my $userinput = "$cmd:$ulsdir";
                   1772: 
                   1773:     my $obs;
                   1774:     my $rights;
                   1775:     my $ulsout='';
                   1776:     my $ulsfn;
1.529     raeburn  1777:     if ($ulsdir =~m{/\.\./}) {
                   1778:         &Failure($client,"refused\n",$userinput);
                   1779:         return 1;
                   1780:     }
1.280     matthew  1781:     if (-e $ulsdir) {
                   1782:         if(-d $ulsdir) {
1.539     raeburn  1783:             unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1784:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
1.529     raeburn  1785:                 &Failure($client,"refused\n","$userinput");
                   1786:                 return 1;
                   1787:             }
1.280     matthew  1788:             if (opendir(LSDIR,$ulsdir)) {
                   1789:                 while ($ulsfn=readdir(LSDIR)) {
1.291     albertel 1790:                     undef($obs);
                   1791: 		    undef($rights); 
1.280     matthew  1792:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1793:                     #We do some obsolete checking here
                   1794:                     if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   1795:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1796:                         my @obsolete=<FILE>;
                   1797:                         foreach my $obsolete (@obsolete) {
1.301     www      1798:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
1.280     matthew  1799:                             if($obsolete =~ m|(<copyright>)(default)|) {
                   1800:                                 $rights = 1;
                   1801:                             }
                   1802:                         }
                   1803:                     }
                   1804:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
                   1805:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1806:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1807:                     $ulsout.= &escape($tmp).':';
                   1808:                 }
                   1809:                 closedir(LSDIR);
                   1810:             }
                   1811:         } else {
1.539     raeburn  1812:             unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1813:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
1.529     raeburn  1814:                 &Failure($client,"refused\n",$userinput);
                   1815:                 return 1;
                   1816:             }
1.280     matthew  1817:             my @ulsstats=stat($ulsdir);
                   1818:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1819:         }
                   1820:     } else {
                   1821:         $ulsout='no_such_dir';
                   1822:    }
                   1823:    if ($ulsout eq '') { $ulsout='empty'; }
1.387     albertel 1824:    &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1.280     matthew  1825:    return 1;
                   1826: }
                   1827: &register_handler("ls2", \&ls2_handler, 0, 1, 0);
1.399     raeburn  1828: #
                   1829: #   ls3  - list the contents of a directory.  For each file in the
                   1830: #    selected directory the filename followed by the full output of
                   1831: #    the stat function is returned.  The returned info for each
                   1832: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1833: #
                   1834: #    If the requested path (after prepending) contains /../ or is:
                   1835: #
                   1836: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1837: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1838: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1839: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
1.539     raeburn  1840: #        (d) /home/httpd/html/priv/<domain> and client is the homeserver
1.529     raeburn  1841: #
1.530     raeburn  1842: #    or is:
1.529     raeburn  1843: #
1.538     raeburn  1844: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1845: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1846: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1847: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
                   1848: #        (d) /home/httpd/html/priv/<domain>/<username>/ and client is the homeserver
1.529     raeburn  1849: #
                   1850: #    the response will be "refused".
                   1851: #
1.399     raeburn  1852: # Parameters:
                   1853: #    $cmd        - The command that dispatched us (ls).
                   1854: #    $tail       - The tail of the request that invoked us.
                   1855: #                  $tail is a : separated list of the following:
                   1856: #                   - $ulsdir - directory path to list (before prepending)
                   1857: #                   - $getpropath = 1 if &propath() should prepend
                   1858: #                   - $getuserdir = 1 if path to user dir in lonUsers should
                   1859: #                                     prepend
                   1860: #                   - $alternate_root - path to prepend
                   1861: #                   - $uname - username to use for &propath or user dir
                   1862: #                   - $udom - domain to use for &propath or user dir
                   1863: #            All of these except $getpropath and &getuserdir are escaped.    
                   1864: #                  no_such_dir.
                   1865: #    $client     - Socket open on the client.
                   1866: # Returns:
                   1867: #     1 - indicating that the daemon should not disconnect.
                   1868: # Side Effects:
                   1869: #   The reply is written to $client.
                   1870: #
                   1871: 
                   1872: sub ls3_handler {
                   1873:     my ($cmd, $tail, $client) = @_;
                   1874:     my $userinput = "$cmd:$tail";
                   1875:     my ($ulsdir,$getpropath,$getuserdir,$alternate_root,$uname,$udom) =
                   1876:         split(/:/,$tail);
                   1877:     if (defined($ulsdir)) {
                   1878:         $ulsdir = &unescape($ulsdir);
                   1879:     }
                   1880:     if (defined($alternate_root)) {
                   1881:         $alternate_root = &unescape($alternate_root);
                   1882:     }
                   1883:     if (defined($uname)) {
                   1884:         $uname = &unescape($uname);
                   1885:     }
                   1886:     if (defined($udom)) {
                   1887:         $udom = &unescape($udom);
                   1888:     }
                   1889: 
                   1890:     my $dir_root = $perlvar{'lonDocRoot'};
1.529     raeburn  1891:     if (($getpropath) || ($getuserdir)) {
1.399     raeburn  1892:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
                   1893:             $dir_root = &propath($udom,$uname);
                   1894:             $dir_root =~ s/\/$//;
                   1895:         } else {
1.529     raeburn  1896:             &Failure($client,"refused\n",$userinput);
1.399     raeburn  1897:             return 1;
                   1898:         }
1.400     raeburn  1899:     } elsif ($alternate_root ne '') {
1.399     raeburn  1900:         $dir_root = $alternate_root;
                   1901:     }
1.408     raeburn  1902:     if (($dir_root ne '') && ($dir_root ne '/')) {
1.400     raeburn  1903:         if ($ulsdir =~ /^\//) {
                   1904:             $ulsdir = $dir_root.$ulsdir;
                   1905:         } else {
                   1906:             $ulsdir = $dir_root.'/'.$ulsdir;
                   1907:         }
1.399     raeburn  1908:     }
1.529     raeburn  1909:     if ($ulsdir =~m{/\.\./}) {
                   1910:         &Failure($client,"refused\n",$userinput);
                   1911:         return 1;
                   1912:     }
                   1913:     my $islocal;
                   1914:     my @machine_ids = &Apache::lonnet::current_machine_ids();
                   1915:     if (grep(/^\Q$clientname\E$/,@machine_ids)) {
                   1916:         $islocal = 1;
                   1917:     }
1.399     raeburn  1918:     my $obs;
                   1919:     my $rights;
                   1920:     my $ulsout='';
                   1921:     my $ulsfn;
1.547     raeburn  1922: 
                   1923:     my ($crscheck,$toplevel,$currdom,$currnum,$skip);
                   1924:     unless ($islocal) {
                   1925:         my ($major,$minor) = split(/\./,$clientversion);
                   1926:         if (($major < 2) || ($major == 2 && $minor < 12)) {
                   1927:             $crscheck = 1;
                   1928:         }
                   1929:     }
1.399     raeburn  1930:     if (-e $ulsdir) {
                   1931:         if(-d $ulsdir) {
1.529     raeburn  1932:             unless (($getpropath) || ($getuserdir) ||
1.539     raeburn  1933:                     ($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1934:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles}) ||
                   1935:                     (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain}) && ($islocal))) {
1.529     raeburn  1936:                 &Failure($client,"refused\n",$userinput);
                   1937:                 return 1;
                   1938:             }
1.547     raeburn  1939:             if (($crscheck) &&
                   1940:                 ($ulsdir =~ m{^/home/httpd/html/res/($LONCAPA::match_domain)(/?$|/$LONCAPA::match_courseid)})) {
                   1941:                 ($currdom,my $posscnum) = ($1,$2);
                   1942:                 if (($posscnum eq '') || ($posscnum eq '/')) {
                   1943:                     $toplevel = 1;
                   1944:                 } else {
                   1945:                     $posscnum =~ s{^/+}{};
                   1946:                     if (&LONCAPA::Lond::is_course($currdom,$posscnum)) {
                   1947:                         $skip = 1;
                   1948:                     }
                   1949:                 }
                   1950:             }
                   1951:             if ((!$skip) && (opendir(LSDIR,$ulsdir))) {
1.399     raeburn  1952:                 while ($ulsfn=readdir(LSDIR)) {
1.547     raeburn  1953:                     if (($crscheck) && ($toplevel) && ($currdom ne '') &&
                   1954:                         ($ulsfn =~ /^$LONCAPA::match_courseid$/) && (-d "$ulsdir/$ulsfn")) {
                   1955:                         if (&LONCAPA::Lond::is_course($currdom,$ulsfn)) {
                   1956:                             next;
                   1957:                         }
                   1958:                     }
1.399     raeburn  1959:                     undef($obs);
                   1960:                     undef($rights);
                   1961:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1962:                     #We do some obsolete checking here
                   1963:                     if(-e $ulsdir.'/'.$ulsfn.".meta") {
                   1964:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1965:                         my @obsolete=<FILE>;
                   1966:                         foreach my $obsolete (@obsolete) {
                   1967:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; }
                   1968:                             if($obsolete =~ m|(<copyright>)(default)|) {
                   1969:                                 $rights = 1;
                   1970:                             }
                   1971:                         }
                   1972:                     }
                   1973:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
                   1974:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1975:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1976:                     $ulsout.= &escape($tmp).':';
                   1977:                 }
                   1978:                 closedir(LSDIR);
                   1979:             }
                   1980:         } else {
1.529     raeburn  1981:             unless (($getpropath) || ($getuserdir) ||
1.539     raeburn  1982:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1983:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/}) ||
                   1984:                     (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain/$LONCAPA::match_name/}) && ($islocal))) {
1.529     raeburn  1985:                 &Failure($client,"refused\n",$userinput);
                   1986:                 return 1;
                   1987:             }
1.399     raeburn  1988:             my @ulsstats=stat($ulsdir);
                   1989:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1990:         }
                   1991:     } else {
                   1992:         $ulsout='no_such_dir';
1.400     raeburn  1993:     }
                   1994:     if ($ulsout eq '') { $ulsout='empty'; }
                   1995:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
                   1996:     return 1;
1.399     raeburn  1997: }
                   1998: &register_handler("ls3", \&ls3_handler, 0, 1, 0);
1.280     matthew  1999: 
1.477     raeburn  2000: sub read_lonnet_global {
                   2001:     my ($cmd,$tail,$client) = @_;
                   2002:     my $userinput = "$cmd:$tail";
                   2003:     my $requested = &Apache::lonnet::thaw_unescape($tail);
                   2004:     my $result;
1.480     raeburn  2005:     my %packagevars = (
                   2006:                         spareid => \%Apache::lonnet::spareid,
                   2007:                         perlvar => \%Apache::lonnet::perlvar,
                   2008:                       );
                   2009:     my %limit_to = (
                   2010:                     perlvar => {
1.531     raeburn  2011:                                  lonOtherAuthen  => 1,
                   2012:                                  lonBalancer     => 1,
                   2013:                                  lonVersion      => 1,
                   2014:                                  lonAdmEMail     => 1,
                   2015:                                  lonSupportEMail => 1,  
                   2016:                                  lonSysEMail     => 1,
                   2017:                                  lonHostID       => 1,
                   2018:                                  lonRole         => 1,
                   2019:                                  lonDefDomain    => 1,
                   2020:                                  lonLoadLim      => 1,
                   2021:                                  lonUserLoadLim  => 1,
1.480     raeburn  2022:                                }
                   2023:                   );
1.477     raeburn  2024:     if (ref($requested) eq 'HASH') {
                   2025:         foreach my $what (keys(%{$requested})) {
                   2026:             my $response;
1.480     raeburn  2027:             my $items = {};
                   2028:             if (exists($packagevars{$what})) {
                   2029:                 if (ref($limit_to{$what}) eq 'HASH') {
                   2030:                     foreach my $varname (keys(%{$packagevars{$what}})) {
                   2031:                         if ($limit_to{$what}{$varname}) {
                   2032:                             $items->{$varname} = $packagevars{$what}{$varname};
                   2033:                         }
                   2034:                     }
                   2035:                 } else {
                   2036:                     $items = $packagevars{$what};
1.477     raeburn  2037:                 }
1.480     raeburn  2038:                 if ($what eq 'perlvar') {
                   2039:                     if (!exists($packagevars{$what}{'lonBalancer'})) {
1.570     raeburn  2040:                         if ($dist =~ /^(centos|rhes|fedora|scientific|oracle|rocky|alma)/) {
1.480     raeburn  2041:                             my $othervarref=LONCAPA::Configuration::read_conf('httpd.conf');
                   2042:                             if (ref($othervarref) eq 'HASH') {
                   2043:                                 $items->{'lonBalancer'} = $othervarref->{'lonBalancer'};
                   2044:                             }
                   2045:                         }
                   2046:                     }
1.477     raeburn  2047:                 }
1.480     raeburn  2048:                 $response = &Apache::lonnet::freeze_escape($items);
1.477     raeburn  2049:             }
1.478     raeburn  2050:             $result .= &escape($what).'='.$response.'&';
1.477     raeburn  2051:         }
                   2052:     }
                   2053:     $result =~ s/\&$//;
                   2054:     &Reply($client,\$result,$userinput);
                   2055:     return 1;
                   2056: }
                   2057: &register_handler("readlonnetglobal", \&read_lonnet_global, 0, 1, 0);
                   2058: 
1.479     raeburn  2059: sub server_devalidatecache_handler {
                   2060:     my ($cmd,$tail,$client) = @_;
                   2061:     my $userinput = "$cmd:$tail";
1.503     raeburn  2062:     my $items = &unescape($tail);
                   2063:     my @cached = split(/\&/,$items);
                   2064:     foreach my $key (@cached) {
                   2065:         if ($key =~ /:/) {
                   2066:             my ($name,$id) = map { &unescape($_); } split(/:/,$key);
                   2067:             &Apache::lonnet::devalidate_cache_new($name,$id);
                   2068:         }
                   2069:     }
1.479     raeburn  2070:     my $result = 'ok';
                   2071:     &Reply($client,\$result,$userinput);
                   2072:     return 1;
                   2073: }
1.481     raeburn  2074: &register_handler("devalidatecache", \&server_devalidatecache_handler, 0, 1, 0);
1.479     raeburn  2075: 
1.410     raeburn  2076: sub server_timezone_handler {
                   2077:     my ($cmd,$tail,$client) = @_;
                   2078:     my $userinput = "$cmd:$tail";
                   2079:     my $timezone;
                   2080:     my $clockfile = '/etc/sysconfig/clock'; # Fedora/CentOS/SuSE
                   2081:     my $tzfile = '/etc/timezone'; # Debian/Ubuntu
                   2082:     if (-e $clockfile) {
                   2083:         if (open(my $fh,"<$clockfile")) {
                   2084:             while (<$fh>) {
                   2085:                 next if (/^[\#\s]/);
                   2086:                 if (/^(?:TIME)?ZONE\s*=\s*['"]?\s*([\w\/]+)/) {
                   2087:                     $timezone = $1;
                   2088:                     last;
                   2089:                 }
                   2090:             }
                   2091:             close($fh);
                   2092:         }
                   2093:     } elsif (-e $tzfile) {
                   2094:         if (open(my $fh,"<$tzfile")) {
                   2095:             $timezone = <$fh>;
                   2096:             close($fh);
                   2097:             chomp($timezone);
                   2098:             if ($timezone =~ m{^Etc/(\w+)$}) {
                   2099:                 $timezone = $1;
                   2100:             }
                   2101:         }
                   2102:     }
                   2103:     &Reply($client,\$timezone,$userinput); # This supports debug logging.
                   2104:     return 1;
                   2105: }
                   2106: &register_handler("servertimezone", \&server_timezone_handler, 0, 1, 0);
                   2107: 
1.413     raeburn  2108: sub server_loncaparev_handler {
                   2109:     my ($cmd,$tail,$client) = @_;
                   2110:     my $userinput = "$cmd:$tail";
                   2111:     &Reply($client,\$perlvar{'lonVersion'},$userinput);
                   2112:     return 1;
                   2113: }
                   2114: &register_handler("serverloncaparev", \&server_loncaparev_handler, 0, 1, 0);
                   2115: 
1.448     raeburn  2116: sub server_homeID_handler {
                   2117:     my ($cmd,$tail,$client) = @_;
                   2118:     my $userinput = "$cmd:$tail";
                   2119:     &Reply($client,\$perlvar{'lonHostID'},$userinput);
                   2120:     return 1;
                   2121: }
                   2122: &register_handler("serverhomeID", \&server_homeID_handler, 0, 1, 0);
                   2123: 
1.471     raeburn  2124: sub server_distarch_handler {
                   2125:     my ($cmd,$tail,$client) = @_;
                   2126:     my $userinput = "$cmd:$tail";
                   2127:     my $reply = &distro_and_arch();
                   2128:     &Reply($client,\$reply,$userinput);
                   2129:     return 1;
                   2130: }
                   2131: &register_handler("serverdistarch", \&server_distarch_handler, 0, 1, 0);
                   2132: 
1.523     raeburn  2133: sub server_certs_handler {
                   2134:     my ($cmd,$tail,$client) = @_;
                   2135:     my $userinput = "$cmd:$tail";
1.548     raeburn  2136:     my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
                   2137:     my $result = &LONCAPA::Lond::server_certs(\%perlvar,$perlvar{'lonHostID'},$hostname);
1.523     raeburn  2138:     &Reply($client,\$result,$userinput);
                   2139:     return;
                   2140: }
                   2141: &register_handler("servercerts", \&server_certs_handler, 0, 1, 0);
                   2142: 
1.218     foxr     2143: #   Process a reinit request.  Reinit requests that either
                   2144: #   lonc or lond be reinitialized so that an updated 
                   2145: #   host.tab or domain.tab can be processed.
                   2146: #
                   2147: # Parameters:
                   2148: #      $cmd    - the actual keyword that invoked us.
                   2149: #      $tail   - the tail of the request that invoked us.
                   2150: #      $client - File descriptor connected to the client
                   2151: #  Returns:
                   2152: #      1       - Ok to continue processing.
                   2153: #      0       - Program should exit
                   2154: #  Implicit output:
                   2155: #     a reply is sent to the client.
                   2156: #
                   2157: sub reinit_process_handler {
                   2158:     my ($cmd, $tail, $client) = @_;
                   2159:    
                   2160:     my $userinput = "$cmd:$tail";
                   2161:    
                   2162:     my $cert = &GetCertificate($userinput);
                   2163:     if(&ValidManager($cert)) {
                   2164: 	chomp($userinput);
                   2165: 	my $reply = &ReinitProcess($userinput);
1.387     albertel 2166: 	&Reply( $client,  \$reply, $userinput);
1.218     foxr     2167:     } else {
                   2168: 	&Failure( $client, "refused\n", $userinput);
                   2169:     }
                   2170:     return 1;
                   2171: }
                   2172: &register_handler("reinit", \&reinit_process_handler, 1, 0, 1);
                   2173: 
                   2174: #  Process the editing script for a table edit operation.
                   2175: #  the editing operation must be encrypted and requested by
                   2176: #  a manager host.
                   2177: #
                   2178: # Parameters:
                   2179: #      $cmd    - the actual keyword that invoked us.
                   2180: #      $tail   - the tail of the request that invoked us.
                   2181: #      $client - File descriptor connected to the client
                   2182: #  Returns:
                   2183: #      1       - Ok to continue processing.
                   2184: #      0       - Program should exit
                   2185: #  Implicit output:
                   2186: #     a reply is sent to the client.
                   2187: #
                   2188: sub edit_table_handler {
                   2189:     my ($command, $tail, $client) = @_;
                   2190:    
                   2191:     my $userinput = "$command:$tail";
                   2192: 
                   2193:     my $cert = &GetCertificate($userinput);
                   2194:     if(&ValidManager($cert)) {
                   2195: 	my($filetype, $script) = split(/:/, $tail);
                   2196: 	if (($filetype eq "hosts") || 
                   2197: 	    ($filetype eq "domain")) {
                   2198: 	    if($script ne "") {
                   2199: 		&Reply($client,              # BUGBUG - EditFile
                   2200: 		      &EditFile($userinput), #   could fail.
                   2201: 		      $userinput);
                   2202: 	    } else {
                   2203: 		&Failure($client,"refused\n",$userinput);
                   2204: 	    }
                   2205: 	} else {
                   2206: 	    &Failure($client,"refused\n",$userinput);
                   2207: 	}
                   2208:     } else {
                   2209: 	&Failure($client,"refused\n",$userinput);
                   2210:     }
                   2211:     return 1;
                   2212: }
1.263     albertel 2213: &register_handler("edit", \&edit_table_handler, 1, 0, 1);
1.218     foxr     2214: 
1.220     foxr     2215: #
                   2216: #   Authenticate a user against the LonCAPA authentication
                   2217: #   database.  Note that there are several authentication
                   2218: #   possibilities:
                   2219: #   - unix     - The user can be authenticated against the unix
                   2220: #                password file.
                   2221: #   - internal - The user can be authenticated against a purely 
                   2222: #                internal per user password file.
                   2223: #   - kerberos - The user can be authenticated against either a kerb4 or kerb5
                   2224: #                ticket granting authority.
                   2225: #   - user     - The person tailoring LonCAPA can supply a user authentication
                   2226: #                mechanism that is per system.
                   2227: #
                   2228: # Parameters:
                   2229: #    $cmd      - The command that got us here.
                   2230: #    $tail     - Tail of the command (remaining parameters).
                   2231: #    $client   - File descriptor connected to client.
                   2232: # Returns
                   2233: #     0        - Requested to exit, caller should shut down.
                   2234: #     1        - Continue processing.
                   2235: # Implicit inputs:
                   2236: #    The authentication systems describe above have their own forms of implicit
                   2237: #    input into the authentication process that are described above.
                   2238: #
                   2239: sub authenticate_handler {
                   2240:     my ($cmd, $tail, $client) = @_;
                   2241: 
                   2242:     
                   2243:     #  Regenerate the full input line 
                   2244:     
                   2245:     my $userinput  = $cmd.":".$tail;
                   2246:     
                   2247:     #  udom    - User's domain.
                   2248:     #  uname   - Username.
                   2249:     #  upass   - User's password.
1.396     raeburn  2250:     #  checkdefauth - Pass to validate_user() to try authentication
                   2251:     #                 with default auth type(s) if no user account.
1.447     raeburn  2252:     #  clientcancheckhost - Passed by clients with functionality in lonauth.pm
                   2253:     #                       to check if session can be hosted.
1.220     foxr     2254:     
1.447     raeburn  2255:     my ($udom, $uname, $upass, $checkdefauth, $clientcancheckhost)=split(/:/,$tail);
1.399     raeburn  2256:     &Debug(" Authenticate domain = $udom, user = $uname, password = $upass,  checkdefauth = $checkdefauth");
1.220     foxr     2257:     chomp($upass);
                   2258:     $upass=&unescape($upass);
                   2259: 
1.396     raeburn  2260:     my $pwdcorrect = &validate_user($udom,$uname,$upass,$checkdefauth);
1.220     foxr     2261:     if($pwdcorrect) {
1.447     raeburn  2262:         my $canhost = 1;
                   2263:         unless ($clientcancheckhost) {
1.448     raeburn  2264:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   2265:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.452     raeburn  2266:             my @intdoms;
                   2267:             my $internet_names = &Apache::lonnet::get_internet_names($clientname);
                   2268:             if (ref($internet_names) eq 'ARRAY') {
                   2269:                 @intdoms = @{$internet_names};
                   2270:             }
1.448     raeburn  2271:             unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
1.447     raeburn  2272:                 my ($remote,$hosted);
                   2273:                 my $remotesession = &get_usersession_config($udom,'remotesession');
                   2274:                 if (ref($remotesession) eq 'HASH') {
1.525     raeburn  2275:                     $remote = $remotesession->{'remote'};
1.447     raeburn  2276:                 }
1.448     raeburn  2277:                 my $hostedsession = &get_usersession_config($clienthomedom,'hostedsession');
1.447     raeburn  2278:                 if (ref($hostedsession) eq 'HASH') {
                   2279:                     $hosted = $hostedsession->{'hosted'};
                   2280:                 }
1.448     raeburn  2281:                 $canhost = &Apache::lonnet::can_host_session($udom,$clientname,
1.492     droeschl 2282:                                                              $clientversion,
1.447     raeburn  2283:                                                              $remote,$hosted);
                   2284:             }
                   2285:         }
                   2286:         if ($canhost) {               
                   2287:             &Reply( $client, "authorized\n", $userinput);
                   2288:         } else {
                   2289:             &Reply( $client, "not_allowed_to_host\n", $userinput);
                   2290:         }
1.220     foxr     2291: 	#
                   2292: 	#  Bad credentials: Failed to authorize
                   2293: 	#
                   2294:     } else {
                   2295: 	&Failure( $client, "non_authorized\n", $userinput);
                   2296:     }
                   2297: 
                   2298:     return 1;
                   2299: }
1.263     albertel 2300: &register_handler("auth", \&authenticate_handler, 1, 1, 0);
1.214     foxr     2301: 
1.222     foxr     2302: #
                   2303: #   Change a user's password.  Note that this function is complicated by
                   2304: #   the fact that a user may be authenticated in more than one way:
                   2305: #   At present, we are not able to change the password for all types of
                   2306: #   authentication methods.  Only for:
                   2307: #      unix    - unix password or shadow passoword style authentication.
                   2308: #      local   - Locally written authentication mechanism.
                   2309: #   For now, kerb4 and kerb5 password changes are not supported and result
                   2310: #   in an error.
                   2311: # FUTURE WORK:
                   2312: #    Support kerberos passwd changes?
                   2313: # Parameters:
                   2314: #    $cmd      - The command that got us here.
                   2315: #    $tail     - Tail of the command (remaining parameters).
                   2316: #    $client   - File descriptor connected to client.
                   2317: # Returns
                   2318: #     0        - Requested to exit, caller should shut down.
                   2319: #     1        - Continue processing.
                   2320: # Implicit inputs:
                   2321: #    The authentication systems describe above have their own forms of implicit
                   2322: #    input into the authentication process that are described above.
                   2323: sub change_password_handler {
                   2324:     my ($cmd, $tail, $client) = @_;
                   2325: 
                   2326:     my $userinput = $cmd.":".$tail;           # Reconstruct client's string.
                   2327: 
                   2328:     #
                   2329:     #  udom  - user's domain.
                   2330:     #  uname - Username.
                   2331:     #  upass - Current password.
                   2332:     #  npass - New password.
1.346     raeburn  2333:     #  context - Context in which this was called 
                   2334:     #            (preferences or reset_by_email).
1.428     raeburn  2335:     #  lonhost - HostID of server where request originated 
1.222     foxr     2336:    
1.428     raeburn  2337:     my ($udom,$uname,$upass,$npass,$context,$lonhost)=split(/:/,$tail);
1.222     foxr     2338: 
                   2339:     $upass=&unescape($upass);
                   2340:     $npass=&unescape($npass);
                   2341:     &Debug("Trying to change password for $uname");
                   2342: 
                   2343:     # First require that the user can be authenticated with their
1.346     raeburn  2344:     # old password unless context was 'reset_by_email':
                   2345:     
1.428     raeburn  2346:     my ($validated,$failure);
1.346     raeburn  2347:     if ($context eq 'reset_by_email') {
1.428     raeburn  2348:         if ($lonhost eq '') {
                   2349:             $failure = 'invalid_client';
                   2350:         } else {
                   2351:             $validated = 1;
                   2352:         }
1.346     raeburn  2353:     } else {
                   2354:         $validated = &validate_user($udom, $uname, $upass);
                   2355:     }
1.222     foxr     2356:     if($validated) {
                   2357: 	my $realpasswd  = &get_auth_type($udom, $uname); # Defined since authd.
                   2358: 	my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
1.558     raeburn  2359:         my $notunique;
1.222     foxr     2360: 	if ($howpwd eq 'internal') {
                   2361: 	    &Debug("internal auth");
1.518     raeburn  2362:             my $ncpass = &hash_passwd($udom,$npass);
1.558     raeburn  2363:             my (undef,$method,@rest) = split(/!/,$contentpwd);
                   2364:             if ($method eq 'bcrypt') {
                   2365:                 my %passwdconf = &Apache::lonnet::get_passwdconf($udom);
                   2366:                 if (($passwdconf{'numsaved'}) && ($passwdconf{'numsaved'} =~ /^\d+$/)) {
                   2367:                     my @oldpasswds;
                   2368:                     my $userpath = &propath($udom,$uname);
                   2369:                     my $fullpath = $userpath.'/oldpasswds';
                   2370:                     if (-d $userpath) {
                   2371:                         my @oldfiles;
                   2372:                         if (-e $fullpath) {
                   2373:                             if (opendir(my $dir,$fullpath)) {
                   2374:                                 (@oldfiles) = grep(/^\d+$/,readdir($dir));
                   2375:                                 closedir($dir);
                   2376:                             }
                   2377:                             if (@oldfiles) {
                   2378:                                 @oldfiles = sort { $b <=> $a } (@oldfiles);
                   2379:                                 my $numremoved = 0;
                   2380:                                 for (my $i=0; $i<@oldfiles; $i++) {
                   2381:                                     if ($i>=$passwdconf{'numsaved'}) {
                   2382:                                         if (-f "$fullpath/$oldfiles[$i]") {
                   2383:                                             if (unlink("$fullpath/$oldfiles[$i]")) {
                   2384:                                                 $numremoved ++;
                   2385:                                             }
                   2386:                                         }
                   2387:                                     } elsif (open(my $fh,'<',"$fullpath/$oldfiles[$i]")) {
                   2388:                                         while (my $line = <$fh>) {
                   2389:                                             push(@oldpasswds,$line);
                   2390:                                         }
                   2391:                                         close($fh);
                   2392:                                     }
                   2393:                                 }
                   2394:                                 if ($numremoved) {
                   2395:                                     &logthis("unlinked $numremoved old password files for $uname:$udom");
                   2396:                                 }
                   2397:                             }
                   2398:                         }
                   2399:                         push(@oldpasswds,$contentpwd);
                   2400:                         foreach my $item (@oldpasswds) {
                   2401:                             my (undef,$method,@rest) = split(/!/,$item);
                   2402:                             if ($method eq 'bcrypt') {
                   2403:                                 my $result = &hash_passwd($udom,$npass,@rest);
                   2404:                                 if ($result eq $item) {
                   2405:                                     $notunique = 1;
                   2406:                                     last;
                   2407:                                 }
                   2408:                             }
                   2409:                         }
                   2410:                         unless ($notunique) {
                   2411:                             unless (-e $fullpath) {
                   2412:                                 if (&mkpath("$fullpath/")) {
                   2413:                                     chmod(0700,$fullpath);
                   2414:                                 }
                   2415:                             }
                   2416:                             if (-d $fullpath) {
                   2417:                                 my $now = time;
                   2418:                                 if (open(my $fh,'>',"$fullpath/$now")) {
                   2419:                                     print $fh $contentpwd;
                   2420:                                     close($fh);
                   2421:                                     chmod(0400,"$fullpath/$now");
                   2422:                                 }
                   2423:                             }
                   2424:                         }
                   2425:                     }
                   2426:                 }
                   2427:             }
                   2428:             if ($notunique) {
                   2429:                 my $msg="Result of password change for $uname:$udom - password matches one used before";
                   2430:                 if ($lonhost) {
                   2431:                     $msg .= " - request originated from: $lonhost";
                   2432:                 }
                   2433:                 &logthis($msg);
                   2434:                 &Reply($client, "prioruse\n", $userinput);
                   2435: 	    } elsif (&rewrite_password_file($udom, $uname, "internal:$ncpass")) {
1.428     raeburn  2436: 		my $msg="Result of password change for $uname: pwchange_success";
                   2437:                 if ($lonhost) {
                   2438:                     $msg .= " - request originated from: $lonhost";
                   2439:                 }
                   2440:                 &logthis($msg);
1.518     raeburn  2441:                 &update_passwd_history($uname,$udom,$howpwd,$context);
1.222     foxr     2442: 		&Reply($client, "ok\n", $userinput);
                   2443: 	    } else {
                   2444: 		&logthis("Unable to open $uname passwd "               
                   2445: 			 ."to change password");
                   2446: 		&Failure( $client, "non_authorized\n",$userinput);
                   2447: 	    }
1.346     raeburn  2448: 	} elsif ($howpwd eq 'unix' && $context ne 'reset_by_email') {
1.287     foxr     2449: 	    my $result = &change_unix_password($uname, $npass);
1.518     raeburn  2450:             if ($result eq 'ok') {
                   2451:                 &update_passwd_history($uname,$udom,$howpwd,$context);
1.561     raeburn  2452:             }
1.222     foxr     2453: 	    &logthis("Result of password change for $uname: ".
1.287     foxr     2454: 		     $result);
1.387     albertel 2455: 	    &Reply($client, \$result, $userinput);
1.222     foxr     2456: 	} else {
                   2457: 	    # this just means that the current password mode is not
                   2458: 	    # one we know how to change (e.g the kerberos auth modes or
                   2459: 	    # locally written auth handler).
                   2460: 	    #
                   2461: 	    &Failure( $client, "auth_mode_error\n", $userinput);
                   2462: 	}  
1.224     foxr     2463:     } else {
1.428     raeburn  2464: 	if ($failure eq '') {
                   2465: 	    $failure = 'non_authorized';
                   2466: 	}
                   2467: 	&Failure( $client, "$failure\n", $userinput);
1.222     foxr     2468:     }
                   2469: 
                   2470:     return 1;
                   2471: }
1.263     albertel 2472: &register_handler("passwd", \&change_password_handler, 1, 1, 0);
1.222     foxr     2473: 
1.518     raeburn  2474: sub hash_passwd {
                   2475:     my ($domain,$plainpass,@rest) = @_;
                   2476:     my ($salt,$cost);
                   2477:     if (@rest) {
                   2478:         $cost = $rest[0];
                   2479:         # salt is first 22 characters, base-64 encoded by bcrypt
                   2480:         my $plainsalt = substr($rest[1],0,22);
                   2481:         $salt = Crypt::Eksblowfish::Bcrypt::de_base64($plainsalt);
                   2482:     } else {
1.533     raeburn  2483:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   2484:         my $defaultcost = $domdefaults{'intauth_cost'};
1.518     raeburn  2485:         if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
                   2486:             $cost = 10;
                   2487:         } else {
                   2488:             $cost = $defaultcost;
                   2489:         }
                   2490:         # Generate random 16-octet base64 salt
                   2491:         $salt = "";
                   2492:         $salt .= pack("C", int rand(256)) for 1..16;
                   2493:     }
                   2494:     my $hash = &Crypt::Eksblowfish::Bcrypt::bcrypt_hash({
                   2495:         key_nul => 1,
                   2496:         cost    => $cost,
                   2497:         salt    => $salt,
                   2498:     }, Digest::SHA::sha512(Encode::encode('UTF-8',$plainpass)));
                   2499: 
                   2500:     my $result = join("!", "", "bcrypt", sprintf("%02d",$cost),
                   2501:                 &Crypt::Eksblowfish::Bcrypt::en_base64($salt).
                   2502:                 &Crypt::Eksblowfish::Bcrypt::en_base64($hash));
                   2503:     return $result;
                   2504: }
                   2505: 
1.225     foxr     2506: #
                   2507: #   Create a new user.  User in this case means a lon-capa user.
                   2508: #   The user must either already exist in some authentication realm
                   2509: #   like kerberos or the /etc/passwd.  If not, a user completely local to
                   2510: #   this loncapa system is created.
                   2511: #
                   2512: # Parameters:
                   2513: #    $cmd      - The command that got us here.
                   2514: #    $tail     - Tail of the command (remaining parameters).
                   2515: #    $client   - File descriptor connected to client.
                   2516: # Returns
                   2517: #     0        - Requested to exit, caller should shut down.
                   2518: #     1        - Continue processing.
                   2519: # Implicit inputs:
                   2520: #    The authentication systems describe above have their own forms of implicit
                   2521: #    input into the authentication process that are described above.
                   2522: sub add_user_handler {
                   2523: 
                   2524:     my ($cmd, $tail, $client) = @_;
                   2525: 
                   2526: 
                   2527:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   2528:     my $userinput = $cmd.":".$tail; # Reconstruct the full request line.
                   2529: 
                   2530:     &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
                   2531: 
                   2532: 
                   2533:     if($udom eq $currentdomainid) { # Reject new users for other domains...
                   2534: 	
                   2535: 	my $oldumask=umask(0077);
                   2536: 	chomp($npass);
                   2537: 	$npass=&unescape($npass);
                   2538: 	my $passfilename  = &password_path($udom, $uname);
                   2539: 	&Debug("Password file created will be:".$passfilename);
                   2540: 	if (-e $passfilename) {
                   2541: 	    &Failure( $client, "already_exists\n", $userinput);
                   2542: 	} else {
                   2543: 	    my $fperror='';
1.264     albertel 2544: 	    if (!&mkpath($passfilename)) {
                   2545: 		$fperror="error: ".($!+0)." mkdir failed while attempting "
                   2546: 		    ."makeuser";
1.225     foxr     2547: 	    }
                   2548: 	    unless ($fperror) {
1.518     raeburn  2549: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
                   2550:                                              $passfilename,'makeuser');
1.390     raeburn  2551: 		&Reply($client,\$result, $userinput);     #BUGBUG - could be fail
1.225     foxr     2552: 	    } else {
1.387     albertel 2553: 		&Failure($client, \$fperror, $userinput);
1.225     foxr     2554: 	    }
                   2555: 	}
                   2556: 	umask($oldumask);
                   2557:     }  else {
                   2558: 	&Failure($client, "not_right_domain\n",
                   2559: 		$userinput);	# Even if we are multihomed.
                   2560:     
                   2561:     }
                   2562:     return 1;
                   2563: 
                   2564: }
                   2565: &register_handler("makeuser", \&add_user_handler, 1, 1, 0);
                   2566: 
                   2567: #
                   2568: #   Change the authentication method of a user.  Note that this may
                   2569: #   also implicitly change the user's password if, for example, the user is
                   2570: #   joining an existing authentication realm.  Known authentication realms at
                   2571: #   this time are:
                   2572: #    internal   - Purely internal password file (only loncapa knows this user)
                   2573: #    local      - Institutionally written authentication module.
                   2574: #    unix       - Unix user (/etc/passwd with or without /etc/shadow).
                   2575: #    kerb4      - kerberos version 4
                   2576: #    kerb5      - kerberos version 5
                   2577: #
                   2578: # Parameters:
                   2579: #    $cmd      - The command that got us here.
                   2580: #    $tail     - Tail of the command (remaining parameters).
                   2581: #    $client   - File descriptor connected to client.
                   2582: # Returns
                   2583: #     0        - Requested to exit, caller should shut down.
                   2584: #     1        - Continue processing.
                   2585: # Implicit inputs:
                   2586: #    The authentication systems describe above have their own forms of implicit
                   2587: #    input into the authentication process that are described above.
1.287     foxr     2588: # NOTE:
                   2589: #   This is also used to change the authentication credential values (e.g. passwd).
                   2590: #   
1.225     foxr     2591: #
                   2592: sub change_authentication_handler {
                   2593: 
                   2594:     my ($cmd, $tail, $client) = @_;
                   2595:    
                   2596:     my $userinput  = "$cmd:$tail";              # Reconstruct user input.
                   2597: 
                   2598:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   2599:     &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
                   2600:     if ($udom ne $currentdomainid) {
                   2601: 	&Failure( $client, "not_right_domain\n", $client);
                   2602:     } else {
                   2603: 	
                   2604: 	chomp($npass);
                   2605: 	
                   2606: 	$npass=&unescape($npass);
1.261     foxr     2607: 	my $oldauth = &get_auth_type($udom, $uname); # Get old auth info.
1.225     foxr     2608: 	my $passfilename = &password_path($udom, $uname);
                   2609: 	if ($passfilename) {	# Not allowed to create a new user!!
1.287     foxr     2610: 	    # If just changing the unix passwd. need to arrange to run
1.502     raeburn  2611: 	    # passwd since otherwise make_passwd_file will fail as 
                   2612: 	    # creation of unix authenticated users is no longer supported
                   2613:             # except from the command line, when running make_domain_coordinator.pl
1.287     foxr     2614: 
                   2615: 	    if(($oldauth =~/^unix/) && ($umode eq "unix")) {
                   2616: 		my $result = &change_unix_password($uname, $npass);
                   2617: 		&logthis("Result of password change for $uname: ".$result);
                   2618: 		if ($result eq "ok") {
1.518     raeburn  2619:                     &update_passwd_history($uname,$udom,$umode,'changeuserauth'); 
1.390     raeburn  2620: 		    &Reply($client, \$result);
1.288     albertel 2621: 		} else {
1.387     albertel 2622: 		    &Failure($client, \$result);
1.287     foxr     2623: 		}
1.288     albertel 2624: 	    } else {
1.518     raeburn  2625: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
                   2626:                                              $passfilename,'changeuserauth');
1.287     foxr     2627: 		#
                   2628: 		#  If the current auth mode is internal, and the old auth mode was
                   2629: 		#  unix, or krb*,  and the user is an author for this domain,
                   2630: 		#  re-run manage_permissions for that role in order to be able
                   2631: 		#  to take ownership of the construction space back to www:www
                   2632: 		#
1.502     raeburn  2633: 
                   2634: 
1.387     albertel 2635: 		&Reply($client, \$result, $userinput);
1.261     foxr     2636: 	    }
                   2637: 	       
                   2638: 
1.225     foxr     2639: 	} else {	       
1.251     foxr     2640: 	    &Failure($client, "non_authorized\n", $userinput); # Fail the user now.
1.225     foxr     2641: 	}
                   2642:     }
                   2643:     return 1;
                   2644: }
                   2645: &register_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
                   2646: 
1.518     raeburn  2647: sub update_passwd_history {
                   2648:     my ($uname,$udom,$umode,$context) = @_;
                   2649:     my $proname=&propath($udom,$uname);
                   2650:     my $now = time;
                   2651:     if (open(my $fh,">>$proname/passwd.log")) {
                   2652:         print $fh "$now:$umode:$context\n";
                   2653:         close($fh);
                   2654:     }
                   2655:     return;
                   2656: }
                   2657: 
1.225     foxr     2658: #
                   2659: #   Determines if this is the home server for a user.  The home server
                   2660: #   for a user will have his/her lon-capa passwd file.  Therefore all we need
                   2661: #   to do is determine if this file exists.
                   2662: #
                   2663: # Parameters:
                   2664: #    $cmd      - The command that got us here.
                   2665: #    $tail     - Tail of the command (remaining parameters).
                   2666: #    $client   - File descriptor connected to client.
                   2667: # Returns
                   2668: #     0        - Requested to exit, caller should shut down.
                   2669: #     1        - Continue processing.
                   2670: # Implicit inputs:
                   2671: #    The authentication systems describe above have their own forms of implicit
                   2672: #    input into the authentication process that are described above.
                   2673: #
                   2674: sub is_home_handler {
                   2675:     my ($cmd, $tail, $client) = @_;
                   2676:    
                   2677:     my $userinput  = "$cmd:$tail";
                   2678:    
                   2679:     my ($udom,$uname)=split(/:/,$tail);
                   2680:     chomp($uname);
                   2681:     my $passfile = &password_filename($udom, $uname);
                   2682:     if($passfile) {
                   2683: 	&Reply( $client, "found\n", $userinput);
                   2684:     } else {
                   2685: 	&Failure($client, "not_found\n", $userinput);
                   2686:     }
                   2687:     return 1;
                   2688: }
                   2689: &register_handler("home", \&is_home_handler, 0,1,0);
                   2690: 
                   2691: #
1.434     www      2692: #   Process an update request for a resource.
                   2693: #   A resource has been modified that we hold a subscription to.
1.225     foxr     2694: #   If the resource is not local, then we must update, or at least invalidate our
                   2695: #   cached copy of the resource. 
                   2696: # Parameters:
                   2697: #    $cmd      - The command that got us here.
                   2698: #    $tail     - Tail of the command (remaining parameters).
                   2699: #    $client   - File descriptor connected to client.
                   2700: # Returns
                   2701: #     0        - Requested to exit, caller should shut down.
                   2702: #     1        - Continue processing.
                   2703: # Implicit inputs:
                   2704: #    The authentication systems describe above have their own forms of implicit
                   2705: #    input into the authentication process that are described above.
                   2706: #
                   2707: sub update_resource_handler {
                   2708: 
                   2709:     my ($cmd, $tail, $client) = @_;
                   2710:    
                   2711:     my $userinput = "$cmd:$tail";
                   2712:    
                   2713:     my $fname= $tail;		# This allows interactive testing
                   2714: 
                   2715: 
                   2716:     my $ownership=ishome($fname);
                   2717:     if ($ownership eq 'not_owner') {
                   2718: 	if (-e $fname) {
1.434     www      2719:             # Delete preview file, if exists
                   2720:             unlink("$fname.tmp");
                   2721:             # Get usage stats
1.225     foxr     2722: 	    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
                   2723: 		$atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
                   2724: 	    my $now=time;
                   2725: 	    my $since=$now-$atime;
1.434     www      2726:             # If the file has not been used within lonExpire seconds,
                   2727:             # unsubscribe from it and delete local copy
1.225     foxr     2728: 	    if ($since>$perlvar{'lonExpire'}) {
1.365     albertel 2729: 		my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
1.308     albertel 2730: 		&devalidate_meta_cache($fname);
1.225     foxr     2731: 		unlink("$fname");
1.334     albertel 2732: 		unlink("$fname.meta");
1.225     foxr     2733: 	    } else {
1.434     www      2734:             # Yes, this is in active use. Get a fresh copy. Since it might be in
                   2735:             # very active use and huge (like a movie), copy it to "in.transfer" filename first.
1.225     foxr     2736: 		my $transname="$fname.in.transfer";
1.365     albertel 2737: 		my $remoteurl=&Apache::lonnet::reply("sub:$fname","$clientname");
1.225     foxr     2738: 		my $response;
1.537     raeburn  2739: # FIXME: cannot replicate files that take more than two minutes to transfer -- needs checking now 1200s timeout used
                   2740: # for LWP request.
                   2741: 		my $request=new HTTP::Request('GET',"$remoteurl");
                   2742:                 $response=&LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,0,1);
1.225     foxr     2743: 		if ($response->is_error()) {
1.541     raeburn  2744:                     my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
                   2745:                     &devalidate_meta_cache($fname);
                   2746:                     if (-e $transname) {
                   2747:                         unlink($transname);
                   2748:                     }
                   2749:                     unlink($fname);
1.225     foxr     2750: 		    my $message=$response->status_line;
                   2751: 		    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   2752: 		} else {
                   2753: 		    if ($remoteurl!~/\.meta$/) {
1.537     raeburn  2754: 			my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2755:                         my $mresponse = &LONCAPA::LWPReq::makerequest($clientname,$mrequest,$fname.'.meta',\%perlvar,120,0,1);
                   2756: 			if ($mresponse->is_error()) {
                   2757: 			    unlink($fname.'.meta');
1.225     foxr     2758: 			}
                   2759: 		    }
1.434     www      2760:                     # we successfully transfered, copy file over to real name
1.225     foxr     2761: 		    rename($transname,$fname);
1.308     albertel 2762: 		    &devalidate_meta_cache($fname);
1.225     foxr     2763: 		}
                   2764: 	    }
                   2765: 	    &Reply( $client, "ok\n", $userinput);
                   2766: 	} else {
                   2767: 	    &Failure($client, "not_found\n", $userinput);
                   2768: 	}
                   2769:     } else {
                   2770: 	&Failure($client, "rejected\n", $userinput);
                   2771:     }
                   2772:     return 1;
                   2773: }
                   2774: &register_handler("update", \&update_resource_handler, 0 ,1, 0);
                   2775: 
1.308     albertel 2776: sub devalidate_meta_cache {
                   2777:     my ($url) = @_;
                   2778:     use Cache::Memcached;
                   2779:     my $memcache = new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.365     albertel 2780:     $url = &Apache::lonnet::declutter($url);
1.308     albertel 2781:     $url =~ s-\.meta$--;
                   2782:     my $id = &escape('meta:'.$url);
                   2783:     $memcache->delete($id);
                   2784: }
                   2785: 
1.225     foxr     2786: #
1.226     foxr     2787: #   Fetch a user file from a remote server to the user's home directory
                   2788: #   userfiles subdir.
1.225     foxr     2789: # Parameters:
                   2790: #    $cmd      - The command that got us here.
                   2791: #    $tail     - Tail of the command (remaining parameters).
                   2792: #    $client   - File descriptor connected to client.
                   2793: # Returns
                   2794: #     0        - Requested to exit, caller should shut down.
                   2795: #     1        - Continue processing.
                   2796: #
                   2797: sub fetch_user_file_handler {
                   2798: 
                   2799:     my ($cmd, $tail, $client) = @_;
                   2800: 
                   2801:     my $userinput = "$cmd:$tail";
                   2802:     my $fname           = $tail;
1.232     foxr     2803:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
1.225     foxr     2804:     my $udir=&propath($udom,$uname).'/userfiles';
                   2805:     unless (-e $udir) {
                   2806: 	mkdir($udir,0770); 
                   2807:     }
1.232     foxr     2808:     Debug("fetch user file for $fname");
1.225     foxr     2809:     if (-e $udir) {
                   2810: 	$ufile=~s/^[\.\~]+//;
1.232     foxr     2811: 
                   2812: 	# IF necessary, create the path right down to the file.
                   2813: 	# Note that any regular files in the way of this path are
                   2814: 	# wiped out to deal with some earlier folly of mine.
                   2815: 
1.267     raeburn  2816: 	if (!&mkpath($udir.'/'.$ufile)) {
1.264     albertel 2817: 	    &Failure($client, "unable_to_create\n", $userinput);	    
1.232     foxr     2818: 	}
                   2819: 
1.225     foxr     2820: 	my $destname=$udir.'/'.$ufile;
                   2821: 	my $transname=$udir.'/'.$ufile.'.in.transit';
1.476     raeburn  2822:         my $clientprotocol=$Apache::lonnet::protocol{$clientname};
                   2823:         $clientprotocol = 'http' if ($clientprotocol ne 'https');
1.486     raeburn  2824: 	my $clienthost = &Apache::lonnet::hostname($clientname);
                   2825: 	my $remoteurl=$clientprotocol.'://'.$clienthost.'/userfiles/'.$fname;
1.225     foxr     2826: 	my $response;
1.232     foxr     2827: 	Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
1.537     raeburn  2828: 	my $request=new HTTP::Request('GET',"$remoteurl");
                   2829:         my $verifycert = 1;
                   2830:         my @machine_ids = &Apache::lonnet::current_machine_ids();
                   2831:         if (grep(/^\Q$clientname\E$/,@machine_ids)) {
                   2832:             $verifycert = 0;
                   2833:         }
                   2834:         $response = &LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,$verifycert);
1.225     foxr     2835: 	if ($response->is_error()) {
                   2836: 	    unlink($transname);
                   2837: 	    my $message=$response->status_line;
                   2838: 	    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   2839: 	    &Failure($client, "failed\n", $userinput);
                   2840: 	} else {
1.232     foxr     2841: 	    Debug("Renaming $transname to $destname");
1.225     foxr     2842: 	    if (!rename($transname,$destname)) {
                   2843: 		&logthis("Unable to move $transname to $destname");
                   2844: 		unlink($transname);
                   2845: 		&Failure($client, "failed\n", $userinput);
                   2846: 	    } else {
1.495     raeburn  2847:                 if ($fname =~ /^default.+\.(page|sequence)$/) {
                   2848:                     my ($major,$minor) = split(/\./,$clientversion);
                   2849:                     if (($major < 2) || ($major == 2 && $minor < 11)) {
                   2850:                         my $now = time;
                   2851:                         &Apache::lonnet::do_cache_new('crschange',$udom.'_'.$uname,$now,600);
                   2852:                         my $key = &escape('internal.contentchange');
                   2853:                         my $what = "$key=$now";
                   2854:                         my $hashref = &tie_user_hash($udom,$uname,'environment',
                   2855:                                                      &GDBM_WRCREAT(),"P",$what);
                   2856:                         if ($hashref) {
                   2857:                             $hashref->{$key}=$now;
                   2858:                             if (!&untie_user_hash($hashref)) {
                   2859:                                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
                   2860:                                          "when updating internal.contentchange");
                   2861:                             }
                   2862:                         }
                   2863:                     }
                   2864:                 }
1.225     foxr     2865: 		&Reply($client, "ok\n", $userinput);
                   2866: 	    }
                   2867: 	}   
                   2868:     } else {
                   2869: 	&Failure($client, "not_home\n", $userinput);
                   2870:     }
                   2871:     return 1;
                   2872: }
                   2873: &register_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
                   2874: 
1.226     foxr     2875: #
                   2876: #   Remove a file from a user's home directory userfiles subdirectory.
                   2877: # Parameters:
                   2878: #    cmd   - the Lond request keyword that got us here.
                   2879: #    tail  - the part of the command past the keyword.
                   2880: #    client- File descriptor connected with the client.
                   2881: #
                   2882: # Returns:
                   2883: #    1    - Continue processing.
                   2884: sub remove_user_file_handler {
                   2885:     my ($cmd, $tail, $client) = @_;
                   2886: 
                   2887:     my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2888: 
                   2889:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2890:     if ($ufile =~m|/\.\./|) {
                   2891: 	# any files paths with /../ in them refuse 
                   2892: 	# to deal with
                   2893: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2894:     } else {
                   2895: 	my $udir = &propath($udom,$uname);
                   2896: 	if (-e $udir) {
                   2897: 	    my $file=$udir.'/userfiles/'.$ufile;
                   2898: 	    if (-e $file) {
1.253     foxr     2899: 		#
                   2900: 		#   If the file is a regular file unlink is fine...
1.520     raeburn  2901: 		#   However it's possible the client wants a dir 
                   2902: 		#   removed, in which case rmdir is more appropriate.
                   2903: 		#   Note: rmdir will only remove an empty directory.
1.253     foxr     2904: 		#
1.240     banghart 2905: 	        if (-f $file){
1.241     albertel 2906: 		    unlink($file);
1.520     raeburn  2907:                     # for html files remove the associated .bak file 
                   2908:                     # which may have been created by the editor.
                   2909:                     if ($ufile =~ m{^((docs|supplemental)/(?:\d+|default)/\d+(?:|/.+)/)[^/]+\.x?html?$}i) {
                   2910:                         my $path = $1;
                   2911:                         if (-e $file.'.bak') {
                   2912:                             unlink($file.'.bak');
                   2913:                         }
                   2914:                     }
1.241     albertel 2915: 		} elsif(-d $file) {
                   2916: 		    rmdir($file);
1.240     banghart 2917: 		}
1.226     foxr     2918: 		if (-e $file) {
1.253     foxr     2919: 		    #  File is still there after we deleted it ?!?
                   2920: 
1.226     foxr     2921: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2922: 		} else {
                   2923: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2924: 		}
                   2925: 	    } else {
                   2926: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2927: 	    }
                   2928: 	} else {
                   2929: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2930: 	}
                   2931:     }
                   2932:     return 1;
                   2933: }
                   2934: &register_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
                   2935: 
1.236     albertel 2936: #
                   2937: #   make a directory in a user's home directory userfiles subdirectory.
                   2938: # Parameters:
                   2939: #    cmd   - the Lond request keyword that got us here.
                   2940: #    tail  - the part of the command past the keyword.
                   2941: #    client- File descriptor connected with the client.
                   2942: #
                   2943: # Returns:
                   2944: #    1    - Continue processing.
                   2945: sub mkdir_user_file_handler {
                   2946:     my ($cmd, $tail, $client) = @_;
                   2947: 
                   2948:     my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2949:     $dir=&unescape($dir);
                   2950:     my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2951:     if ($ufile =~m|/\.\./|) {
                   2952: 	# any files paths with /../ in them refuse 
                   2953: 	# to deal with
                   2954: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2955:     } else {
                   2956: 	my $udir = &propath($udom,$uname);
                   2957: 	if (-e $udir) {
1.264     albertel 2958: 	    my $newdir=$udir.'/userfiles/'.$ufile.'/';
                   2959: 	    if (!&mkpath($newdir)) {
                   2960: 		&Failure($client, "failed\n", "$cmd:$tail");
1.236     albertel 2961: 	    }
1.264     albertel 2962: 	    &Reply($client, "ok\n", "$cmd:$tail");
1.236     albertel 2963: 	} else {
                   2964: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2965: 	}
                   2966:     }
                   2967:     return 1;
                   2968: }
                   2969: &register_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
                   2970: 
1.237     albertel 2971: #
                   2972: #   rename a file in a user's home directory userfiles subdirectory.
                   2973: # Parameters:
                   2974: #    cmd   - the Lond request keyword that got us here.
                   2975: #    tail  - the part of the command past the keyword.
                   2976: #    client- File descriptor connected with the client.
                   2977: #
                   2978: # Returns:
                   2979: #    1    - Continue processing.
                   2980: sub rename_user_file_handler {
                   2981:     my ($cmd, $tail, $client) = @_;
                   2982: 
                   2983:     my ($udom,$uname,$old,$new) = split(/:/, $tail);
                   2984:     $old=&unescape($old);
                   2985:     $new=&unescape($new);
                   2986:     if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
                   2987: 	# any files paths with /../ in them refuse to deal with
                   2988: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2989:     } else {
                   2990: 	my $udir = &propath($udom,$uname);
                   2991: 	if (-e $udir) {
                   2992: 	    my $oldfile=$udir.'/userfiles/'.$old;
                   2993: 	    my $newfile=$udir.'/userfiles/'.$new;
                   2994: 	    if (-e $newfile) {
                   2995: 		&Failure($client, "exists\n", "$cmd:$tail");
                   2996: 	    } elsif (! -e $oldfile) {
                   2997: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2998: 	    } else {
                   2999: 		if (!rename($oldfile,$newfile)) {
                   3000: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   3001: 		} else {
                   3002: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   3003: 		}
                   3004: 	    }
                   3005: 	} else {
                   3006: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   3007: 	}
                   3008:     }
                   3009:     return 1;
                   3010: }
                   3011: &register_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
                   3012: 
1.227     foxr     3013: #
1.382     albertel 3014: #  Checks if the specified user has an active session on the server
                   3015: #  return ok if so, not_found if not
                   3016: #
                   3017: # Parameters:
                   3018: #   cmd      - The request keyword that dispatched to tus.
                   3019: #   tail     - The tail of the request (colon separated parameters).
                   3020: #   client   - Filehandle open on the client.
                   3021: # Return:
                   3022: #    1.
                   3023: sub user_has_session_handler {
                   3024:     my ($cmd, $tail, $client) = @_;
                   3025: 
                   3026:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
                   3027:     
                   3028:     opendir(DIR,$perlvar{'lonIDsDir'});
                   3029:     my $filename;
                   3030:     while ($filename=readdir(DIR)) {
                   3031: 	last if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/);
                   3032:     }
                   3033:     if ($filename) {
                   3034: 	&Reply($client, "ok\n", "$cmd:$tail");
                   3035:     } else {
                   3036: 	&Failure($client, "not_found\n", "$cmd:$tail");
                   3037:     }
                   3038:     return 1;
                   3039: 
                   3040: }
                   3041: &register_handler("userhassession", \&user_has_session_handler, 0,1,0);
                   3042: 
1.560     raeburn  3043: sub del_usersession_handler {
                   3044:     my ($cmd, $tail, $client) = @_;
                   3045: 
                   3046:     my $result;
                   3047:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
                   3048:     if (($udom =~ /^$LONCAPA::match_domain$/) && ($uname =~ /^$LONCAPA::match_username$/)) {
                   3049:         my $lonidsdir = $perlvar{'lonIDsDir'};
                   3050:         if (-d $lonidsdir) {
                   3051:             if (opendir(DIR,$lonidsdir)) {
                   3052:                 my $filename;
                   3053:                 while ($filename=readdir(DIR)) {
                   3054:                     if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/) {
                   3055:                         if (tie(my %oldenv,'GDBM_File',"$lonidsdir/$filename",
                   3056:                                 &GDBM_READER(),0640)) {
                   3057:                             my $linkedfile;
                   3058:                             if (exists($oldenv{'user.linkedenv'})) {
                   3059:                                 $linkedfile = $oldenv{'user.linkedenv'};
                   3060:                             }
                   3061:                             untie(%oldenv);
                   3062:                             $result = unlink("$lonidsdir/$filename");
                   3063:                             if ($result) {
                   3064:                                 if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   3065:                                     if (-l "$lonidsdir/$linkedfile.id") {
                   3066:                                         unlink("$lonidsdir/$linkedfile.id");
                   3067:                                     }
                   3068:                                 }
                   3069:                             }
                   3070:                         } else {
                   3071:                             $result = unlink("$lonidsdir/$filename");
                   3072:                         }
                   3073:                         last;
                   3074:                     }
                   3075:                 }
                   3076:             }
                   3077:         }
                   3078:         if ($result == 1) {
                   3079:             &Reply($client, "$result\n", "$cmd:$tail");
                   3080:         } else {
                   3081:             &Reply($client, "not_found\n", "$cmd:$tail");
                   3082:         }
                   3083:     } else {
                   3084:         &Failure($client, "invalid_user\n", "$cmd:$tail");
                   3085:     }
                   3086:     return 1;
                   3087: }
                   3088: 
                   3089: &register_handler("delusersession", \&del_usersession_handler, 0,1,0);
                   3090: 
1.382     albertel 3091: #
1.263     albertel 3092: #  Authenticate access to a user file by checking that the token the user's 
                   3093: #  passed also exists in their session file
1.227     foxr     3094: #
                   3095: # Parameters:
                   3096: #   cmd      - The request keyword that dispatched to tus.
                   3097: #   tail     - The tail of the request (colon separated parameters).
                   3098: #   client   - Filehandle open on the client.
                   3099: # Return:
                   3100: #    1.
                   3101: sub token_auth_user_file_handler {
                   3102:     my ($cmd, $tail, $client) = @_;
                   3103: 
                   3104:     my ($fname, $session) = split(/:/, $tail);
                   3105:     
                   3106:     chomp($session);
1.393     raeburn  3107:     my $reply="non_auth";
1.343     albertel 3108:     my $file = $perlvar{'lonIDsDir'}.'/'.$session.'.id';
                   3109:     if (open(ENVIN,"$file")) {
1.332     albertel 3110: 	flock(ENVIN,LOCK_SH);
1.343     albertel 3111: 	tie(my %disk_env,'GDBM_File',"$file",&GDBM_READER(),0640);
                   3112: 	if (exists($disk_env{"userfile.$fname"})) {
1.393     raeburn  3113: 	    $reply="ok";
1.343     albertel 3114: 	} else {
                   3115: 	    foreach my $envname (keys(%disk_env)) {
                   3116: 		if ($envname=~ m|^userfile\.\Q$fname\E|) {
1.393     raeburn  3117: 		    $reply="ok";
1.343     albertel 3118: 		    last;
                   3119: 		}
                   3120: 	    }
1.227     foxr     3121: 	}
1.343     albertel 3122: 	untie(%disk_env);
1.227     foxr     3123: 	close(ENVIN);
1.387     albertel 3124: 	&Reply($client, \$reply, "$cmd:$tail");
1.227     foxr     3125:     } else {
                   3126: 	&Failure($client, "invalid_token\n", "$cmd:$tail");
                   3127:     }
                   3128:     return 1;
                   3129: 
                   3130: }
                   3131: &register_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
1.229     foxr     3132: 
                   3133: #
                   3134: #   Unsubscribe from a resource.
                   3135: #
                   3136: # Parameters:
                   3137: #    $cmd      - The command that got us here.
                   3138: #    $tail     - Tail of the command (remaining parameters).
                   3139: #    $client   - File descriptor connected to client.
                   3140: # Returns
                   3141: #     0        - Requested to exit, caller should shut down.
                   3142: #     1        - Continue processing.
                   3143: #
                   3144: sub unsubscribe_handler {
                   3145:     my ($cmd, $tail, $client) = @_;
                   3146: 
                   3147:     my $userinput= "$cmd:$tail";
                   3148:     
                   3149:     my ($fname) = split(/:/,$tail); # Split in case there's extrs.
                   3150: 
                   3151:     &Debug("Unsubscribing $fname");
                   3152:     if (-e $fname) {
                   3153: 	&Debug("Exists");
                   3154: 	&Reply($client, &unsub($fname,$clientip), $userinput);
                   3155:     } else {
                   3156: 	&Failure($client, "not_found\n", $userinput);
                   3157:     }
                   3158:     return 1;
                   3159: }
                   3160: &register_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
1.263     albertel 3161: 
1.230     foxr     3162: #   Subscribe to a resource
                   3163: #
                   3164: # Parameters:
                   3165: #    $cmd      - The command that got us here.
                   3166: #    $tail     - Tail of the command (remaining parameters).
                   3167: #    $client   - File descriptor connected to client.
                   3168: # Returns
                   3169: #     0        - Requested to exit, caller should shut down.
                   3170: #     1        - Continue processing.
                   3171: #
                   3172: sub subscribe_handler {
                   3173:     my ($cmd, $tail, $client)= @_;
                   3174: 
                   3175:     my $userinput  = "$cmd:$tail";
                   3176: 
                   3177:     &Reply( $client, &subscribe($userinput,$clientip), $userinput);
                   3178: 
                   3179:     return 1;
                   3180: }
                   3181: &register_handler("sub", \&subscribe_handler, 0, 1, 0);
                   3182: 
                   3183: #
1.379     albertel 3184: #   Determine the latest version of a resource (it looks for the highest
                   3185: #   past version and then returns that +1)
1.230     foxr     3186: #
                   3187: # Parameters:
                   3188: #    $cmd      - The command that got us here.
                   3189: #    $tail     - Tail of the command (remaining parameters).
1.379     albertel 3190: #                 (Should consist of an absolute path to a file)
1.230     foxr     3191: #    $client   - File descriptor connected to client.
                   3192: # Returns
                   3193: #     0        - Requested to exit, caller should shut down.
                   3194: #     1        - Continue processing.
                   3195: #
                   3196: sub current_version_handler {
                   3197:     my ($cmd, $tail, $client) = @_;
                   3198: 
                   3199:     my $userinput= "$cmd:$tail";
                   3200:    
                   3201:     my $fname   = $tail;
                   3202:     &Reply( $client, &currentversion($fname)."\n", $userinput);
                   3203:     return 1;
                   3204: 
                   3205: }
                   3206: &register_handler("currentversion", \&current_version_handler, 0, 1, 0);
                   3207: 
                   3208: #  Make an entry in a user's activity log.
                   3209: #
                   3210: # Parameters:
                   3211: #    $cmd      - The command that got us here.
                   3212: #    $tail     - Tail of the command (remaining parameters).
                   3213: #    $client   - File descriptor connected to client.
                   3214: # Returns
                   3215: #     0        - Requested to exit, caller should shut down.
                   3216: #     1        - Continue processing.
                   3217: #
                   3218: sub activity_log_handler {
                   3219:     my ($cmd, $tail, $client) = @_;
                   3220: 
                   3221: 
                   3222:     my $userinput= "$cmd:$tail";
                   3223: 
                   3224:     my ($udom,$uname,$what)=split(/:/,$tail);
                   3225:     chomp($what);
                   3226:     my $proname=&propath($udom,$uname);
                   3227:     my $now=time;
                   3228:     my $hfh;
                   3229:     if ($hfh=IO::File->new(">>$proname/activity.log")) { 
                   3230: 	print $hfh "$now:$clientname:$what\n";
                   3231: 	&Reply( $client, "ok\n", $userinput); 
                   3232:     } else {
                   3233: 	&Failure($client, "error: ".($!+0)." IO::File->new Failed "
                   3234: 		 ."while attempting log\n", 
                   3235: 		 $userinput);
                   3236:     }
                   3237: 
                   3238:     return 1;
                   3239: }
1.263     albertel 3240: &register_handler("log", \&activity_log_handler, 0, 1, 0);
1.230     foxr     3241: 
                   3242: #
                   3243: #   Put a namespace entry in a user profile hash.
                   3244: #   My druthers would be for this to be an encrypted interaction too.
                   3245: #   anything that might be an inadvertent covert channel about either
                   3246: #   user authentication or user personal information....
                   3247: #
                   3248: # Parameters:
                   3249: #    $cmd      - The command that got us here.
                   3250: #    $tail     - Tail of the command (remaining parameters).
                   3251: #    $client   - File descriptor connected to client.
                   3252: # Returns
                   3253: #     0        - Requested to exit, caller should shut down.
                   3254: #     1        - Continue processing.
                   3255: #
                   3256: sub put_user_profile_entry {
                   3257:     my ($cmd, $tail, $client)  = @_;
1.229     foxr     3258: 
1.230     foxr     3259:     my $userinput = "$cmd:$tail";
                   3260:     
1.242     raeburn  3261:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
1.230     foxr     3262:     if ($namespace ne 'roles') {
                   3263: 	chomp($what);
                   3264: 	my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3265: 				  &GDBM_WRCREAT(),"P",$what);
                   3266: 	if($hashref) {
                   3267: 	    my @pairs=split(/\&/,$what);
                   3268: 	    foreach my $pair (@pairs) {
                   3269: 		my ($key,$value)=split(/=/,$pair);
                   3270: 		$hashref->{$key}=$value;
                   3271: 	    }
1.311     albertel 3272: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     3273: 		&Reply( $client, "ok\n", $userinput);
                   3274: 	    } else {
                   3275: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3276: 			"while attempting put\n", 
                   3277: 			$userinput);
                   3278: 	    }
                   3279: 	} else {
1.316     albertel 3280: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.230     foxr     3281: 		     "while attempting put\n", $userinput);
                   3282: 	}
                   3283:     } else {
                   3284:         &Failure( $client, "refused\n", $userinput);
                   3285:     }
                   3286:     
                   3287:     return 1;
                   3288: }
                   3289: &register_handler("put", \&put_user_profile_entry, 0, 1, 0);
                   3290: 
1.283     albertel 3291: #   Put a piece of new data in hash, returns error if entry already exists
                   3292: # Parameters:
                   3293: #    $cmd      - The command that got us here.
                   3294: #    $tail     - Tail of the command (remaining parameters).
                   3295: #    $client   - File descriptor connected to client.
                   3296: # Returns
                   3297: #     0        - Requested to exit, caller should shut down.
                   3298: #     1        - Continue processing.
                   3299: #
                   3300: sub newput_user_profile_entry {
                   3301:     my ($cmd, $tail, $client)  = @_;
                   3302: 
                   3303:     my $userinput = "$cmd:$tail";
                   3304: 
                   3305:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
                   3306:     if ($namespace eq 'roles') {
                   3307:         &Failure( $client, "refused\n", $userinput);
                   3308: 	return 1;
                   3309:     }
                   3310: 
                   3311:     chomp($what);
                   3312: 
                   3313:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3314: 				 &GDBM_WRCREAT(),"N",$what);
                   3315:     if(!$hashref) {
1.316     albertel 3316: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.283     albertel 3317: 		  "while attempting put\n", $userinput);
                   3318: 	return 1;
                   3319:     }
                   3320: 
                   3321:     my @pairs=split(/\&/,$what);
                   3322:     foreach my $pair (@pairs) {
                   3323: 	my ($key,$value)=split(/=/,$pair);
                   3324: 	if (exists($hashref->{$key})) {
1.513     raeburn  3325:             if (!&untie_user_hash($hashref)) {
                   3326:                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
                   3327:                          "while attempting newput - early out as key exists");
                   3328:             }
                   3329:             &Failure($client, "key_exists: ".$key."\n",$userinput);
                   3330:             return 1;
1.283     albertel 3331: 	}
                   3332:     }
                   3333: 
                   3334:     foreach my $pair (@pairs) {
                   3335: 	my ($key,$value)=split(/=/,$pair);
                   3336: 	$hashref->{$key}=$value;
                   3337:     }
                   3338: 
1.311     albertel 3339:     if (&untie_user_hash($hashref)) {
1.283     albertel 3340: 	&Reply( $client, "ok\n", $userinput);
                   3341:     } else {
                   3342: 	&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3343: 		 "while attempting put\n", 
                   3344: 		 $userinput);
                   3345:     }
                   3346:     return 1;
                   3347: }
                   3348: &register_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
                   3349: 
1.230     foxr     3350: # 
                   3351: #   Increment a profile entry in the user history file.
                   3352: #   The history contains keyword value pairs.  In this case,
                   3353: #   The value itself is a pair of numbers.  The first, the current value
                   3354: #   the second an increment that this function applies to the current
                   3355: #   value.
                   3356: #
                   3357: # Parameters:
                   3358: #    $cmd      - The command that got us here.
                   3359: #    $tail     - Tail of the command (remaining parameters).
                   3360: #    $client   - File descriptor connected to client.
                   3361: # Returns
                   3362: #     0        - Requested to exit, caller should shut down.
                   3363: #     1        - Continue processing.
                   3364: #
                   3365: sub increment_user_value_handler {
                   3366:     my ($cmd, $tail, $client) = @_;
                   3367:     
                   3368:     my $userinput   = "$cmd:$tail";
                   3369:     
                   3370:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
                   3371:     if ($namespace ne 'roles') {
                   3372:         chomp($what);
                   3373: 	my $hashref = &tie_user_hash($udom, $uname,
                   3374: 				     $namespace, &GDBM_WRCREAT(),
                   3375: 				     "P",$what);
                   3376: 	if ($hashref) {
                   3377: 	    my @pairs=split(/\&/,$what);
                   3378: 	    foreach my $pair (@pairs) {
                   3379: 		my ($key,$value)=split(/=/,$pair);
1.284     raeburn  3380:                 $value = &unescape($value);
1.230     foxr     3381: 		# We could check that we have a number...
                   3382: 		if (! defined($value) || $value eq '') {
                   3383: 		    $value = 1;
                   3384: 		}
                   3385: 		$hashref->{$key}+=$value;
1.284     raeburn  3386:                 if ($namespace eq 'nohist_resourcetracker') {
                   3387:                     if ($hashref->{$key} < 0) {
                   3388:                         $hashref->{$key} = 0;
                   3389:                     }
                   3390:                 }
1.230     foxr     3391: 	    }
1.311     albertel 3392: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     3393: 		&Reply( $client, "ok\n", $userinput);
                   3394: 	    } else {
                   3395: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3396: 			 "while attempting inc\n", $userinput);
                   3397: 	    }
                   3398: 	} else {
                   3399: 	    &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3400: 		     "while attempting inc\n", $userinput);
                   3401: 	}
                   3402:     } else {
                   3403: 	&Failure($client, "refused\n", $userinput);
                   3404:     }
                   3405:     
                   3406:     return 1;
                   3407: }
                   3408: &register_handler("inc", \&increment_user_value_handler, 0, 1, 0);
                   3409: 
                   3410: #
                   3411: #   Put a new role for a user.  Roles are LonCAPA's packaging of permissions.
                   3412: #   Each 'role' a user has implies a set of permissions.  Adding a new role
                   3413: #   for a person grants the permissions packaged with that role
                   3414: #   to that user when the role is selected.
                   3415: #
                   3416: # Parameters:
                   3417: #    $cmd       - The command string (rolesput).
                   3418: #    $tail      - The remainder of the request line.  For rolesput this
                   3419: #                 consists of a colon separated list that contains:
                   3420: #                 The domain and user that is granting the role (logged).
                   3421: #                 The domain and user that is getting the role.
                   3422: #                 The roles being granted as a set of & separated pairs.
                   3423: #                 each pair a key value pair.
                   3424: #    $client    - File descriptor connected to the client.
                   3425: # Returns:
                   3426: #     0         - If the daemon should exit
                   3427: #     1         - To continue processing.
                   3428: #
                   3429: #
                   3430: sub roles_put_handler {
                   3431:     my ($cmd, $tail, $client) = @_;
                   3432: 
                   3433:     my $userinput  = "$cmd:$tail";
                   3434: 
                   3435:     my ( $exedom, $exeuser, $udom, $uname,  $what) = split(/:/,$tail);
                   3436:     
                   3437: 
                   3438:     my $namespace='roles';
                   3439:     chomp($what);
                   3440:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3441: 				 &GDBM_WRCREAT(), "P",
                   3442: 				 "$exedom:$exeuser:$what");
                   3443:     #
                   3444:     #  Log the attempt to set a role.  The {}'s here ensure that the file 
                   3445:     #  handle is open for the minimal amount of time.  Since the flush
                   3446:     #  is done on close this improves the chances the log will be an un-
                   3447:     #  corrupted ordered thing.
                   3448:     if ($hashref) {
1.261     foxr     3449: 	my $pass_entry = &get_auth_type($udom, $uname);
                   3450: 	my ($auth_type,$pwd)  = split(/:/, $pass_entry);
                   3451: 	$auth_type = $auth_type.":";
1.230     foxr     3452: 	my @pairs=split(/\&/,$what);
                   3453: 	foreach my $pair (@pairs) {
                   3454: 	    my ($key,$value)=split(/=/,$pair);
                   3455: 	    &manage_permissions($key, $udom, $uname,
1.260     foxr     3456: 			       $auth_type);
1.230     foxr     3457: 	    $hashref->{$key}=$value;
                   3458: 	}
1.311     albertel 3459: 	if (&untie_user_hash($hashref)) {
1.230     foxr     3460: 	    &Reply($client, "ok\n", $userinput);
                   3461: 	} else {
                   3462: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3463: 		     "while attempting rolesput\n", $userinput);
                   3464: 	}
                   3465:     } else {
                   3466: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3467: 		 "while attempting rolesput\n", $userinput);
                   3468:     }
                   3469:     return 1;
                   3470: }
                   3471: &register_handler("rolesput", \&roles_put_handler, 1,1,0);  # Encoded client only.
                   3472: 
                   3473: #
1.231     foxr     3474: #   Deletes (removes) a role for a user.   This is equivalent to removing
                   3475: #  a permissions package associated with the role from the user's profile.
                   3476: #
                   3477: # Parameters:
                   3478: #     $cmd                 - The command (rolesdel)
                   3479: #     $tail                - The remainder of the request line. This consists
                   3480: #                             of:
                   3481: #                             The domain and user requesting the change (logged)
                   3482: #                             The domain and user being changed.
                   3483: #                             The roles being revoked.  These are shipped to us
                   3484: #                             as a bunch of & separated role name keywords.
                   3485: #     $client              - The file handle open on the client.
                   3486: # Returns:
                   3487: #     1                    - Continue processing
                   3488: #     0                    - Exit.
                   3489: #
                   3490: sub roles_delete_handler {
                   3491:     my ($cmd, $tail, $client)  = @_;
                   3492: 
                   3493:     my $userinput    = "$cmd:$tail";
                   3494:    
                   3495:     my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
                   3496:     &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
                   3497: 	   "what = ".$what);
                   3498:     my $namespace='roles';
                   3499:     chomp($what);
                   3500:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3501: 				 &GDBM_WRCREAT(), "D",
                   3502: 				 "$exedom:$exeuser:$what");
                   3503:     
                   3504:     if ($hashref) {
                   3505: 	my @rolekeys=split(/\&/,$what);
                   3506: 	
                   3507: 	foreach my $key (@rolekeys) {
                   3508: 	    delete $hashref->{$key};
                   3509: 	}
1.315     albertel 3510: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3511: 	    &Reply($client, "ok\n", $userinput);
                   3512: 	} else {
                   3513: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3514: 		     "while attempting rolesdel\n", $userinput);
                   3515: 	}
                   3516:     } else {
                   3517:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3518: 		 "while attempting rolesdel\n", $userinput);
                   3519:     }
                   3520:     
                   3521:     return 1;
                   3522: }
                   3523: &register_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
                   3524: 
                   3525: # Unencrypted get from a user's profile database.  See 
                   3526: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
                   3527: # This function retrieves a keyed item from a specific named database in the
                   3528: # user's directory.
                   3529: #
                   3530: # Parameters:
                   3531: #   $cmd             - Command request keyword (get).
                   3532: #   $tail            - Tail of the command.  This is a colon separated list
                   3533: #                      consisting of the domain and username that uniquely
                   3534: #                      identifies the profile,
                   3535: #                      The 'namespace' which selects the gdbm file to 
                   3536: #                      do the lookup in, 
                   3537: #                      & separated list of keys to lookup.  Note that
                   3538: #                      the values are returned as an & separated list too.
                   3539: #   $client          - File descriptor open on the client.
                   3540: # Returns:
                   3541: #   1       - Continue processing.
                   3542: #   0       - Exit.
                   3543: #
                   3544: sub get_profile_entry {
                   3545:     my ($cmd, $tail, $client) = @_;
                   3546: 
                   3547:     my $userinput= "$cmd:$tail";
                   3548:    
                   3549:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   3550:     chomp($what);
1.255     foxr     3551: 
1.390     raeburn  3552: 
1.255     foxr     3553:     my $replystring = read_profile($udom, $uname, $namespace, $what);
                   3554:     my ($first) = split(/:/,$replystring);
                   3555:     if($first ne "error") {
1.387     albertel 3556: 	&Reply($client, \$replystring, $userinput);
1.231     foxr     3557:     } else {
1.255     foxr     3558: 	&Failure($client, $replystring." while attempting get\n", $userinput);
1.231     foxr     3559:     }
                   3560:     return 1;
1.255     foxr     3561: 
                   3562: 
1.231     foxr     3563: }
                   3564: &register_handler("get", \&get_profile_entry, 0,1,0);
                   3565: 
                   3566: #
                   3567: #  Process the encrypted get request.  Note that the request is sent
                   3568: #  in clear, but the reply is encrypted.  This is a small covert channel:
                   3569: #  information about the sensitive keys is given to the snooper.  Just not
                   3570: #  information about the values of the sensitive key.  Hmm if I wanted to
                   3571: #  know these I'd snoop for the egets. Get the profile item names from them
                   3572: #  and then issue a get for them since there's no enforcement of the
                   3573: #  requirement of an encrypted get for particular profile items.  If I
                   3574: #  were re-doing this, I'd force the request to be encrypted as well as the
                   3575: #  reply.  I'd also just enforce encrypted transactions for all gets since
                   3576: #  that would prevent any covert channel snooping.
                   3577: #
                   3578: #  Parameters:
                   3579: #     $cmd               - Command keyword of request (eget).
1.536     raeburn  3580: #     $tail              - Tail of the command.  See GetProfileEntry
                   3581: #                          for more information about this.
1.231     foxr     3582: #     $client            - File open on the client.
                   3583: #  Returns:
                   3584: #     1      - Continue processing
                   3585: #     0      - server should exit.
                   3586: sub get_profile_entry_encrypted {
                   3587:     my ($cmd, $tail, $client) = @_;
                   3588: 
                   3589:     my $userinput = "$cmd:$tail";
                   3590:    
1.339     albertel 3591:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
1.231     foxr     3592:     chomp($what);
1.255     foxr     3593:     my $qresult = read_profile($udom, $uname, $namespace, $what);
                   3594:     my ($first) = split(/:/, $qresult);
                   3595:     if($first ne "error") {
                   3596: 	
                   3597: 	if ($cipher) {
                   3598: 	    my $cmdlength=length($qresult);
                   3599: 	    $qresult.="         ";
                   3600: 	    my $encqresult='';
                   3601: 	    for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   3602: 		$encqresult.= unpack("H16", 
                   3603: 				     $cipher->encrypt(substr($qresult,
                   3604: 							     $encidx,
                   3605: 							     8)));
                   3606: 	    }
                   3607: 	    &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
                   3608: 	} else {
1.231     foxr     3609: 		&Failure( $client, "error:no_key\n", $userinput);
                   3610: 	    }
                   3611:     } else {
1.255     foxr     3612: 	&Failure($client, "$qresult while attempting eget\n", $userinput);
                   3613: 
1.231     foxr     3614:     }
                   3615:     
                   3616:     return 1;
                   3617: }
1.255     foxr     3618: &register_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
1.263     albertel 3619: 
1.231     foxr     3620: #
                   3621: #   Deletes a key in a user profile database.
                   3622: #   
                   3623: #   Parameters:
                   3624: #       $cmd                  - Command keyword (del).
                   3625: #       $tail                 - Command tail.  IN this case a colon
                   3626: #                               separated list containing:
                   3627: #                               The domain and user that identifies uniquely
                   3628: #                               the identity of the user.
                   3629: #                               The profile namespace (name of the profile
                   3630: #                               database file).
                   3631: #                               & separated list of keywords to delete.
                   3632: #       $client              - File open on client socket.
                   3633: # Returns:
                   3634: #     1   - Continue processing
                   3635: #     0   - Exit server.
                   3636: #
                   3637: #
                   3638: sub delete_profile_entry {
                   3639:     my ($cmd, $tail, $client) = @_;
                   3640: 
                   3641:     my $userinput = "cmd:$tail";
                   3642: 
                   3643:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   3644:     chomp($what);
                   3645:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3646: 				 &GDBM_WRCREAT(),
                   3647: 				 "D",$what);
                   3648:     if ($hashref) {
                   3649:         my @keys=split(/\&/,$what);
                   3650: 	foreach my $key (@keys) {
                   3651: 	    delete($hashref->{$key});
                   3652: 	}
1.315     albertel 3653: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3654: 	    &Reply($client, "ok\n", $userinput);
                   3655: 	} else {
                   3656: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3657: 		    "while attempting del\n", $userinput);
                   3658: 	}
                   3659:     } else {
                   3660: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3661: 		 "while attempting del\n", $userinput);
                   3662:     }
                   3663:     return 1;
                   3664: }
                   3665: &register_handler("del", \&delete_profile_entry, 0, 1, 0);
1.263     albertel 3666: 
1.231     foxr     3667: #
                   3668: #  List the set of keys that are defined in a profile database file.
                   3669: #  A successful reply from this will contain an & separated list of
                   3670: #  the keys. 
                   3671: # Parameters:
                   3672: #     $cmd              - Command request (keys).
                   3673: #     $tail             - Remainder of the request, a colon separated
                   3674: #                         list containing domain/user that identifies the
                   3675: #                         user being queried, and the database namespace
                   3676: #                         (database filename essentially).
                   3677: #     $client           - File open on the client.
                   3678: #  Returns:
                   3679: #    1    - Continue processing.
                   3680: #    0    - Exit the server.
                   3681: #
                   3682: sub get_profile_keys {
                   3683:     my ($cmd, $tail, $client) = @_;
                   3684: 
                   3685:     my $userinput = "$cmd:$tail";
                   3686: 
                   3687:     my ($udom,$uname,$namespace)=split(/:/,$tail);
                   3688:     my $qresult='';
                   3689:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3690: 				  &GDBM_READER());
                   3691:     if ($hashref) {
                   3692: 	foreach my $key (keys %$hashref) {
                   3693: 	    $qresult.="$key&";
                   3694: 	}
1.315     albertel 3695: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3696: 	    $qresult=~s/\&$//;
1.387     albertel 3697: 	    &Reply($client, \$qresult, $userinput);
1.231     foxr     3698: 	} else {
                   3699: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3700: 		    "while attempting keys\n", $userinput);
                   3701: 	}
                   3702:     } else {
                   3703: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3704: 		 "while attempting keys\n", $userinput);
                   3705:     }
                   3706:    
                   3707:     return 1;
                   3708: }
                   3709: &register_handler("keys", \&get_profile_keys, 0, 1, 0);
                   3710: 
                   3711: #
                   3712: #   Dump the contents of a user profile database.
                   3713: #   Note that this constitutes a very large covert channel too since
                   3714: #   the dump will return sensitive information that is not encrypted.
                   3715: #   The naive security assumption is that the session negotiation ensures
                   3716: #   our client is trusted and I don't believe that's assured at present.
                   3717: #   Sure want badly to go to ssl or tls.  Of course if my peer isn't really
                   3718: #   a LonCAPA node they could have negotiated an encryption key too so >sigh<.
                   3719: # 
                   3720: #  Parameters:
                   3721: #     $cmd           - The command request keyword (currentdump).
                   3722: #     $tail          - Remainder of the request, consisting of a colon
                   3723: #                      separated list that has the domain/username and
                   3724: #                      the namespace to dump (database file).
                   3725: #     $client        - file open on the remote client.
                   3726: # Returns:
                   3727: #     1    - Continue processing.
                   3728: #     0    - Exit the server.
                   3729: #
                   3730: sub dump_profile_database {
                   3731:     my ($cmd, $tail, $client) = @_;
                   3732: 
1.494     droeschl 3733:     my $res = LONCAPA::Lond::dump_profile_database($tail);
                   3734: 
                   3735:     if ($res =~ /^error:/) {
                   3736:         Failure($client, \$res, "$cmd:$tail");
                   3737:     } else {
                   3738:         Reply($client, \$res, "$cmd:$tail");
                   3739:     }
                   3740: 
                   3741:     return 1;  
                   3742: 
                   3743:     #TODO remove 
1.231     foxr     3744:     my $userinput = "$cmd:$tail";
                   3745:    
                   3746:     my ($udom,$uname,$namespace) = split(/:/,$tail);
                   3747:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3748: 				 &GDBM_READER());
                   3749:     if ($hashref) {
                   3750: 	# Structure of %data:
                   3751: 	# $data{$symb}->{$parameter}=$value;
                   3752: 	# $data{$symb}->{'v.'.$parameter}=$version;
                   3753: 	# since $parameter will be unescaped, we do not
                   3754:  	# have to worry about silly parameter names...
                   3755: 	
                   3756:         my $qresult='';
                   3757: 	my %data = ();                     # A hash of anonymous hashes..
                   3758: 	while (my ($key,$value) = each(%$hashref)) {
                   3759: 	    my ($v,$symb,$param) = split(/:/,$key);
                   3760: 	    next if ($v eq 'version' || $symb eq 'keys');
                   3761: 	    next if (exists($data{$symb}) && 
                   3762: 		     exists($data{$symb}->{$param}) &&
                   3763: 		     $data{$symb}->{'v.'.$param} > $v);
                   3764: 	    $data{$symb}->{$param}=$value;
                   3765: 	    $data{$symb}->{'v.'.$param}=$v;
                   3766: 	}
1.311     albertel 3767: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3768: 	    while (my ($symb,$param_hash) = each(%data)) {
                   3769: 		while(my ($param,$value) = each (%$param_hash)){
                   3770: 		    next if ($param =~ /^v\./);       # Ignore versions...
                   3771: 		    #
                   3772: 		    #   Just dump the symb=value pairs separated by &
                   3773: 		    #
                   3774: 		    $qresult.=$symb.':'.$param.'='.$value.'&';
                   3775: 		}
                   3776: 	    }
                   3777: 	    chop($qresult);
1.387     albertel 3778: 	    &Reply($client , \$qresult, $userinput);
1.231     foxr     3779: 	} else {
                   3780: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3781: 		     "while attempting currentdump\n", $userinput);
                   3782: 	}
                   3783:     } else {
                   3784: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3785: 		"while attempting currentdump\n", $userinput);
                   3786:     }
                   3787: 
                   3788:     return 1;
                   3789: }
                   3790: &register_handler("currentdump", \&dump_profile_database, 0, 1, 0);
                   3791: 
                   3792: #
                   3793: #   Dump a profile database with an optional regular expression
                   3794: #   to match against the keys.  In this dump, no effort is made
                   3795: #   to separate symb from version information. Presumably the
                   3796: #   databases that are dumped by this command are of a different
                   3797: #   structure.  Need to look at this and improve the documentation of
                   3798: #   both this and the currentdump handler.
                   3799: # Parameters:
                   3800: #    $cmd                     - The command keyword.
                   3801: #    $tail                    - All of the characters after the $cmd:
                   3802: #                               These are expected to be a colon
                   3803: #                               separated list containing:
                   3804: #                               domain/user - identifying the user.
                   3805: #                               namespace   - identifying the database.
                   3806: #                               regexp      - optional regular expression
                   3807: #                                             that is matched against
                   3808: #                                             database keywords to do
                   3809: #                                             selective dumps.
1.488     raeburn  3810: #                               range       - optional range of entries
                   3811: #                                             e.g., 10-20 would return the
                   3812: #                                             10th to 19th items, etc.  
1.231     foxr     3813: #   $client                   - Channel open on the client.
                   3814: # Returns:
                   3815: #    1    - Continue processing.
                   3816: # Side effects:
                   3817: #    response is written to $client.
                   3818: #
                   3819: sub dump_with_regexp {
                   3820:     my ($cmd, $tail, $client) = @_;
                   3821: 
1.494     droeschl 3822:     my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
1.490     droeschl 3823:     
                   3824:     if ($res =~ /^error:/) {
                   3825:         Failure($client, \$res, "$cmd:$tail");
                   3826:     } else {
                   3827:         Reply($client, \$res, "$cmd:$tail");
                   3828:     }
1.231     foxr     3829: 
                   3830:     return 1;
                   3831: }
                   3832: &register_handler("dump", \&dump_with_regexp, 0, 1, 0);
                   3833: 
1.568     raeburn  3834: #
                   3835: #  Process the encrypted dump request. Original call should
                   3836: #  be from lonnet::dump() with seventh arg ($encrypt) set to
                   3837: #  1, to ensure that both request and response are encrypted.
                   3838: #
                   3839: #  Parameters:
                   3840: #     $cmd               - Command keyword of request (edump).
                   3841: #     $tail              - Tail of the command.
                   3842: #                          See &dump_with_regexp for more
                   3843: #                          information about this.
                   3844: #     $client            - File open on the client.
                   3845: #  Returns:
                   3846: #     1      - Continue processing
                   3847: #     0      - server should exit.
                   3848: #
                   3849: 
                   3850: sub encrypted_dump_with_regexp {
                   3851:     my ($cmd, $tail, $client) = @_;
                   3852:     my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
                   3853: 
                   3854:     if ($res =~ /^error:/) {
                   3855:         Failure($client, \$res, "$cmd:$tail");
                   3856:     } else {
                   3857:         if ($cipher) {
                   3858:             my $cmdlength=length($res);
                   3859:             $res.="         ";
                   3860:             my $encres='';
                   3861:             for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   3862:                 $encres.= unpack("H16",
                   3863:                                  $cipher->encrypt(substr($res,
                   3864:                                                          $encidx,
                   3865:                                                          8)));
                   3866:             }
                   3867:             &Reply( $client,"enc:$cmdlength:$encres\n","$cmd:$tail");
                   3868:         } else {
                   3869:             &Failure( $client, "error:no_key\n","$cmd:$tail");
                   3870:         }
                   3871:     }
                   3872: }
                   3873: &register_handler("edump", \&encrypted_dump_with_regexp, 0, 1, 0);
                   3874: 
1.231     foxr     3875: #  Store a set of key=value pairs associated with a versioned name.
                   3876: #
                   3877: #  Parameters:
                   3878: #    $cmd                - Request command keyword.
                   3879: #    $tail               - Tail of the request.  This is a colon
                   3880: #                          separated list containing:
                   3881: #                          domain/user - User and authentication domain.
                   3882: #                          namespace   - Name of the database being modified
                   3883: #                          rid         - Resource keyword to modify.
                   3884: #                          what        - new value associated with rid.
1.512     raeburn  3885: #                          laststore   - (optional) version=timestamp
                   3886: #                                        for most recent transaction for rid
                   3887: #                                        in namespace, when cstore was called
1.231     foxr     3888: #
                   3889: #    $client             - Socket open on the client.
                   3890: #
                   3891: #
                   3892: #  Returns:
                   3893: #      1 (keep on processing).
                   3894: #  Side-Effects:
                   3895: #    Writes to the client
1.512     raeburn  3896: #    Successful storage will cause either 'ok', or, if $laststore was included
                   3897: #    in the tail of the request, and the version number for the last transaction
                   3898: #    is larger than the version in $laststore, delay:$numtrans , where $numtrans
                   3899: #    is the number of store evevnts recorded for rid in namespace since
                   3900: #    lonnet::store() was called by the client.
                   3901: #
1.231     foxr     3902: sub store_handler {
                   3903:     my ($cmd, $tail, $client) = @_;
                   3904:  
                   3905:     my $userinput = "$cmd:$tail";
1.512     raeburn  3906:     chomp($tail);
                   3907:     my ($udom,$uname,$namespace,$rid,$what,$laststore) =split(/:/,$tail);
1.231     foxr     3908:     if ($namespace ne 'roles') {
                   3909: 
                   3910: 	my @pairs=split(/\&/,$what);
                   3911: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
1.268     albertel 3912: 				       &GDBM_WRCREAT(), "S",
1.231     foxr     3913: 				       "$rid:$what");
                   3914: 	if ($hashref) {
                   3915: 	    my $now = time;
1.512     raeburn  3916:             my $numtrans;
                   3917:             if ($laststore) {
                   3918:                 my ($previousversion,$previoustime) = split(/\=/,$laststore);
                   3919:                 my ($lastversion,$lasttime) = (0,0);
                   3920:                 $lastversion = $hashref->{"version:$rid"};
                   3921:                 if ($lastversion) {
                   3922:                     $lasttime = $hashref->{"$lastversion:$rid:timestamp"};
                   3923:                 }
                   3924:                 if (($previousversion) && ($previousversion !~ /\D/)) {
                   3925:                     if (($lastversion > $previousversion) && ($lasttime >= $previoustime)) {
                   3926:                         $numtrans = $lastversion - $previousversion;
                   3927:                     }
                   3928:                 } elsif ($lastversion) {
                   3929:                     $numtrans = $lastversion;
                   3930:                 }
                   3931:                 if ($numtrans) {
                   3932:                     $numtrans =~ s/D//g;
                   3933:                 }
                   3934:             }
1.231     foxr     3935: 	    $hashref->{"version:$rid"}++;
                   3936: 	    my $version=$hashref->{"version:$rid"};
                   3937: 	    my $allkeys=''; 
                   3938: 	    foreach my $pair (@pairs) {
                   3939: 		my ($key,$value)=split(/=/,$pair);
                   3940: 		$allkeys.=$key.':';
                   3941: 		$hashref->{"$version:$rid:$key"}=$value;
                   3942: 	    }
                   3943: 	    $hashref->{"$version:$rid:timestamp"}=$now;
                   3944: 	    $allkeys.='timestamp';
                   3945: 	    $hashref->{"$version:keys:$rid"}=$allkeys;
1.311     albertel 3946: 	    if (&untie_user_hash($hashref)) {
1.512     raeburn  3947:                 my $msg = 'ok';
                   3948:                 if ($numtrans) {
                   3949:                     $msg = 'delay:'.$numtrans;
                   3950:                 }
                   3951: 		&Reply($client, "$msg\n", $userinput);
1.231     foxr     3952: 	    } else {
                   3953: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3954: 			"while attempting store\n", $userinput);
                   3955: 	    }
                   3956: 	} else {
                   3957: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3958: 		     "while attempting store\n", $userinput);
                   3959: 	}
                   3960:     } else {
                   3961: 	&Failure($client, "refused\n", $userinput);
                   3962:     }
                   3963: 
                   3964:     return 1;
                   3965: }
                   3966: &register_handler("store", \&store_handler, 0, 1, 0);
1.263     albertel 3967: 
1.323     albertel 3968: #  Modify a set of key=value pairs associated with a versioned name.
                   3969: #
                   3970: #  Parameters:
                   3971: #    $cmd                - Request command keyword.
                   3972: #    $tail               - Tail of the request.  This is a colon
                   3973: #                          separated list containing:
                   3974: #                          domain/user - User and authentication domain.
                   3975: #                          namespace   - Name of the database being modified
                   3976: #                          rid         - Resource keyword to modify.
                   3977: #                          v           - Version item to modify
                   3978: #                          what        - new value associated with rid.
                   3979: #
                   3980: #    $client             - Socket open on the client.
                   3981: #
                   3982: #
                   3983: #  Returns:
                   3984: #      1 (keep on processing).
                   3985: #  Side-Effects:
                   3986: #    Writes to the client
                   3987: sub putstore_handler {
                   3988:     my ($cmd, $tail, $client) = @_;
                   3989:  
                   3990:     my $userinput = "$cmd:$tail";
                   3991: 
                   3992:     my ($udom,$uname,$namespace,$rid,$v,$what) =split(/:/,$tail);
                   3993:     if ($namespace ne 'roles') {
                   3994: 
                   3995: 	chomp($what);
                   3996: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
                   3997: 				       &GDBM_WRCREAT(), "M",
                   3998: 				       "$rid:$v:$what");
                   3999: 	if ($hashref) {
                   4000: 	    my $now = time;
                   4001: 	    my %data = &hash_extract($what);
                   4002: 	    my @allkeys;
                   4003: 	    while (my($key,$value) = each(%data)) {
                   4004: 		push(@allkeys,$key);
                   4005: 		$hashref->{"$v:$rid:$key"} = $value;
                   4006: 	    }
                   4007: 	    my $allkeys = join(':',@allkeys);
                   4008: 	    $hashref->{"$v:keys:$rid"}=$allkeys;
                   4009: 
                   4010: 	    if (&untie_user_hash($hashref)) {
                   4011: 		&Reply($client, "ok\n", $userinput);
                   4012: 	    } else {
                   4013: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4014: 			"while attempting store\n", $userinput);
                   4015: 	    }
                   4016: 	} else {
                   4017: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4018: 		     "while attempting store\n", $userinput);
                   4019: 	}
                   4020:     } else {
                   4021: 	&Failure($client, "refused\n", $userinput);
                   4022:     }
                   4023: 
                   4024:     return 1;
                   4025: }
                   4026: &register_handler("putstore", \&putstore_handler, 0, 1, 0);
                   4027: 
                   4028: sub hash_extract {
                   4029:     my ($str)=@_;
                   4030:     my %hash;
                   4031:     foreach my $pair (split(/\&/,$str)) {
                   4032: 	my ($key,$value)=split(/=/,$pair);
                   4033: 	$hash{$key}=$value;
                   4034:     }
                   4035:     return (%hash);
                   4036: }
                   4037: sub hash_to_str {
                   4038:     my ($hash_ref)=@_;
                   4039:     my $str;
                   4040:     foreach my $key (keys(%$hash_ref)) {
                   4041: 	$str.=$key.'='.$hash_ref->{$key}.'&';
                   4042:     }
                   4043:     $str=~s/\&$//;
                   4044:     return $str;
                   4045: }
                   4046: 
1.231     foxr     4047: #
                   4048: #  Dump out all versions of a resource that has key=value pairs associated
                   4049: # with it for each version.  These resources are built up via the store
                   4050: # command.
                   4051: #
                   4052: #  Parameters:
                   4053: #     $cmd               - Command keyword.
                   4054: #     $tail              - Remainder of the request which consists of:
                   4055: #                          domain/user   - User and auth. domain.
                   4056: #                          namespace     - name of resource database.
                   4057: #                          rid           - Resource id.
                   4058: #    $client             - socket open on the client.
                   4059: #
                   4060: # Returns:
                   4061: #      1  indicating the caller should not yet exit.
                   4062: # Side-effects:
                   4063: #   Writes a reply to the client.
                   4064: #   The reply is a string of the following shape:
                   4065: #   version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
                   4066: #    Where the 1 above represents version 1.
                   4067: #    this continues for all pairs of keys in all versions.
                   4068: #
                   4069: #
                   4070: #    
                   4071: #
                   4072: sub restore_handler {
                   4073:     my ($cmd, $tail, $client) = @_;
                   4074: 
                   4075:     my $userinput = "$cmd:$tail";	# Only used for logging purposes.
1.351     banghart 4076:     my ($udom,$uname,$namespace,$rid) = split(/:/,$tail);
1.352     albertel 4077:     $namespace=~s/\//\_/g;
1.350     albertel 4078:     $namespace = &LONCAPA::clean_username($namespace);
1.349     albertel 4079: 
1.231     foxr     4080:     chomp($rid);
                   4081:     my $qresult='';
1.309     albertel 4082:     my $hashref = &tie_user_hash($udom, $uname, $namespace, &GDBM_READER());
                   4083:     if ($hashref) {
                   4084: 	my $version=$hashref->{"version:$rid"};
1.231     foxr     4085: 	$qresult.="version=$version&";
                   4086: 	my $scope;
                   4087: 	for ($scope=1;$scope<=$version;$scope++) {
1.309     albertel 4088: 	    my $vkeys=$hashref->{"$scope:keys:$rid"};
1.231     foxr     4089: 	    my @keys=split(/:/,$vkeys);
                   4090: 	    my $key;
                   4091: 	    $qresult.="$scope:keys=$vkeys&";
                   4092: 	    foreach $key (@keys) {
1.309     albertel 4093: 		$qresult.="$scope:$key=".$hashref->{"$scope:$rid:$key"}."&";
1.231     foxr     4094: 	    }                                  
                   4095: 	}
1.311     albertel 4096: 	if (&untie_user_hash($hashref)) {
1.231     foxr     4097: 	    $qresult=~s/\&$//;
1.387     albertel 4098: 	    &Reply( $client, \$qresult, $userinput);
1.231     foxr     4099: 	} else {
                   4100: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4101: 		    "while attempting restore\n", $userinput);
                   4102: 	}
                   4103:     } else {
                   4104: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4105: 		"while attempting restore\n", $userinput);
                   4106:     }
                   4107:   
                   4108:     return 1;
                   4109: 
                   4110: 
                   4111: }
                   4112: &register_handler("restore", \&restore_handler, 0,1,0);
1.234     foxr     4113: 
                   4114: #
1.324     raeburn  4115: #   Add a chat message to a synchronous discussion board.
1.234     foxr     4116: #
                   4117: # Parameters:
                   4118: #    $cmd                - Request keyword.
                   4119: #    $tail               - Tail of the command. A colon separated list
                   4120: #                          containing:
                   4121: #                          cdom    - Domain on which the chat board lives
1.324     raeburn  4122: #                          cnum    - Course containing the chat board.
                   4123: #                          newpost - Body of the posting.
                   4124: #                          group   - Optional group, if chat board is only 
                   4125: #                                    accessible in a group within the course 
1.234     foxr     4126: #   $client              - Socket open on the client.
                   4127: # Returns:
                   4128: #   1    - Indicating caller should keep on processing.
                   4129: #
                   4130: # Side-effects:
                   4131: #   writes a reply to the client.
                   4132: #
                   4133: #
                   4134: sub send_chat_handler {
                   4135:     my ($cmd, $tail, $client) = @_;
                   4136: 
                   4137:     
                   4138:     my $userinput = "$cmd:$tail";
                   4139: 
1.324     raeburn  4140:     my ($cdom,$cnum,$newpost,$group)=split(/\:/,$tail);
                   4141:     &chat_add($cdom,$cnum,$newpost,$group);
1.234     foxr     4142:     &Reply($client, "ok\n", $userinput);
                   4143: 
                   4144:     return 1;
                   4145: }
                   4146: &register_handler("chatsend", \&send_chat_handler, 0, 1, 0);
1.263     albertel 4147: 
1.234     foxr     4148: #
1.324     raeburn  4149: #   Retrieve the set of chat messages from a discussion board.
1.234     foxr     4150: #
                   4151: #  Parameters:
                   4152: #    $cmd             - Command keyword that initiated the request.
                   4153: #    $tail            - Remainder of the request after the command
                   4154: #                       keyword.  In this case a colon separated list of
                   4155: #                       chat domain    - Which discussion board.
                   4156: #                       chat id        - Discussion thread(?)
                   4157: #                       domain/user    - Authentication domain and username
                   4158: #                                        of the requesting person.
1.324     raeburn  4159: #                       group          - Optional course group containing
                   4160: #                                        the board.      
1.234     foxr     4161: #   $client           - Socket open on the client program.
                   4162: # Returns:
                   4163: #    1     - continue processing
                   4164: # Side effects:
                   4165: #    Response is written to the client.
                   4166: #
                   4167: sub retrieve_chat_handler {
                   4168:     my ($cmd, $tail, $client) = @_;
                   4169: 
                   4170: 
                   4171:     my $userinput = "$cmd:$tail";
                   4172: 
1.324     raeburn  4173:     my ($cdom,$cnum,$udom,$uname,$group)=split(/\:/,$tail);
1.234     foxr     4174:     my $reply='';
1.324     raeburn  4175:     foreach (&get_chat($cdom,$cnum,$udom,$uname,$group)) {
1.234     foxr     4176: 	$reply.=&escape($_).':';
                   4177:     }
                   4178:     $reply=~s/\:$//;
1.387     albertel 4179:     &Reply($client, \$reply, $userinput);
1.234     foxr     4180: 
                   4181: 
                   4182:     return 1;
                   4183: }
                   4184: &register_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
                   4185: 
                   4186: #
                   4187: #  Initiate a query of an sql database.  SQL query repsonses get put in
                   4188: #  a file for later retrieval.  This prevents sql query results from
                   4189: #  bottlenecking the system.  Note that with loncnew, perhaps this is
                   4190: #  less of an issue since multiple outstanding requests can be concurrently
                   4191: #  serviced.
                   4192: #
                   4193: #  Parameters:
1.535     raeburn  4194: #     $cmd       - Command keyword that initiated the request.
1.234     foxr     4195: #     $tail      - Remainder of the command after the keyword.
                   4196: #                  For this function, this consists of a query and
                   4197: #                  3 arguments that are self-documentingly labelled
                   4198: #                  in the original arg1, arg2, arg3.
                   4199: #     $client    - Socket open on the client.
                   4200: # Return:
                   4201: #    1   - Indicating processing should continue.
                   4202: # Side-effects:
                   4203: #    a reply is written to $client.
                   4204: #
                   4205: sub send_query_handler {
                   4206:     my ($cmd, $tail, $client) = @_;
                   4207: 
                   4208:     my $userinput = "$cmd:$tail";
                   4209: 
                   4210:     my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
                   4211:     $query=~s/\n*$//g;
1.534     raeburn  4212:     if (($query eq 'usersearch') || ($query eq 'instdirsearch')) {
                   4213:         my $usersearchconf = &get_usersearch_config($currentdomainid,'directorysrch');
                   4214:         my $earlyout;
                   4215:         if (ref($usersearchconf) eq 'HASH') {
                   4216:             if ($currentdomainid eq $clienthomedom) {
                   4217:                 if ($query eq 'usersearch') {
                   4218:                     if ($usersearchconf->{'lcavailable'} eq '0') {
                   4219:                         $earlyout = 1;
                   4220:                     }
                   4221:                 } else {
                   4222:                     if ($usersearchconf->{'available'} eq '0') {
                   4223:                         $earlyout = 1;
                   4224:                     }
                   4225:                 }
                   4226:             } else {
                   4227:                 if ($query eq 'usersearch') {
                   4228:                     if ($usersearchconf->{'lclocalonly'}) {
                   4229:                         $earlyout = 1;
                   4230:                     }
                   4231:                 } else {
                   4232:                     if ($usersearchconf->{'localonly'}) {
                   4233:                         $earlyout = 1;
                   4234:                     }
                   4235:                 }
                   4236:             }
                   4237:         }
                   4238:         if ($earlyout) {
                   4239:             &Reply($client, "query_not_authorized\n");
                   4240:             return 1;
                   4241:         }
                   4242:     }
1.234     foxr     4243:     &Reply($client, "". &sql_reply("$clientname\&$query".
                   4244: 				"\&$arg1"."\&$arg2"."\&$arg3")."\n",
                   4245: 	  $userinput);
                   4246:     
                   4247:     return 1;
                   4248: }
                   4249: &register_handler("querysend", \&send_query_handler, 0, 1, 0);
                   4250: 
                   4251: #
                   4252: #   Add a reply to an sql query.  SQL queries are done asyncrhonously.
                   4253: #   The query is submitted via a "querysend" transaction.
                   4254: #   There it is passed on to the lonsql daemon, queued and issued to
                   4255: #   mysql.
                   4256: #     This transaction is invoked when the sql transaction is complete
                   4257: #   it stores the query results in flie and indicates query completion.
                   4258: #   presumably local software then fetches this response... I'm guessing
                   4259: #   the sequence is: lonc does a querysend, we ask lonsql to do it.
                   4260: #   lonsql on completion of the query interacts with the lond of our
                   4261: #   client to do a query reply storing two files:
                   4262: #    - id     - The results of the query.
                   4263: #    - id.end - Indicating the transaction completed. 
                   4264: #    NOTE: id is a unique id assigned to the query and querysend time.
                   4265: # Parameters:
                   4266: #    $cmd        - Command keyword that initiated this request.
                   4267: #    $tail       - Remainder of the tail.  In this case that's a colon
                   4268: #                  separated list containing the query Id and the 
                   4269: #                  results of the query.
                   4270: #    $client     - Socket open on the client.
                   4271: # Return:
                   4272: #    1           - Indicating that we should continue processing.
                   4273: # Side effects:
                   4274: #    ok written to the client.
                   4275: #
                   4276: sub reply_query_handler {
                   4277:     my ($cmd, $tail, $client) = @_;
                   4278: 
                   4279: 
                   4280:     my $userinput = "$cmd:$tail";
                   4281: 
1.339     albertel 4282:     my ($id,$reply)=split(/:/,$tail); 
1.234     foxr     4283:     my $store;
                   4284:     my $execdir=$perlvar{'lonDaemons'};
                   4285:     if ($store=IO::File->new(">$execdir/tmp/$id")) {
                   4286: 	$reply=~s/\&/\n/g;
                   4287: 	print $store $reply;
                   4288: 	close $store;
                   4289: 	my $store2=IO::File->new(">$execdir/tmp/$id.end");
                   4290: 	print $store2 "done\n";
                   4291: 	close $store2;
                   4292: 	&Reply($client, "ok\n", $userinput);
                   4293:     } else {
                   4294: 	&Failure($client, "error: ".($!+0)
                   4295: 		." IO::File->new Failed ".
                   4296: 		"while attempting queryreply\n", $userinput);
                   4297:     }
                   4298:  
                   4299: 
                   4300:     return 1;
                   4301: }
                   4302: &register_handler("queryreply", \&reply_query_handler, 0, 1, 0);
                   4303: 
                   4304: #
                   4305: #  Process the courseidput request.  Not quite sure what this means
                   4306: #  at the system level sense.  It appears a gdbm file in the 
                   4307: #  /home/httpd/lonUsers/$domain/nohist_courseids is tied and
                   4308: #  a set of entries made in that database.
                   4309: #
                   4310: # Parameters:
                   4311: #   $cmd      - The command keyword that initiated this request.
                   4312: #   $tail     - Tail of the command.  In this case consists of a colon
                   4313: #               separated list contaning the domain to apply this to and
                   4314: #               an ampersand separated list of keyword=value pairs.
1.272     raeburn  4315: #               Each value is a colon separated list that includes:  
                   4316: #               description, institutional code and course owner.
                   4317: #               For backward compatibility with versions included
                   4318: #               in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
                   4319: #               code and/or course owner are preserved from the existing 
                   4320: #               record when writing a new record in response to 1.1 or 
                   4321: #               1.2 implementations of lonnet::flushcourselogs().   
                   4322: #                      
1.234     foxr     4323: #   $client   - Socket open on the client.
                   4324: # Returns:
                   4325: #   1    - indicating that processing should continue
                   4326: #
                   4327: # Side effects:
                   4328: #   reply is written to the client.
                   4329: #
                   4330: sub put_course_id_handler {
                   4331:     my ($cmd, $tail, $client) = @_;
                   4332: 
                   4333: 
                   4334:     my $userinput = "$cmd:$tail";
                   4335: 
1.266     raeburn  4336:     my ($udom, $what) = split(/:/, $tail,2);
1.234     foxr     4337:     chomp($what);
                   4338:     my $now=time;
                   4339:     my @pairs=split(/\&/,$what);
                   4340: 
                   4341:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   4342:     if ($hashref) {
                   4343: 	foreach my $pair (@pairs) {
1.271     raeburn  4344:             my ($key,$courseinfo) = split(/=/,$pair,2);
                   4345:             $courseinfo =~ s/=/:/g;
1.384     raeburn  4346:             if (defined($hashref->{$key})) {
                   4347:                 my $value = &Apache::lonnet::thaw_unescape($hashref->{$key});
                   4348:                 if (ref($value) eq 'HASH') {
                   4349:                     my @items = ('description','inst_code','owner','type');
                   4350:                     my @new_items = split(/:/,$courseinfo,-1);
                   4351:                     my %storehash; 
                   4352:                     for (my $i=0; $i<@new_items; $i++) {
1.391     raeburn  4353:                         $storehash{$items[$i]} = &unescape($new_items[$i]);
1.384     raeburn  4354:                     }
                   4355:                     $hashref->{$key} = 
                   4356:                         &Apache::lonnet::freeze_escape(\%storehash);
                   4357:                     my $unesc_key = &unescape($key);
                   4358:                     $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
                   4359:                     next;
1.383     raeburn  4360:                 }
1.384     raeburn  4361:             }
                   4362:             my @current_items = split(/:/,$hashref->{$key},-1);
                   4363:             shift(@current_items); # remove description
                   4364:             pop(@current_items);   # remove last access
                   4365:             my $numcurrent = scalar(@current_items);
                   4366:             if ($numcurrent > 3) {
                   4367:                 $numcurrent = 3;
                   4368:             }
                   4369:             my @new_items = split(/:/,$courseinfo,-1);
                   4370:             my $numnew = scalar(@new_items);
                   4371:             if ($numcurrent > 0) {
                   4372:                 if ($numnew <= $numcurrent) { # flushcourselogs() from pre 2.2 
                   4373:                     for (my $j=$numcurrent-$numnew; $j>=0; $j--) {
                   4374:                         $courseinfo .= ':'.$current_items[$numcurrent-$j-1];
1.333     raeburn  4375:                     }
1.272     raeburn  4376:                 }
                   4377:             }
1.384     raeburn  4378:             $hashref->{$key}=$courseinfo.':'.$now;
1.234     foxr     4379: 	}
1.311     albertel 4380: 	if (&untie_domain_hash($hashref)) {
1.253     foxr     4381: 	    &Reply( $client, "ok\n", $userinput);
1.234     foxr     4382: 	} else {
1.253     foxr     4383: 	    &Failure($client, "error: ".($!+0)
1.234     foxr     4384: 		     ." untie(GDBM) Failed ".
                   4385: 		     "while attempting courseidput\n", $userinput);
                   4386: 	}
                   4387:     } else {
1.253     foxr     4388: 	&Failure($client, "error: ".($!+0)
1.234     foxr     4389: 		 ." tie(GDBM) Failed ".
                   4390: 		 "while attempting courseidput\n", $userinput);
                   4391:     }
                   4392: 
                   4393:     return 1;
                   4394: }
                   4395: &register_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
                   4396: 
1.383     raeburn  4397: sub put_course_id_hash_handler {
                   4398:     my ($cmd, $tail, $client) = @_;
                   4399:     my $userinput = "$cmd:$tail";
1.384     raeburn  4400:     my ($udom,$mode,$what) = split(/:/, $tail,3);
1.383     raeburn  4401:     chomp($what);
                   4402:     my $now=time;
                   4403:     my @pairs=split(/\&/,$what);
1.384     raeburn  4404:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
1.383     raeburn  4405:     if ($hashref) {
                   4406:         foreach my $pair (@pairs) {
                   4407:             my ($key,$value)=split(/=/,$pair);
1.384     raeburn  4408:             my $unesc_key = &unescape($key);
                   4409:             if ($mode ne 'timeonly') {
                   4410:                 if (!defined($hashref->{&escape('lasttime:'.$unesc_key)})) {
                   4411:                     my $curritems = &Apache::lonnet::thaw_unescape($key); 
                   4412:                     if (ref($curritems) ne 'HASH') {
                   4413:                         my @current_items = split(/:/,$hashref->{$key},-1);
                   4414:                         my $lasttime = pop(@current_items);
                   4415:                         $hashref->{&escape('lasttime:'.$unesc_key)} = $lasttime;
                   4416:                     } else {
                   4417:                         $hashref->{&escape('lasttime:'.$unesc_key)} = '';
                   4418:                     }
                   4419:                 } 
                   4420:                 $hashref->{$key} = $value;
                   4421:             }
                   4422:             if ($mode ne 'notime') {
                   4423:                 $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
                   4424:             }
1.383     raeburn  4425:         }
                   4426:         if (&untie_domain_hash($hashref)) {
                   4427:             &Reply($client, "ok\n", $userinput);
                   4428:         } else {
                   4429:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4430:                      "while attempting courseidputhash\n", $userinput);
                   4431:         }
                   4432:     } else {
                   4433:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4434:                   "while attempting courseidputhash\n", $userinput);
                   4435:     }
                   4436:     return 1;
                   4437: }
                   4438: &register_handler("courseidputhash", \&put_course_id_hash_handler, 0, 1, 0);
                   4439: 
1.234     foxr     4440: #  Retrieves the value of a course id resource keyword pattern
                   4441: #  defined since a starting date.  Both the starting date and the
                   4442: #  keyword pattern are optional.  If the starting date is not supplied it
                   4443: #  is treated as the beginning of time.  If the pattern is not found,
                   4444: #  it is treatred as "." matching everything.
                   4445: #
                   4446: #  Parameters:
                   4447: #     $cmd     - Command keyword that resulted in us being dispatched.
                   4448: #     $tail    - The remainder of the command that, in this case, consists
                   4449: #                of a colon separated list of:
                   4450: #                 domain   - The domain in which the course database is 
                   4451: #                            defined.
                   4452: #                 since    - Optional parameter describing the minimum
                   4453: #                            time of definition(?) of the resources that
                   4454: #                            will match the dump.
                   4455: #                 description - regular expression that is used to filter
                   4456: #                            the dump.  Only keywords matching this regexp
                   4457: #                            will be used.
1.272     raeburn  4458: #                 institutional code - optional supplied code to filter 
                   4459: #                            the dump. Only courses with an institutional code 
                   4460: #                            that match the supplied code will be returned.
1.336     raeburn  4461: #                 owner    - optional supplied username and domain of owner to
                   4462: #                            filter the dump.  Only courses for which the course
                   4463: #                            owner matches the supplied username and/or domain
                   4464: #                            will be returned. Pre-2.2.0 legacy entries from 
                   4465: #                            nohist_courseiddump will only contain usernames.
1.384     raeburn  4466: #                 type     - optional parameter for selection 
1.418     raeburn  4467: #                 regexp_ok - if 1 or -1 allow the supplied institutional code
                   4468: #                            filter to behave as a regular expression:
                   4469: #	                      1 will not exclude the course if the instcode matches the RE 
                   4470: #                            -1 will exclude the course if the instcode matches the RE
1.384     raeburn  4471: #                 rtn_as_hash - whether to return the information available for
                   4472: #                            each matched item as a frozen hash of all 
                   4473: #                            key, value pairs in the item's hash, or as a 
                   4474: #                            colon-separated list of (in order) description,
                   4475: #                            institutional code, and course owner.
1.404     raeburn  4476: #                 selfenrollonly - filter by courses allowing self-enrollment  
                   4477: #                                  now or in the future (selfenrollonly = 1).
                   4478: #                 catfilter - filter by course category, assigned to a course 
                   4479: #                             using manually defined categories (i.e., not
1.407     raeburn  4480: #                             self-cataloging based on on institutional code).   
1.404     raeburn  4481: #                 showhidden - include course in results even if course  
1.407     raeburn  4482: #                              was set to be excluded from course catalog (DC only).
1.404     raeburn  4483: #                 caller -  if set to 'coursecatalog', courses set to be hidden
                   4484: #                           from course catalog will be excluded from results (unless
                   4485: #                           overridden by "showhidden".
1.427     raeburn  4486: #                 cloner - escaped username:domain of course cloner (if picking course to
1.419     raeburn  4487: #                          clone).
                   4488: #                 cc_clone_list - escaped comma separated list of courses for which 
                   4489: #                                 course cloner has active CC role (and so can clone
                   4490: #                                 automatically).
1.427     raeburn  4491: #                 cloneonly - filter by courses for which cloner has rights to clone.
                   4492: #                 createdbefore - include courses for which creation date preceeded this date.
                   4493: #                 createdafter - include courses for which creation date followed this date.
                   4494: #                 creationcontext - include courses created in specified context 
1.404     raeburn  4495: #
1.445     raeburn  4496: #                 domcloner - flag to indicate if user can create CCs in course's domain.
1.505     raeburn  4497: #                             If so, ability to clone course is automatic.
                   4498: #                 hasuniquecode - filter by courses for which a six character unique code has 
                   4499: #                                 been set.
1.445     raeburn  4500: #
1.234     foxr     4501: #     $client  - The socket open on the client.
                   4502: # Returns:
                   4503: #    1     - Continue processing.
                   4504: # Side Effects:
                   4505: #   a reply is written to $client.
                   4506: sub dump_course_id_handler {
                   4507:     my ($cmd, $tail, $client) = @_;
1.494     droeschl 4508: 
                   4509:     my $res = LONCAPA::Lond::dump_course_id_handler($tail);
                   4510:     if ($res =~ /^error:/) {
                   4511:         Failure($client, \$res, "$cmd:$tail");
                   4512:     } else {
                   4513:         Reply($client, \$res, "$cmd:$tail");
                   4514:     }
                   4515: 
                   4516:     return 1;  
                   4517: 
                   4518:     #TODO remove
1.234     foxr     4519:     my $userinput = "$cmd:$tail";
                   4520: 
1.333     raeburn  4521:     my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter,
1.404     raeburn  4522:         $typefilter,$regexp_ok,$rtn_as_hash,$selfenrollonly,$catfilter,$showhidden,
1.427     raeburn  4523:         $caller,$cloner,$cc_clone_list,$cloneonly,$createdbefore,$createdafter,
1.505     raeburn  4524:         $creationcontext,$domcloner,$hasuniquecode) =split(/:/,$tail);
1.397     raeburn  4525:     my $now = time;
1.419     raeburn  4526:     my ($cloneruname,$clonerudom,%cc_clone);
1.234     foxr     4527:     if (defined($description)) {
                   4528: 	$description=&unescape($description);
                   4529:     } else {
                   4530: 	$description='.';
                   4531:     }
1.266     raeburn  4532:     if (defined($instcodefilter)) {
                   4533:         $instcodefilter=&unescape($instcodefilter);
                   4534:     } else {
                   4535:         $instcodefilter='.';
                   4536:     }
1.336     raeburn  4537:     my ($ownerunamefilter,$ownerdomfilter);
1.266     raeburn  4538:     if (defined($ownerfilter)) {
                   4539:         $ownerfilter=&unescape($ownerfilter);
1.336     raeburn  4540:         if ($ownerfilter ne '.' && defined($ownerfilter)) {
                   4541:             if ($ownerfilter =~ /^([^:]*):([^:]*)$/) {
                   4542:                  $ownerunamefilter = $1;
                   4543:                  $ownerdomfilter = $2;
                   4544:             } else {
                   4545:                 $ownerunamefilter = $ownerfilter;
                   4546:                 $ownerdomfilter = '';
                   4547:             }
                   4548:         }
1.266     raeburn  4549:     } else {
                   4550:         $ownerfilter='.';
                   4551:     }
1.336     raeburn  4552: 
1.282     raeburn  4553:     if (defined($coursefilter)) {
                   4554:         $coursefilter=&unescape($coursefilter);
                   4555:     } else {
                   4556:         $coursefilter='.';
                   4557:     }
1.333     raeburn  4558:     if (defined($typefilter)) {
                   4559:         $typefilter=&unescape($typefilter);
                   4560:     } else {
                   4561:         $typefilter='.';
                   4562:     }
1.344     raeburn  4563:     if (defined($regexp_ok)) {
                   4564:         $regexp_ok=&unescape($regexp_ok);
                   4565:     }
1.401     raeburn  4566:     if (defined($catfilter)) {
                   4567:         $catfilter=&unescape($catfilter);
                   4568:     }
1.419     raeburn  4569:     if (defined($cloner)) {
                   4570:         $cloner = &unescape($cloner);
                   4571:         ($cloneruname,$clonerudom) = ($cloner =~ /^($LONCAPA::match_username):($LONCAPA::match_domain)$/); 
                   4572:     }
                   4573:     if (defined($cc_clone_list)) {
                   4574:         $cc_clone_list = &unescape($cc_clone_list);
                   4575:         my @cc_cloners = split('&',$cc_clone_list);
                   4576:         foreach my $cid (@cc_cloners) {
                   4577:             my ($clonedom,$clonenum) = split(':',$cid);
                   4578:             next if ($clonedom ne $udom); 
                   4579:             $cc_clone{$clonedom.'_'.$clonenum} = 1;
                   4580:         } 
                   4581:     }
1.431     raeburn  4582:     if ($createdbefore ne '') {
1.427     raeburn  4583:         $createdbefore = &unescape($createdbefore);
                   4584:     } else {
                   4585:        $createdbefore = 0;
                   4586:     }
1.431     raeburn  4587:     if ($createdafter ne '') {
1.427     raeburn  4588:         $createdafter = &unescape($createdafter);
                   4589:     } else {
                   4590:         $createdafter = 0;
                   4591:     }
1.431     raeburn  4592:     if ($creationcontext ne '') {
1.427     raeburn  4593:         $creationcontext = &unescape($creationcontext);
                   4594:     } else {
                   4595:         $creationcontext = '.';
                   4596:     }
1.505     raeburn  4597:     unless ($hasuniquecode) {
                   4598:         $hasuniquecode = '.';
                   4599:     }
1.384     raeburn  4600:     my $unpack = 1;
1.485     raeburn  4601:     if ($description eq '.' && $instcodefilter eq '.' && $ownerfilter eq '.' && 
1.384     raeburn  4602:         $typefilter eq '.') {
                   4603:         $unpack = 0;
                   4604:     }
                   4605:     if (!defined($since)) { $since=0; }
1.234     foxr     4606:     my $qresult='';
                   4607:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   4608:     if ($hashref) {
1.384     raeburn  4609: 	while (my ($key,$value) = each(%$hashref)) {
1.397     raeburn  4610:             my ($unesc_key,$lasttime_key,$lasttime,$is_hash,%val,
1.427     raeburn  4611:                 %unesc_val,$selfenroll_end,$selfenroll_types,$created,
                   4612:                 $context);
1.384     raeburn  4613:             $unesc_key = &unescape($key);
                   4614:             if ($unesc_key =~ /^lasttime:/) {
                   4615:                 next;
                   4616:             } else {
                   4617:                 $lasttime_key = &escape('lasttime:'.$unesc_key);
                   4618:             }
                   4619:             if ($hashref->{$lasttime_key} ne '') {
                   4620:                 $lasttime = $hashref->{$lasttime_key};
                   4621:                 next if ($lasttime<$since);
                   4622:             }
1.419     raeburn  4623:             my ($canclone,$valchange);
1.384     raeburn  4624:             my $items = &Apache::lonnet::thaw_unescape($value);
                   4625:             if (ref($items) eq 'HASH') {
1.429     raeburn  4626:                 if ($hashref->{$lasttime_key} eq '') {
1.430     raeburn  4627:                     next if ($since > 1);
1.429     raeburn  4628:                 }
1.384     raeburn  4629:                 $is_hash =  1;
1.445     raeburn  4630:                 if ($domcloner) {
                   4631:                     $canclone = 1;
                   4632:                 } elsif (defined($clonerudom)) {
1.419     raeburn  4633:                     if ($items->{'cloners'}) {
                   4634:                         my @cloneable = split(',',$items->{'cloners'});
                   4635:                         if (@cloneable) {
                   4636:                             if (grep(/^\*$/,@cloneable))  {
                   4637:                                 $canclone = 1;
                   4638:                             } elsif (grep(/^\*:\Q$clonerudom\E$/,@cloneable)) {
                   4639:                                 $canclone = 1;
                   4640:                             } elsif (grep(/^\Q$cloneruname\E:\Q$clonerudom\E$/,@cloneable)) {
                   4641:                                 $canclone = 1;
                   4642:                             }
                   4643:                         }
                   4644:                         unless ($canclone) {
                   4645:                             if ($cloneruname ne '' && $clonerudom ne '') {
                   4646:                                 if ($cc_clone{$unesc_key}) {
                   4647:                                     $canclone = 1;
                   4648:                                     $items->{'cloners'} .= ','.$cloneruname.':'.
                   4649:                                                            $clonerudom;
                   4650:                                     $valchange = 1;
                   4651:                                 }
                   4652:                             }
                   4653:                         }
                   4654:                     } elsif (defined($cloneruname)) {
                   4655:                         if ($cc_clone{$unesc_key}) {
                   4656:                             $canclone = 1;
                   4657:                             $items->{'cloners'} = $cloneruname.':'.$clonerudom;
                   4658:                             $valchange = 1;
                   4659:                         }
1.437     raeburn  4660:                         unless ($canclone) {
                   4661:                             if ($items->{'owner'} =~ /:/) {
                   4662:                                 if ($items->{'owner'} eq $cloner) {
                   4663:                                     $canclone = 1;
                   4664:                                 }
1.444     raeburn  4665:                             } elsif ($cloner eq $items->{'owner'}.':'.$udom) {
1.437     raeburn  4666:                                 $canclone = 1;
                   4667:                             }
                   4668:                             if ($canclone) {
                   4669:                                 $items->{'cloners'} = $cloneruname.':'.$clonerudom;
                   4670:                                 $valchange = 1;
                   4671:                             }
                   4672:                         }
1.419     raeburn  4673:                     }
                   4674:                 }
1.384     raeburn  4675:                 if ($unpack || !$rtn_as_hash) {
                   4676:                     $unesc_val{'descr'} = $items->{'description'};
                   4677:                     $unesc_val{'inst_code'} = $items->{'inst_code'};
                   4678:                     $unesc_val{'owner'} = $items->{'owner'};
                   4679:                     $unesc_val{'type'} = $items->{'type'};
1.419     raeburn  4680:                     $unesc_val{'cloners'} = $items->{'cloners'};
1.427     raeburn  4681:                     $unesc_val{'created'} = $items->{'created'};
                   4682:                     $unesc_val{'context'} = $items->{'context'};
1.404     raeburn  4683:                 }
                   4684:                 $selfenroll_types = $items->{'selfenroll_types'};
                   4685:                 $selfenroll_end = $items->{'selfenroll_end_date'};
1.427     raeburn  4686:                 $created = $items->{'created'};
                   4687:                 $context = $items->{'context'};
1.505     raeburn  4688:                 if ($hasuniquecode ne '.') {
                   4689:                     next unless ($items->{'uniquecode'});
                   4690:                 }
1.404     raeburn  4691:                 if ($selfenrollonly) {
                   4692:                     next if (!$selfenroll_types);
                   4693:                     if (($selfenroll_end > 0) && ($selfenroll_end <= $now)) {
                   4694:                         next;
1.397     raeburn  4695:                     }
1.404     raeburn  4696:                 }
1.427     raeburn  4697:                 if ($creationcontext ne '.') {
                   4698:                     next if (($context ne '') && ($context ne $creationcontext));  
                   4699:                 }
                   4700:                 if ($createdbefore > 0) {
                   4701:                     next if (($created eq '') || ($created > $createdbefore));   
                   4702:                 }
                   4703:                 if ($createdafter > 0) {
                   4704:                     next if (($created eq '') || ($created <= $createdafter)); 
                   4705:                 }
1.404     raeburn  4706:                 if ($catfilter ne '') {
1.406     raeburn  4707:                     next if ($items->{'categories'} eq '');
                   4708:                     my @categories = split('&',$items->{'categories'}); 
1.407     raeburn  4709:                     next if (@categories == 0);
                   4710:                     my @subcats = split('&',$catfilter);
                   4711:                     my $matchcat = 0;
                   4712:                     foreach my $cat (@categories) {
                   4713:                         if (grep(/^\Q$cat\E$/,@subcats)) {
                   4714:                             $matchcat = 1;
                   4715:                             last;
                   4716:                         }
                   4717:                     }
                   4718:                     next if (!$matchcat);
1.404     raeburn  4719:                 }
                   4720:                 if ($caller eq 'coursecatalog') {
1.405     raeburn  4721:                     if ($items->{'hidefromcat'} eq 'yes') {
                   4722:                         next if !$showhidden;
1.401     raeburn  4723:                     }
1.384     raeburn  4724:                 }
1.383     raeburn  4725:             } else {
1.401     raeburn  4726:                 next if ($catfilter ne '');
1.419     raeburn  4727:                 next if ($selfenrollonly);
1.427     raeburn  4728:                 next if ($createdbefore || $createdafter);
                   4729:                 next if ($creationcontext ne '.');
1.419     raeburn  4730:                 if ((defined($clonerudom)) && (defined($cloneruname)))  {
                   4731:                     if ($cc_clone{$unesc_key}) {
                   4732:                         $canclone = 1;
                   4733:                         $val{'cloners'} = &escape($cloneruname.':'.$clonerudom);
                   4734:                     }
                   4735:                 }
1.384     raeburn  4736:                 $is_hash =  0;
1.388     raeburn  4737:                 my @courseitems = split(/:/,$value);
1.403     raeburn  4738:                 $lasttime = pop(@courseitems);
1.402     raeburn  4739:                 if ($hashref->{$lasttime_key} eq '') {
                   4740:                     next if ($lasttime<$since);
                   4741:                 }
1.384     raeburn  4742: 	        ($val{'descr'},$val{'inst_code'},$val{'owner'},$val{'type'}) = @courseitems;
1.383     raeburn  4743:             }
1.419     raeburn  4744:             if ($cloneonly) {
                   4745:                next unless ($canclone);
                   4746:             }
1.266     raeburn  4747:             my $match = 1;
1.384     raeburn  4748: 	    if ($description ne '.') {
                   4749:                 if (!$is_hash) {
                   4750:                     $unesc_val{'descr'} = &unescape($val{'descr'});
                   4751:                 }
                   4752:                 if (eval{$unesc_val{'descr'} !~ /\Q$description\E/i}) {
1.266     raeburn  4753:                     $match = 0;
1.384     raeburn  4754:                 }
1.266     raeburn  4755:             }
1.384     raeburn  4756:             if ($instcodefilter ne '.') {
                   4757:                 if (!$is_hash) {
                   4758:                     $unesc_val{'inst_code'} = &unescape($val{'inst_code'});
                   4759:                 }
1.418     raeburn  4760:                 if ($regexp_ok == 1) {
1.384     raeburn  4761:                     if (eval{$unesc_val{'inst_code'} !~ /$instcodefilter/}) {
1.344     raeburn  4762:                         $match = 0;
                   4763:                     }
1.418     raeburn  4764:                 } elsif ($regexp_ok == -1) {
                   4765:                     if (eval{$unesc_val{'inst_code'} =~ /$instcodefilter/}) {
                   4766:                         $match = 0;
                   4767:                     }
1.344     raeburn  4768:                 } else {
1.384     raeburn  4769:                     if (eval{$unesc_val{'inst_code'} !~ /\Q$instcodefilter\E/i}) {
1.344     raeburn  4770:                         $match = 0;
                   4771:                     }
1.266     raeburn  4772:                 }
1.234     foxr     4773: 	    }
1.384     raeburn  4774:             if ($ownerfilter ne '.') {
                   4775:                 if (!$is_hash) {
                   4776:                     $unesc_val{'owner'} = &unescape($val{'owner'});
                   4777:                 }
1.336     raeburn  4778:                 if (($ownerunamefilter ne '') && ($ownerdomfilter ne '')) {
1.384     raeburn  4779:                     if ($unesc_val{'owner'} =~ /:/) {
                   4780:                         if (eval{$unesc_val{'owner'} !~ 
                   4781:                              /\Q$ownerunamefilter\E:\Q$ownerdomfilter\E$/i}) {
1.336     raeburn  4782:                             $match = 0;
                   4783:                         } 
                   4784:                     } else {
1.384     raeburn  4785:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336     raeburn  4786:                             $match = 0;
                   4787:                         }
                   4788:                     }
                   4789:                 } elsif ($ownerunamefilter ne '') {
1.384     raeburn  4790:                     if ($unesc_val{'owner'} =~ /:/) {
                   4791:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E:[^:]+$/i}) {
1.336     raeburn  4792:                              $match = 0;
                   4793:                         }
                   4794:                     } else {
1.384     raeburn  4795:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336     raeburn  4796:                             $match = 0;
                   4797:                         }
                   4798:                     }
                   4799:                 } elsif ($ownerdomfilter ne '') {
1.384     raeburn  4800:                     if ($unesc_val{'owner'} =~ /:/) {
                   4801:                         if (eval{$unesc_val{'owner'} !~ /^[^:]+:\Q$ownerdomfilter\E/}) {
1.336     raeburn  4802:                              $match = 0;
                   4803:                         }
                   4804:                     } else {
                   4805:                         if ($ownerdomfilter ne $udom) {
                   4806:                             $match = 0;
                   4807:                         }
                   4808:                     }
1.266     raeburn  4809:                 }
                   4810:             }
1.384     raeburn  4811:             if ($coursefilter ne '.') {
                   4812:                 if (eval{$unesc_key !~ /^$udom(_)\Q$coursefilter\E$/}) {
1.282     raeburn  4813:                     $match = 0;
                   4814:                 }
                   4815:             }
1.384     raeburn  4816:             if ($typefilter ne '.') {
                   4817:                 if (!$is_hash) {
                   4818:                     $unesc_val{'type'} = &unescape($val{'type'});
                   4819:                 }
                   4820:                 if ($unesc_val{'type'} eq '') {
1.333     raeburn  4821:                     if ($typefilter ne 'Course') {
                   4822:                         $match = 0;
                   4823:                     }
1.383     raeburn  4824:                 } else {
1.384     raeburn  4825:                     if (eval{$unesc_val{'type'} !~ /^\Q$typefilter\E$/}) {
1.333     raeburn  4826:                         $match = 0;
                   4827:                     }
                   4828:                 }
                   4829:             }
1.266     raeburn  4830:             if ($match == 1) {
1.384     raeburn  4831:                 if ($rtn_as_hash) {
                   4832:                     if ($is_hash) {
1.419     raeburn  4833:                         if ($valchange) {
                   4834:                             my $newvalue = &Apache::lonnet::freeze_escape($items);
                   4835:                             $qresult.=$key.'='.$newvalue.'&';
                   4836:                         } else {
                   4837:                             $qresult.=$key.'='.$value.'&';
                   4838:                         }
1.384     raeburn  4839:                     } else {
1.388     raeburn  4840:                         my %rtnhash = ( 'description' => &unescape($val{'descr'}),
                   4841:                                         'inst_code' => &unescape($val{'inst_code'}),
                   4842:                                         'owner'     => &unescape($val{'owner'}),
                   4843:                                         'type'      => &unescape($val{'type'}),
1.419     raeburn  4844:                                         'cloners'   => &unescape($val{'cloners'}),
1.384     raeburn  4845:                                       );
                   4846:                         my $items = &Apache::lonnet::freeze_escape(\%rtnhash);
                   4847:                         $qresult.=$key.'='.$items.'&';
                   4848:                     }
1.383     raeburn  4849:                 } else {
1.384     raeburn  4850:                     if ($is_hash) {
                   4851:                         $qresult .= $key.'='.&escape($unesc_val{'descr'}).':'.
                   4852:                                     &escape($unesc_val{'inst_code'}).':'.
                   4853:                                     &escape($unesc_val{'owner'}).'&';
                   4854:                     } else {
                   4855:                         $qresult .= $key.'='.$val{'descr'}.':'.$val{'inst_code'}.
                   4856:                                     ':'.$val{'owner'}.'&';
                   4857:                     }
1.383     raeburn  4858:                 }
1.266     raeburn  4859:             }
1.234     foxr     4860: 	}
1.311     albertel 4861: 	if (&untie_domain_hash($hashref)) {
1.234     foxr     4862: 	    chop($qresult);
1.387     albertel 4863: 	    &Reply($client, \$qresult, $userinput);
1.234     foxr     4864: 	} else {
                   4865: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4866: 		    "while attempting courseiddump\n", $userinput);
                   4867: 	}
                   4868:     } else {
                   4869: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4870: 		"while attempting courseiddump\n", $userinput);
                   4871:     }
                   4872:     return 1;
                   4873: }
                   4874: &register_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
1.238     foxr     4875: 
1.438     raeburn  4876: sub course_lastaccess_handler {
                   4877:     my ($cmd, $tail, $client) = @_;
                   4878:     my $userinput = "$cmd:$tail";
                   4879:     my ($cdom,$cnum) = split(':',$tail); 
                   4880:     my (%lastaccess,$qresult);
                   4881:     my $hashref = &tie_domain_hash($cdom, "nohist_courseids", &GDBM_WRCREAT());
                   4882:     if ($hashref) {
                   4883:         while (my ($key,$value) = each(%$hashref)) {
                   4884:             my ($unesc_key,$lasttime);
                   4885:             $unesc_key = &unescape($key);
                   4886:             if ($cnum) {
                   4887:                 next unless ($unesc_key =~ /\Q$cdom\E_\Q$cnum\E$/);
                   4888:             }
                   4889:             if ($unesc_key =~ /^lasttime:($LONCAPA::match_domain\_$LONCAPA::match_courseid)/) {
                   4890:                 $lastaccess{$1} = $value;
                   4891:             } else {
                   4892:                 my $items = &Apache::lonnet::thaw_unescape($value);
                   4893:                 if (ref($items) eq 'HASH') {
                   4894:                     unless ($lastaccess{$unesc_key}) {
                   4895:                         $lastaccess{$unesc_key} = '';
                   4896:                     }
                   4897:                 } else {
                   4898:                     my @courseitems = split(':',$value);
                   4899:                     $lastaccess{$unesc_key} = pop(@courseitems);
                   4900:                 }
                   4901:             }
                   4902:         }
                   4903:         foreach my $cid (sort(keys(%lastaccess))) {
                   4904:             $qresult.=&escape($cid).'='.$lastaccess{$cid}.'&'; 
                   4905:         }
                   4906:         if (&untie_domain_hash($hashref)) {
                   4907:             if ($qresult) {
                   4908:                 chop($qresult);
                   4909:             }
                   4910:             &Reply($client, \$qresult, $userinput);
                   4911:         } else {
                   4912:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4913:                     "while attempting lastacourseaccess\n", $userinput);
                   4914:         }
                   4915:     } else {
                   4916:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4917:                 "while attempting lastcourseaccess\n", $userinput);
                   4918:     }
                   4919:     return 1;
                   4920: }
                   4921: &register_handler("courselastaccess",\&course_lastaccess_handler, 0, 1, 0);
                   4922: 
1.561     raeburn  4923: sub course_sessions_handler {
                   4924:     my ($cmd, $tail, $client) = @_;
                   4925:     my $userinput = "$cmd:$tail";
                   4926:     my ($cdom,$cnum,$lastactivity) = split(':',$tail);
                   4927:     my $dbsuffix = '_'.$cdom.'_'.$cnum.'.db';
                   4928:     my (%sessions,$qresult);
                   4929:     my $now=time;
                   4930:     if (opendir(DIR,$perlvar{'lonIDsDir'})) {
                   4931:         my $filename;
                   4932:         while ($filename=readdir(DIR)) {
                   4933:             next if ($filename=~/^\./);
                   4934:             next if ($filename=~/^publicuser_/);
                   4935:             next if ($filename=~/^[a-f0-9]+_(linked|lti_\d+)\.id$/);
1.562     raeburn  4936:             if ($filename =~ /^($LONCAPA::match_username)_\d+_($LONCAPA::match_domain)_/) {
1.561     raeburn  4937:                 my ($uname,$udom) = ($1,$2);
1.562     raeburn  4938:                 next unless (-e "$perlvar{'lonDaemons'}/tmp/$uname$dbsuffix");
1.561     raeburn  4939:                 my $mtime = (stat("$perlvar{'lonIDsDir'}/$filename"))[9];
                   4940:                 if ($lastactivity < 0) {
1.563     raeburn  4941:                     next if ($mtime-$now > $lastactivity);
1.561     raeburn  4942:                 } else {
1.563     raeburn  4943:                     next if ($now-$mtime > $lastactivity);
1.561     raeburn  4944:                 }
                   4945:                 $sessions{$uname.':'.$udom} = $mtime;
                   4946:             }
                   4947:         }
                   4948:         closedir(DIR); 
                   4949:     }
                   4950:     foreach my $user (keys(%sessions)) {
                   4951:         $qresult.=&escape($user).'='.$sessions{$user}.'&';
                   4952:     }
                   4953:     if ($qresult) {
                   4954:         chop($qresult);
                   4955:     }
                   4956:     &Reply($client, \$qresult, $userinput);
                   4957:     return 1;
                   4958: }
                   4959: &register_handler("coursesessions",\&course_sessions_handler, 0, 1, 0);
                   4960: 
1.238     foxr     4961: #
1.348     raeburn  4962: # Puts an unencrypted entry in a namespace db file at the domain level 
                   4963: #
                   4964: # Parameters:
                   4965: #    $cmd      - The command that got us here.
                   4966: #    $tail     - Tail of the command (remaining parameters).
                   4967: #    $client   - File descriptor connected to client.
                   4968: # Returns
                   4969: #     0        - Requested to exit, caller should shut down.
                   4970: #     1        - Continue processing.
                   4971: #  Side effects:
                   4972: #     reply is written to $client.
                   4973: #
                   4974: sub put_domain_handler {
                   4975:     my ($cmd,$tail,$client) = @_;
                   4976: 
                   4977:     my $userinput = "$cmd:$tail";
                   4978: 
                   4979:     my ($udom,$namespace,$what) =split(/:/,$tail,3);
                   4980:     chomp($what);
                   4981:     my @pairs=split(/\&/,$what);
                   4982:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_WRCREAT(),
                   4983:                                    "P", $what);
                   4984:     if ($hashref) {
                   4985:         foreach my $pair (@pairs) {
                   4986:             my ($key,$value)=split(/=/,$pair);
                   4987:             $hashref->{$key}=$value;
                   4988:         }
                   4989:         if (&untie_domain_hash($hashref)) {
                   4990:             &Reply($client, "ok\n", $userinput);
                   4991:         } else {
                   4992:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4993:                      "while attempting putdom\n", $userinput);
                   4994:         }
                   4995:     } else {
                   4996:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4997:                   "while attempting putdom\n", $userinput);
                   4998:     }
                   4999: 
                   5000:     return 1;
                   5001: }
                   5002: &register_handler("putdom", \&put_domain_handler, 0, 1, 0);
                   5003: 
1.517     raeburn  5004: # Updates one or more entries in clickers.db file at the domain level
                   5005: #
                   5006: # Parameters:
                   5007: #    $cmd      - The command that got us here.
                   5008: #    $tail     - Tail of the command (remaining parameters).
                   5009: #                In this case a colon separated list containing:
                   5010: #                (a) the domain for which we are updating the entries,
                   5011: #                (b) the action required -- add or del -- and
                   5012: #                (c) a &-separated list of entries to add or delete.
                   5013: #    $client   - File descriptor connected to client.
                   5014: # Returns
                   5015: #     1        - Continue processing.
                   5016: #     0        - Requested to exit, caller should shut down.
                   5017: #  Side effects:
                   5018: #     reply is written to $client.
                   5019: #
                   5020: 
                   5021: 
                   5022: sub update_clickers {
                   5023:     my ($cmd, $tail, $client)  = @_;
                   5024: 
                   5025:     my $userinput = "$cmd:$tail";
                   5026:     my ($udom,$action,$what) =split(/:/,$tail,3);
                   5027:     chomp($what);
                   5028: 
                   5029:     my $hashref = &tie_domain_hash($udom, "clickers", &GDBM_WRCREAT(),
                   5030:                                  "U","$action:$what");
                   5031: 
                   5032:     if (!$hashref) {
                   5033:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5034:                   "while attempting updateclickers\n", $userinput);
                   5035:         return 1;
                   5036:     }
                   5037: 
                   5038:     my @pairs=split(/\&/,$what);
                   5039:     foreach my $pair (@pairs) {
                   5040:         my ($key,$value)=split(/=/,$pair);
                   5041:         if ($action eq 'add') {
                   5042:             if (exists($hashref->{$key})) {
                   5043:                 my @newvals = split(/,/,&unescape($value));
                   5044:                 my @currvals = split(/,/,&unescape($hashref->{$key}));
                   5045:                 my @merged = sort(keys(%{{map { $_ => 1 } (@newvals,@currvals)}}));
                   5046:                 $hashref->{$key}=&escape(join(',',@merged));
                   5047:             } else {
                   5048:                 $hashref->{$key}=$value;
                   5049:             }
                   5050:         } elsif ($action eq 'del') {
                   5051:             if (exists($hashref->{$key})) {
                   5052:                 my %current;
                   5053:                 map { $current{$_} = 1; } split(/,/,&unescape($hashref->{$key}));
                   5054:                 map { delete($current{$_}); } split(/,/,&unescape($value));
                   5055:                 if (keys(%current)) {
                   5056:                     $hashref->{$key}=&escape(join(',',sort(keys(%current))));
                   5057:                 } else {
                   5058:                     delete($hashref->{$key});
                   5059:                 }
                   5060:             }
                   5061:         }
                   5062:     }
                   5063:     if (&untie_user_hash($hashref)) {
                   5064:         &Reply( $client, "ok\n", $userinput);
                   5065:     } else {
                   5066:         &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   5067:                  "while attempting put\n",
                   5068:                  $userinput);
                   5069:     }
                   5070:     return 1;
                   5071: }
                   5072: &register_handler("updateclickers", \&update_clickers, 0, 1, 0);
                   5073: 
                   5074: 
                   5075: # Deletes one or more entries in a namespace db file at the domain level
                   5076: #
                   5077: # Parameters:
                   5078: #    $cmd      - The command that got us here.
                   5079: #    $tail     - Tail of the command (remaining parameters).
                   5080: #                In this case a colon separated list containing:
                   5081: #                (a) the domain for which we are deleting the entries,
                   5082: #                (b) &-separated list of keys to delete.  
                   5083: #    $client   - File descriptor connected to client.
                   5084: # Returns
                   5085: #     1        - Continue processing.
                   5086: #     0        - Requested to exit, caller should shut down.
                   5087: #  Side effects:
                   5088: #     reply is written to $client.
                   5089: #
                   5090: 
                   5091: sub del_domain_handler {
                   5092:     my ($cmd,$tail,$client) = @_;
                   5093: 
                   5094:     my $userinput = "$cmd:$tail";
                   5095: 
                   5096:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   5097:     chomp($what);
                   5098:     my $hashref = &tie_domain_hash($udom,$namespace,&GDBM_WRCREAT(),
                   5099:                                    "D", $what);
                   5100:     if ($hashref) {
                   5101:         my @keys=split(/\&/,$what);
                   5102:         foreach my $key (@keys) {
                   5103:             delete($hashref->{$key});
                   5104:         }
                   5105:         if (&untie_user_hash($hashref)) {
                   5106:             &Reply($client, "ok\n", $userinput);
                   5107:         } else {
                   5108:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5109:                     "while attempting deldom\n", $userinput);
                   5110:         }
                   5111:     } else {
                   5112:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5113:                  "while attempting deldom\n", $userinput);
                   5114:     }
                   5115:     return 1;
                   5116: }
                   5117: &register_handler("deldom", \&del_domain_handler, 0, 1, 0);
                   5118: 
                   5119: 
1.348     raeburn  5120: # Unencrypted get from the namespace database file at the domain level.
                   5121: # This function retrieves a keyed item from a specific named database in the
                   5122: # domain directory.
                   5123: #
                   5124: # Parameters:
1.565     raeburn  5125: #   $cmd             - Command request keyword (getdom).
1.348     raeburn  5126: #   $tail            - Tail of the command.  This is a colon separated list
                   5127: #                      consisting of the domain and the 'namespace' 
                   5128: #                      which selects the gdbm file to do the lookup in,
                   5129: #                      & separated list of keys to lookup.  Note that
                   5130: #                      the values are returned as an & separated list too.
                   5131: #   $client          - File descriptor open on the client.
                   5132: # Returns:
                   5133: #   1       - Continue processing.
                   5134: #   0       - Exit.
                   5135: #  Side effects:
                   5136: #     reply is written to $client.
                   5137: #
                   5138: 
                   5139: sub get_domain_handler {
                   5140:     my ($cmd, $tail, $client) = @_;
                   5141: 
1.536     raeburn  5142:     my $userinput = "$cmd:$tail";
                   5143: 
                   5144:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   5145:     if ($namespace =~ /^enc/) {
                   5146:         &Failure( $client, "refused\n", $userinput);
                   5147:     } else {
1.565     raeburn  5148:         my $res = LONCAPA::Lond::get_dom($userinput);
                   5149:         if ($res =~ /^error:/) {
                   5150:             &Failure($client, \$res, $userinput);
1.536     raeburn  5151:         } else {
1.565     raeburn  5152:             &Reply($client, \$res, $userinput);
1.536     raeburn  5153:         }
                   5154:     }
                   5155: 
                   5156:     return 1;
                   5157: }
                   5158: &register_handler("getdom", \&get_domain_handler, 0, 1, 0);
                   5159: 
1.572   ! raeburn  5160: #
        !          5161: # Encrypted get from the namespace database file at the domain level.
        !          5162: # This function retrieves a keyed item from a specific named database in the
        !          5163: # domain directory.
        !          5164: #
        !          5165: # Parameters:
        !          5166: #   $cmd             - Command request keyword (egetdom).
        !          5167: #   $tail            - Tail of the command.  This is a colon separated list
        !          5168: #                      consisting of the domain and the 'namespace'
        !          5169: #                      which selects the gdbm file to do the lookup in,
        !          5170: #                      & separated list of keys to lookup.  Note that
        !          5171: #                      the values are returned as an & separated list too.
        !          5172: #   $client          - File descriptor open on the client.
        !          5173: # Returns:
        !          5174: #   1       - Continue processing.
        !          5175: #   0       - Exit.
        !          5176: #  Side effects:
        !          5177: #     reply is encrypted before being written to $client.
        !          5178: #
1.536     raeburn  5179: sub encrypted_get_domain_handler {
                   5180:     my ($cmd, $tail, $client) = @_;
                   5181: 
                   5182:     my $userinput = "$cmd:$tail";
1.348     raeburn  5183: 
1.565     raeburn  5184:     my $res = LONCAPA::Lond::get_dom($userinput);
                   5185:     if ($res =~ /^error:/) {
                   5186:         &Failure($client, \$res, $userinput);
                   5187:     } else {
                   5188:         if ($cipher) {
                   5189:             my $cmdlength=length($res);
                   5190:             $res.="         ";
                   5191:             my $encres='';
                   5192:             for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   5193:                 $encres.= unpack("H16",
                   5194:                                  $cipher->encrypt(substr($res,
                   5195:                                                          $encidx,
                   5196:                                                          8)));
1.536     raeburn  5197:             }
1.565     raeburn  5198:             &Reply( $client,"enc:$cmdlength:$encres\n",$userinput);
1.348     raeburn  5199:         } else {
1.565     raeburn  5200:             &Failure( $client, "error:no_key\n",$userinput);
1.348     raeburn  5201:         }
                   5202:     }
                   5203:     return 1;
                   5204: }
1.536     raeburn  5205: &register_handler("egetdom", \&encrypted_get_domain_handler, 1, 1, 0);
1.348     raeburn  5206: 
1.420     raeburn  5207: #
1.572   ! raeburn  5208: # Encrypted get from the namespace database file at the domain level.
        !          5209: # This function retrieves a keyed item from a specific named database in the
        !          5210: # domain directory.
        !          5211: #
        !          5212: # Parameters:
        !          5213: #   $cmd             - Command request keyword (lti).
        !          5214: #   $tail            - Tail of the command.  This is a colon-separated list
        !          5215: #                      consisting of the domain, coursenum, if for LTI-
        !          5216: #                      enabled deep-linking to course content using
        !          5217: #                      link protection configured within a course,
        !          5218: #                      context (=deeplink) if for LTI-enabled deep-linking
        !          5219: #                      to course content using LTI Provider settings
        !          5220: #                      configured within a course's domain, the (escaped)
        !          5221: #                      launch URL, the (escaped) method (typically POST),
        !          5222: #                      and a frozen hash of the LTI launch parameters
        !          5223: #                      from the LTI payload.
        !          5224: #   $client          - File descriptor open on the client.
        !          5225: # Returns:
        !          5226: #   1       - Continue processing.
        !          5227: #   0       - Exit.
        !          5228: #  Side effects:
        !          5229: #     The reply will contain an LTI itemID, if the signed LTI payload
        !          5230: #     could be verified using the consumer key and the shared secret 
        !          5231: #     available for that key (for the itemID) for either the course or domain, 
        !          5232: #     depending on values for cnum and context. The reply is encrypted before 
        !          5233: #     being written to $client.
        !          5234: #
        !          5235: sub lti_handler {
        !          5236:     my ($cmd, $tail, $client) = @_;
        !          5237: 
        !          5238:     my $userinput = "$cmd:$tail";
        !          5239: 
        !          5240:     my ($cdom,$cnum,$context,$escurl,$escmethod,$items) = split(/:/,$tail);
        !          5241:     my $url = &unescape($escurl);
        !          5242:     my $method = &unescape($escmethod);
        !          5243:     my $params = &Apache::lonnet::thaw_unescape($items);
        !          5244:     my $res;
        !          5245:     if ($cnum ne '') {
        !          5246:         $res = &LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
        !          5247:     } else {
        !          5248:         $res = &LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
        !          5249:     }
        !          5250:     if ($res =~ /^error:/) {
        !          5251:         &Failure($client, \$res, $userinput);
        !          5252:     } else {
        !          5253:         if ($cipher) {
        !          5254:             my $cmdlength=length($res);
        !          5255:             $res.="         ";
        !          5256:             my $encres='';
        !          5257:             for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
        !          5258:                 $encres.= unpack("H16",
        !          5259:                                  $cipher->encrypt(substr($res,
        !          5260:                                                          $encidx,
        !          5261:                                                          8)));
        !          5262:             }
        !          5263:             &Reply( $client,"enc:$cmdlength:$encres\n",$userinput);
        !          5264:         } else {
        !          5265:             &Failure( $client, "error:no_key\n",$userinput);
        !          5266:         }
        !          5267:     }
        !          5268:     return 1;
        !          5269: }
        !          5270: &register_handler("lti", \&lti_handler, 1, 1, 0);
        !          5271: 
        !          5272: #
1.238     foxr     5273: #  Puts an id to a domains id database. 
                   5274: #
                   5275: #  Parameters:
                   5276: #   $cmd     - The command that triggered us.
                   5277: #   $tail    - Remainder of the request other than the command. This is a 
                   5278: #              colon separated list containing:
                   5279: #              $domain  - The domain for which we are writing the id.
                   5280: #              $pairs  - The id info to write... this is and & separated list
                   5281: #                        of keyword=value.
                   5282: #   $client  - Socket open on the client.
                   5283: #  Returns:
                   5284: #    1   - Continue processing.
                   5285: #  Side effects:
                   5286: #     reply is written to $client.
                   5287: #
                   5288: sub put_id_handler {
                   5289:     my ($cmd,$tail,$client) = @_;
                   5290: 
                   5291: 
                   5292:     my $userinput = "$cmd:$tail";
                   5293: 
                   5294:     my ($udom,$what)=split(/:/,$tail);
                   5295:     chomp($what);
                   5296:     my @pairs=split(/\&/,$what);
                   5297:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   5298: 				   "P", $what);
                   5299:     if ($hashref) {
                   5300: 	foreach my $pair (@pairs) {
                   5301: 	    my ($key,$value)=split(/=/,$pair);
                   5302: 	    $hashref->{$key}=$value;
                   5303: 	}
1.311     albertel 5304: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     5305: 	    &Reply($client, "ok\n", $userinput);
                   5306: 	} else {
                   5307: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5308: 		     "while attempting idput\n", $userinput);
                   5309: 	}
                   5310:     } else {
                   5311: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5312: 		  "while attempting idput\n", $userinput);
                   5313:     }
                   5314: 
                   5315:     return 1;
                   5316: }
1.263     albertel 5317: &register_handler("idput", \&put_id_handler, 0, 1, 0);
1.238     foxr     5318: 
                   5319: #
                   5320: #  Retrieves a set of id values from the id database.
                   5321: #  Returns an & separated list of results, one for each requested id to the
                   5322: #  client.
                   5323: #
                   5324: # Parameters:
                   5325: #   $cmd       - Command keyword that caused us to be dispatched.
                   5326: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5327: #               domain - the domain whose id table we dump
                   5328: #               ids      Consists of an & separated list of
                   5329: #                        id keywords whose values will be fetched.
                   5330: #                        nonexisting keywords will have an empty value.
                   5331: #   $client    - Socket open on the client.
                   5332: #
                   5333: # Returns:
                   5334: #    1 - indicating processing should continue.
                   5335: # Side effects:
                   5336: #   An & separated list of results is written to $client.
                   5337: #
                   5338: sub get_id_handler {
                   5339:     my ($cmd, $tail, $client) = @_;
                   5340: 
                   5341:     
                   5342:     my $userinput = "$client:$tail";
                   5343:     
                   5344:     my ($udom,$what)=split(/:/,$tail);
                   5345:     chomp($what);
                   5346:     my @queries=split(/\&/,$what);
                   5347:     my $qresult='';
                   5348:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
                   5349:     if ($hashref) {
                   5350: 	for (my $i=0;$i<=$#queries;$i++) {
                   5351: 	    $qresult.="$hashref->{$queries[$i]}&";
                   5352: 	}
1.311     albertel 5353: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     5354: 	    $qresult=~s/\&$//;
1.387     albertel 5355: 	    &Reply($client, \$qresult, $userinput);
1.238     foxr     5356: 	} else {
                   5357: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5358: 		      "while attempting idget\n",$userinput);
                   5359: 	}
                   5360:     } else {
                   5361: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5362: 		 "while attempting idget\n",$userinput);
                   5363:     }
                   5364:     
                   5365:     return 1;
                   5366: }
1.263     albertel 5367: &register_handler("idget", \&get_id_handler, 0, 1, 0);
1.238     foxr     5368: 
1.501     raeburn  5369: #   Deletes one or more ids in a domain's id database.
                   5370: #
                   5371: #   Parameters:
                   5372: #       $cmd                  - Command keyword (iddel).
                   5373: #       $tail                 - Command tail.  In this case a colon
                   5374: #                               separated list containing:
                   5375: #                               The domain for which we are deleting the id(s).
                   5376: #                               &-separated list of id(s) to delete.
                   5377: #       $client               - File open on client socket.
                   5378: # Returns:
                   5379: #     1   - Continue processing
                   5380: #     0   - Exit server.
                   5381: #     
                   5382: #
                   5383: 
                   5384: sub del_id_handler {
                   5385:     my ($cmd,$tail,$client) = @_;
                   5386: 
                   5387:     my $userinput = "$cmd:$tail";
                   5388: 
                   5389:     my ($udom,$what)=split(/:/,$tail);
                   5390:     chomp($what);
                   5391:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   5392:                                    "D", $what);
                   5393:     if ($hashref) {
                   5394:         my @keys=split(/\&/,$what);
                   5395:         foreach my $key (@keys) {
                   5396:             delete($hashref->{$key});
                   5397:         }
                   5398:         if (&untie_user_hash($hashref)) {
                   5399:             &Reply($client, "ok\n", $userinput);
                   5400:         } else {
                   5401:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5402:                     "while attempting iddel\n", $userinput);
                   5403:         }
                   5404:     } else {
                   5405:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5406:                  "while attempting iddel\n", $userinput);
                   5407:     }
                   5408:     return 1;
                   5409: }
                   5410: &register_handler("iddel", \&del_id_handler, 0, 1, 0);
                   5411: 
1.238     foxr     5412: #
1.299     raeburn  5413: # Puts broadcast e-mail sent by Domain Coordinator in nohist_dcmail database 
                   5414: #
                   5415: # Parameters
                   5416: #   $cmd       - Command keyword that caused us to be dispatched.
                   5417: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5418: #               domain - the domain whose dcmail we are recording
                   5419: #               email    Consists of key=value pair 
                   5420: #                        where key is unique msgid
                   5421: #                        and value is message (in XML)
                   5422: #   $client    - Socket open on the client.
                   5423: #
                   5424: # Returns:
                   5425: #    1 - indicating processing should continue.
                   5426: # Side effects
                   5427: #     reply is written to $client.
                   5428: #
                   5429: sub put_dcmail_handler {
                   5430:     my ($cmd,$tail,$client) = @_;
                   5431:     my $userinput = "$cmd:$tail";
1.463     foxr     5432: 
                   5433: 
1.299     raeburn  5434:     my ($udom,$what)=split(/:/,$tail);
                   5435:     chomp($what);
                   5436:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   5437:     if ($hashref) {
                   5438:         my ($key,$value)=split(/=/,$what);
                   5439:         $hashref->{$key}=$value;
                   5440:     }
1.311     albertel 5441:     if (&untie_domain_hash($hashref)) {
1.299     raeburn  5442:         &Reply($client, "ok\n", $userinput);
                   5443:     } else {
                   5444:         &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5445:                  "while attempting dcmailput\n", $userinput);
                   5446:     }
                   5447:     return 1;
                   5448: }
                   5449: &register_handler("dcmailput", \&put_dcmail_handler, 0, 1, 0);
                   5450: 
                   5451: #
                   5452: # Retrieves broadcast e-mail from nohist_dcmail database
                   5453: # Returns to client an & separated list of key=value pairs,
                   5454: # where key is msgid and value is message information.
                   5455: #
                   5456: # Parameters
                   5457: #   $cmd       - Command keyword that caused us to be dispatched.
                   5458: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5459: #               domain - the domain whose dcmail table we dump
                   5460: #               startfilter - beginning of time window 
                   5461: #               endfilter - end of time window
                   5462: #               sendersfilter - & separated list of username:domain 
                   5463: #                 for senders to search for.
                   5464: #   $client    - Socket open on the client.
                   5465: #
                   5466: # Returns:
                   5467: #    1 - indicating processing should continue.
                   5468: # Side effects
                   5469: #     reply (& separated list of msgid=messageinfo pairs) is 
                   5470: #     written to $client.
                   5471: #
                   5472: sub dump_dcmail_handler {
                   5473:     my ($cmd, $tail, $client) = @_;
                   5474:                                                                                 
                   5475:     my $userinput = "$cmd:$tail";
                   5476:     my ($udom,$startfilter,$endfilter,$sendersfilter) = split(/:/,$tail);
                   5477:     chomp($sendersfilter);
                   5478:     my @senders = ();
                   5479:     if (defined($startfilter)) {
                   5480:         $startfilter=&unescape($startfilter);
                   5481:     } else {
                   5482:         $startfilter='.';
                   5483:     }
                   5484:     if (defined($endfilter)) {
                   5485:         $endfilter=&unescape($endfilter);
                   5486:     } else {
                   5487:         $endfilter='.';
                   5488:     }
                   5489:     if (defined($sendersfilter)) {
                   5490:         $sendersfilter=&unescape($sendersfilter);
1.300     albertel 5491: 	@senders = map { &unescape($_) } split(/\&/,$sendersfilter);
1.299     raeburn  5492:     }
                   5493: 
                   5494:     my $qresult='';
                   5495:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   5496:     if ($hashref) {
                   5497:         while (my ($key,$value) = each(%$hashref)) {
                   5498:             my $match = 1;
1.303     albertel 5499:             my ($timestamp,$subj,$uname,$udom) = 
                   5500: 		split(/:/,&unescape(&unescape($key)),5); # yes, twice really
1.299     raeburn  5501:             $subj = &unescape($subj);
                   5502:             unless ($startfilter eq '.' || !defined($startfilter)) {
                   5503:                 if ($timestamp < $startfilter) {
                   5504:                     $match = 0;
                   5505:                 }
                   5506:             }
                   5507:             unless ($endfilter eq '.' || !defined($endfilter)) {
                   5508:                 if ($timestamp > $endfilter) {
                   5509:                     $match = 0;
                   5510:                 }
                   5511:             }
                   5512:             unless (@senders < 1) {
                   5513:                 unless (grep/^$uname:$udom$/,@senders) {
                   5514:                     $match = 0;
                   5515:                 }
                   5516:             }
                   5517:             if ($match == 1) {
                   5518:                 $qresult.=$key.'='.$value.'&';
                   5519:             }
                   5520:         }
1.311     albertel 5521:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5522:             chop($qresult);
1.387     albertel 5523:             &Reply($client, \$qresult, $userinput);
1.299     raeburn  5524:         } else {
                   5525:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5526:                     "while attempting dcmaildump\n", $userinput);
                   5527:         }
                   5528:     } else {
                   5529:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5530:                 "while attempting dcmaildump\n", $userinput);
                   5531:     }
                   5532:     return 1;
                   5533: }
                   5534: 
                   5535: &register_handler("dcmaildump", \&dump_dcmail_handler, 0, 1, 0);
                   5536: 
                   5537: #
                   5538: # Puts domain roles in nohist_domainroles database
                   5539: #
                   5540: # Parameters
                   5541: #   $cmd       - Command keyword that caused us to be dispatched.
                   5542: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5543: #               domain - the domain whose roles we are recording  
                   5544: #               role -   Consists of key=value pair
                   5545: #                        where key is unique role
                   5546: #                        and value is start/end date information
                   5547: #   $client    - Socket open on the client.
                   5548: #
                   5549: # Returns:
                   5550: #    1 - indicating processing should continue.
                   5551: # Side effects
                   5552: #     reply is written to $client.
                   5553: #
                   5554: 
                   5555: sub put_domainroles_handler {
                   5556:     my ($cmd,$tail,$client) = @_;
                   5557: 
                   5558:     my $userinput = "$cmd:$tail";
                   5559:     my ($udom,$what)=split(/:/,$tail);
                   5560:     chomp($what);
                   5561:     my @pairs=split(/\&/,$what);
                   5562:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   5563:     if ($hashref) {
                   5564:         foreach my $pair (@pairs) {
                   5565:             my ($key,$value)=split(/=/,$pair);
                   5566:             $hashref->{$key}=$value;
                   5567:         }
1.311     albertel 5568:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5569:             &Reply($client, "ok\n", $userinput);
                   5570:         } else {
                   5571:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5572:                      "while attempting domroleput\n", $userinput);
                   5573:         }
                   5574:     } else {
                   5575:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5576:                   "while attempting domroleput\n", $userinput);
                   5577:     }
                   5578:                                                                                   
                   5579:     return 1;
                   5580: }
                   5581: 
                   5582: &register_handler("domroleput", \&put_domainroles_handler, 0, 1, 0);
                   5583: 
                   5584: #
                   5585: # Retrieves domain roles from nohist_domainroles database
                   5586: # Returns to client an & separated list of key=value pairs,
                   5587: # where key is role and value is start and end date information.
                   5588: #
                   5589: # Parameters
                   5590: #   $cmd       - Command keyword that caused us to be dispatched.
                   5591: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5592: #               domain - the domain whose domain roles table we dump
                   5593: #   $client    - Socket open on the client.
                   5594: #
                   5595: # Returns:
                   5596: #    1 - indicating processing should continue.
                   5597: # Side effects
                   5598: #     reply (& separated list of role=start/end info pairs) is
                   5599: #     written to $client.
                   5600: #
                   5601: sub dump_domainroles_handler {
                   5602:     my ($cmd, $tail, $client) = @_;
                   5603:                                                                                            
                   5604:     my $userinput = "$cmd:$tail";
                   5605:     my ($udom,$startfilter,$endfilter,$rolesfilter) = split(/:/,$tail);
                   5606:     chomp($rolesfilter);
                   5607:     my @roles = ();
                   5608:     if (defined($startfilter)) {
                   5609:         $startfilter=&unescape($startfilter);
                   5610:     } else {
                   5611:         $startfilter='.';
                   5612:     }
                   5613:     if (defined($endfilter)) {
                   5614:         $endfilter=&unescape($endfilter);
                   5615:     } else {
                   5616:         $endfilter='.';
                   5617:     }
                   5618:     if (defined($rolesfilter)) {
                   5619:         $rolesfilter=&unescape($rolesfilter);
1.300     albertel 5620: 	@roles = split(/\&/,$rolesfilter);
1.299     raeburn  5621:     }
1.421     raeburn  5622: 
1.299     raeburn  5623:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   5624:     if ($hashref) {
                   5625:         my $qresult = '';
                   5626:         while (my ($key,$value) = each(%$hashref)) {
                   5627:             my $match = 1;
1.421     raeburn  5628:             my ($end,$start) = split(/:/,&unescape($value));
1.299     raeburn  5629:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,&unescape($key));
1.421     raeburn  5630:             unless (@roles < 1) {
                   5631:                 unless (grep/^\Q$trole\E$/,@roles) {
                   5632:                     $match = 0;
                   5633:                     next;
                   5634:                 }
                   5635:             }
1.299     raeburn  5636:             unless ($startfilter eq '.' || !defined($startfilter)) {
1.415     raeburn  5637:                 if ((defined($start)) && ($start >= $startfilter)) {
1.299     raeburn  5638:                     $match = 0;
1.421     raeburn  5639:                     next;
1.299     raeburn  5640:                 }
                   5641:             }
                   5642:             unless ($endfilter eq '.' || !defined($endfilter)) {
1.421     raeburn  5643:                 if ((defined($end)) && (($end > 0) && ($end <= $endfilter))) {
1.299     raeburn  5644:                     $match = 0;
1.421     raeburn  5645:                     next;
1.299     raeburn  5646:                 }
                   5647:             }
                   5648:             if ($match == 1) {
                   5649:                 $qresult.=$key.'='.$value.'&';
                   5650:             }
                   5651:         }
1.311     albertel 5652:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5653:             chop($qresult);
1.387     albertel 5654:             &Reply($client, \$qresult, $userinput);
1.299     raeburn  5655:         } else {
                   5656:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5657:                     "while attempting domrolesdump\n", $userinput);
                   5658:         }
                   5659:     } else {
                   5660:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5661:                 "while attempting domrolesdump\n", $userinput);
                   5662:     }
                   5663:     return 1;
                   5664: }
                   5665: 
                   5666: &register_handler("domrolesdump", \&dump_domainroles_handler, 0, 1, 0);
                   5667: 
                   5668: 
1.238     foxr     5669: #  Process the tmpput command I'm not sure what this does.. Seems to
                   5670: #  create a file in the lonDaemons/tmp directory of the form $id.tmp
                   5671: # where Id is the client's ip concatenated with a sequence number.
                   5672: # The file will contain some value that is passed in.  Is this e.g.
                   5673: # a login token?
                   5674: #
                   5675: # Parameters:
                   5676: #    $cmd     - The command that got us dispatched.
                   5677: #    $tail    - The remainder of the request following $cmd:
                   5678: #               In this case this will be the contents of the file.
                   5679: #    $client  - Socket connected to the client.
                   5680: # Returns:
                   5681: #    1 indicating processing can continue.
                   5682: # Side effects:
                   5683: #   A file is created in the local filesystem.
                   5684: #   A reply is sent to the client.
                   5685: sub tmp_put_handler {
                   5686:     my ($cmd, $what, $client) = @_;
                   5687: 
                   5688:     my $userinput = "$cmd:$what";	# Reconstruct for logging.
                   5689: 
1.347     raeburn  5690:     my ($record,$context) = split(/:/,$what);
                   5691:     if ($context ne '') {
                   5692:         chomp($context);
                   5693:         $context = &unescape($context);
                   5694:     }
                   5695:     my ($id,$store);
1.238     foxr     5696:     $tmpsnum++;
1.569     raeburn  5697:     my $numtries = 0;
                   5698:     my $execdir=$perlvar{'lonDaemons'};
                   5699:     if (($context eq 'resetpw') || ($context eq 'createaccount') ||
                   5700:         ($context eq 'sso') || ($context eq 'link') || ($context eq 'retry')) {
                   5701:         $id = &md5_hex(&md5_hex(time.{}.rand().$$.$tmpsnum));
                   5702:         while ((-e "$execdir/tmp/$id.tmp") && ($numtries <10)) {
                   5703:             undef($id);
                   5704:             $id = &md5_hex(&md5_hex(time.{}.rand().$$.$tmpsnum));
                   5705:             $numtries ++;
                   5706:         }
1.347     raeburn  5707:     } else {
                   5708:         $id = $$.'_'.$clientip.'_'.$tmpsnum;
                   5709:     }
1.238     foxr     5710:     $id=~s/\W/\_/g;
1.347     raeburn  5711:     $record=~s/\n//g;
1.569     raeburn  5712:     if (($id ne '') &&
                   5713:         ($store=IO::File->new(">$execdir/tmp/$id.tmp"))) {
1.347     raeburn  5714: 	print $store $record;
1.238     foxr     5715: 	close $store;
1.387     albertel 5716: 	&Reply($client, \$id, $userinput);
1.238     foxr     5717:     } else {
                   5718: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   5719: 		  "while attempting tmpput\n", $userinput);
                   5720:     }
                   5721:     return 1;
                   5722:   
                   5723: }
                   5724: &register_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
1.263     albertel 5725: 
1.238     foxr     5726: #   Processes the tmpget command.  This command returns the contents
                   5727: #  of a temporary resource file(?) created via tmpput.
                   5728: #
                   5729: # Paramters:
                   5730: #    $cmd      - Command that got us dispatched.
                   5731: #    $id       - Tail of the command, contain the id of the resource
                   5732: #                we want to fetch.
                   5733: #    $client   - socket open on the client.
                   5734: # Return:
                   5735: #    1         - Inidcating processing can continue.
                   5736: # Side effects:
                   5737: #   A reply is sent to the client.
                   5738: #
                   5739: sub tmp_get_handler {
                   5740:     my ($cmd, $id, $client) = @_;
                   5741: 
                   5742:     my $userinput = "$cmd:$id"; 
                   5743:     
                   5744: 
                   5745:     $id=~s/\W/\_/g;
                   5746:     my $store;
                   5747:     my $execdir=$perlvar{'lonDaemons'};
                   5748:     if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
                   5749: 	my $reply=<$store>;
1.387     albertel 5750: 	&Reply( $client, \$reply, $userinput);
1.238     foxr     5751: 	close $store;
                   5752:     } else {
                   5753: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   5754: 		  "while attempting tmpget\n", $userinput);
                   5755:     }
                   5756: 
                   5757:     return 1;
                   5758: }
                   5759: &register_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
1.263     albertel 5760: 
1.238     foxr     5761: #
                   5762: #  Process the tmpdel command.  This command deletes a temp resource
                   5763: #  created by the tmpput command.
                   5764: #
                   5765: # Parameters:
                   5766: #   $cmd      - Command that got us here.
                   5767: #   $id       - Id of the temporary resource created.
                   5768: #   $client   - socket open on the client process.
                   5769: #
                   5770: # Returns:
                   5771: #   1     - Indicating processing should continue.
                   5772: # Side Effects:
                   5773: #   A file is deleted
                   5774: #   A reply is sent to the client.
                   5775: sub tmp_del_handler {
                   5776:     my ($cmd, $id, $client) = @_;
                   5777:     
                   5778:     my $userinput= "$cmd:$id";
                   5779:     
                   5780:     chomp($id);
                   5781:     $id=~s/\W/\_/g;
                   5782:     my $execdir=$perlvar{'lonDaemons'};
                   5783:     if (unlink("$execdir/tmp/$id.tmp")) {
                   5784: 	&Reply($client, "ok\n", $userinput);
                   5785:     } else {
                   5786: 	&Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
                   5787: 		  "while attempting tmpdel\n", $userinput);
                   5788:     }
                   5789:     
                   5790:     return 1;
                   5791: 
                   5792: }
                   5793: &register_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
1.263     albertel 5794: 
1.238     foxr     5795: #
1.564     raeburn  5796: #  Process the updatebalcookie command.  This command updates a
                   5797: #  cookie in the lonBalancedir directory on a load balancer node.
                   5798: #
                   5799: # Parameters:
                   5800: #   $cmd      - Command that got us here.
                   5801: #   $tail     - Tail of the request (escaped cookie: escaped current entry)
                   5802: #
                   5803: #   $client   - socket open on the client process.
                   5804: #
                   5805: # Returns:
                   5806: #   1     - Indicating processing should continue.
                   5807: # Side Effects:
                   5808: #   A cookie file is updated from the lonBalancedir directory
                   5809: #   A reply is sent to the client.
                   5810: #
                   5811: sub update_balcookie_handler {
                   5812:     my ($cmd, $tail, $client) = @_;
                   5813: 
                   5814:     my $userinput= "$cmd:$tail";
                   5815:     chomp($tail);
                   5816:     my ($cookie,$lastentry) = map { &unescape($_) } (split(/:/,$tail));
                   5817: 
                   5818:     my $updatedone;
                   5819:     if ($cookie =~ /^$LONCAPA::match_domain\_$LONCAPA::match_username\_[a-f0-9]{32}$/) {
                   5820:         my $execdir=$perlvar{'lonBalanceDir'};
                   5821:         if (-e "$execdir/$cookie.id") {
                   5822:             my $doupdate;
                   5823:             if (open(my $fh,'<',"$execdir/$cookie.id")) {
                   5824:                 while (my $line = <$fh>) {
                   5825:                     chomp($line);
                   5826:                     if ($line eq $lastentry) {
                   5827:                         $doupdate = 1;
                   5828:                         last;
                   5829:                     }
                   5830:                 }
                   5831:                 close($fh);
                   5832:             }
                   5833:             if ($doupdate) {
                   5834:                 if (open(my $fh,'>',"$execdir/$cookie.id")) {
                   5835:                     print $fh $clientname;
                   5836:                     close($fh);
                   5837:                     $updatedone = 1;
                   5838:                 }
                   5839:             }
                   5840:         }
                   5841:     }
                   5842:     if ($updatedone) {
                   5843:         &Reply($client, "ok\n", $userinput);
                   5844:     } else {
                   5845:         &Failure( $client, "error: ".($!+0)."file update failed ".
                   5846:                   "while attempting updatebalcookie\n", $userinput);
                   5847:     }
                   5848:     return 1;
                   5849: }
                   5850: &register_handler("updatebalcookie", \&update_balcookie_handler, 0, 1, 0);
                   5851: 
                   5852: #
1.551     raeburn  5853: #  Process the delbalcookie command. This command deletes a balancer
1.564     raeburn  5854: #  cookie in the lonBalancedir directory on a load balancer node.
1.551     raeburn  5855: #
                   5856: # Parameters:
                   5857: #   $cmd      - Command that got us here.
                   5858: #   $cookie   - Cookie to be deleted.
                   5859: #   $client   - socket open on the client process.
                   5860: #
                   5861: # Returns:
                   5862: #   1     - Indicating processing should continue.
                   5863: # Side Effects:
                   5864: #   A cookie file is deleted from the lonBalancedir directory
                   5865: #   A reply is sent to the client.
                   5866: sub del_balcookie_handler {
                   5867:     my ($cmd, $cookie, $client) = @_;
                   5868: 
                   5869:     my $userinput= "$cmd:$cookie";
                   5870: 
                   5871:     chomp($cookie);
1.564     raeburn  5872:     $cookie = &unescape($cookie);
1.551     raeburn  5873:     my $deleted = '';
                   5874:     if ($cookie =~ /^$LONCAPA::match_domain\_$LONCAPA::match_username\_[a-f0-9]{32}$/) {
                   5875:         my $execdir=$perlvar{'lonBalanceDir'};
                   5876:         if (-e "$execdir/$cookie.id") {
                   5877:             if (open(my $fh,'<',"$execdir/$cookie.id")) {
                   5878:                 my $dodelete;
                   5879:                 while (my $line = <$fh>) {
                   5880:                     chomp($line);
                   5881:                     if ($line eq $clientname) {
                   5882:                         $dodelete = 1;
1.554     raeburn  5883:                         last;
1.551     raeburn  5884:                     }
                   5885:                 }
1.554     raeburn  5886:                 close($fh);
1.551     raeburn  5887:                 if ($dodelete) {
                   5888:                     if (unlink("$execdir/$cookie.id")) {
                   5889:                         $deleted = 1;
                   5890:                     }
                   5891:                 }
                   5892:             }
                   5893:         }
                   5894:     }
                   5895:     if ($deleted) {
                   5896:         &Reply($client, "ok\n", $userinput);
                   5897:     } else {
                   5898:         &Failure( $client, "error: ".($!+0)."Unlinking cookie file Failed ".
                   5899:                   "while attempting delbalcookie\n", $userinput);
                   5900:     }
                   5901:     return 1;
                   5902: }
                   5903: &register_handler("delbalcookie", \&del_balcookie_handler, 0, 1, 0);
                   5904: 
                   5905: #
1.246     foxr     5906: #   Processes the setannounce command.  This command
                   5907: #   creates a file named announce.txt in the top directory of
                   5908: #   the documentn root and sets its contents.  The announce.txt file is
                   5909: #   printed in its entirety at the LonCAPA login page.  Note:
                   5910: #   once the announcement.txt fileis created it cannot be deleted.
                   5911: #   However, setting the contents of the file to empty removes the
                   5912: #   announcement from the login page of loncapa so who cares.
                   5913: #
                   5914: # Parameters:
                   5915: #    $cmd          - The command that got us dispatched.
                   5916: #    $announcement - The text of the announcement.
                   5917: #    $client       - Socket open on the client process.
                   5918: # Retunrns:
                   5919: #   1             - Indicating request processing should continue
                   5920: # Side Effects:
                   5921: #   The file {DocRoot}/announcement.txt is created.
                   5922: #   A reply is sent to $client.
                   5923: #
                   5924: sub set_announce_handler {
                   5925:     my ($cmd, $announcement, $client) = @_;
                   5926:   
                   5927:     my $userinput    = "$cmd:$announcement";
                   5928: 
                   5929:     chomp($announcement);
                   5930:     $announcement=&unescape($announcement);
                   5931:     if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
                   5932: 				'/announcement.txt')) {
                   5933: 	print $store $announcement;
                   5934: 	close $store;
                   5935: 	&Reply($client, "ok\n", $userinput);
                   5936:     } else {
                   5937: 	&Failure($client, "error: ".($!+0)."\n", $userinput);
                   5938:     }
                   5939: 
                   5940:     return 1;
                   5941: }
                   5942: &register_handler("setannounce", \&set_announce_handler, 0, 1, 0);
1.263     albertel 5943: 
1.246     foxr     5944: #
                   5945: #  Return the version of the daemon.  This can be used to determine
                   5946: #  the compatibility of cross version installations or, alternatively to
                   5947: #  simply know who's out of date and who isn't.  Note that the version
                   5948: #  is returned concatenated with the tail.
                   5949: # Parameters:
                   5950: #   $cmd        - the request that dispatched to us.
                   5951: #   $tail       - Tail of the request (client's version?).
                   5952: #   $client     - Socket open on the client.
                   5953: #Returns:
                   5954: #   1 - continue processing requests.
                   5955: # Side Effects:
                   5956: #   Replies with version to $client.
                   5957: sub get_version_handler {
                   5958:     my ($cmd, $tail, $client) = @_;
                   5959: 
                   5960:     my $userinput  = $cmd.$tail;
                   5961:     
                   5962:     &Reply($client, &version($userinput)."\n", $userinput);
                   5963: 
                   5964: 
                   5965:     return 1;
                   5966: }
                   5967: &register_handler("version", \&get_version_handler, 0, 1, 0);
1.263     albertel 5968: 
1.246     foxr     5969: #  Set the current host and domain.  This is used to support
                   5970: #  multihomed systems.  Each IP of the system, or even separate daemons
                   5971: #  on the same IP can be treated as handling a separate lonCAPA virtual
                   5972: #  machine.  This command selects the virtual lonCAPA.  The client always
                   5973: #  knows the right one since it is lonc and it is selecting the domain/system
                   5974: #  from the hosts.tab file.
                   5975: # Parameters:
                   5976: #    $cmd      - Command that dispatched us.
                   5977: #    $tail     - Tail of the command (domain/host requested).
                   5978: #    $socket   - Socket open on the client.
                   5979: #
                   5980: # Returns:
                   5981: #     1   - Indicates the program should continue to process requests.
                   5982: # Side-effects:
                   5983: #     The default domain/system context is modified for this daemon.
                   5984: #     a reply is sent to the client.
                   5985: #
                   5986: sub set_virtual_host_handler {
                   5987:     my ($cmd, $tail, $socket) = @_;
                   5988:   
                   5989:     my $userinput  ="$cmd:$tail";
                   5990: 
                   5991:     &Reply($client, &sethost($userinput)."\n", $userinput);
                   5992: 
                   5993: 
                   5994:     return 1;
                   5995: }
1.247     albertel 5996: &register_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
1.246     foxr     5997: 
                   5998: #  Process a request to exit:
                   5999: #   - "bye" is sent to the client.
                   6000: #   - The client socket is shutdown and closed.
                   6001: #   - We indicate to the caller that we should exit.
                   6002: # Formal Parameters:
                   6003: #   $cmd                - The command that got us here.
                   6004: #   $tail               - Tail of the command (empty).
                   6005: #   $client             - Socket open on the tail.
                   6006: # Returns:
                   6007: #   0      - Indicating the program should exit!!
                   6008: #
                   6009: sub exit_handler {
                   6010:     my ($cmd, $tail, $client) = @_;
                   6011: 
                   6012:     my $userinput = "$cmd:$tail";
                   6013: 
                   6014:     &logthis("Client $clientip ($clientname) hanging up: $userinput");
                   6015:     &Reply($client, "bye\n", $userinput);
                   6016:     $client->shutdown(2);        # shutdown the socket forcibly.
                   6017:     $client->close();
                   6018: 
                   6019:     return 0;
                   6020: }
1.248     foxr     6021: &register_handler("exit", \&exit_handler, 0,1,1);
                   6022: &register_handler("init", \&exit_handler, 0,1,1);
                   6023: &register_handler("quit", \&exit_handler, 0,1,1);
                   6024: 
                   6025: #  Determine if auto-enrollment is enabled.
                   6026: #  Note that the original had what I believe to be a defect.
                   6027: #  The original returned 0 if the requestor was not a registerd client.
                   6028: #  It should return "refused".
                   6029: # Formal Parameters:
                   6030: #   $cmd       - The command that invoked us.
                   6031: #   $tail      - The tail of the command (Extra command parameters.
                   6032: #   $client    - The socket open on the client that issued the request.
                   6033: # Returns:
                   6034: #    1         - Indicating processing should continue.
                   6035: #
                   6036: sub enrollment_enabled_handler {
                   6037:     my ($cmd, $tail, $client) = @_;
                   6038:     my $userinput = $cmd.":".$tail; # For logging purposes.
                   6039: 
                   6040:     
1.337     albertel 6041:     my ($cdom) = split(/:/, $tail, 2);   # Domain we're asking about.
                   6042: 
1.248     foxr     6043:     my $outcome  = &localenroll::run($cdom);
1.387     albertel 6044:     &Reply($client, \$outcome, $userinput);
1.248     foxr     6045: 
                   6046:     return 1;
                   6047: }
                   6048: &register_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
                   6049: 
1.417     raeburn  6050: #
1.423     raeburn  6051: #   Validate an institutional code used for a LON-CAPA course.          
1.417     raeburn  6052: #
                   6053: # Formal Parameters:
                   6054: #   $cmd          - The command request that got us dispatched.
                   6055: #   $tail         - The tail of the command.  In this case,
                   6056: #                   this is a colon separated set of words that will be split
                   6057: #                   into:
1.424     raeburn  6058: #                        $dom      - The domain for which the check of 
                   6059: #                                    institutional course code will occur.
                   6060: #
                   6061: #                        $instcode - The institutional code for the course
                   6062: #                                    being requested, or validated for rights
                   6063: #                                    to request.
                   6064: #
                   6065: #                        $owner    - The course requestor (who will be the
                   6066: #                                    course owner, in the form username:domain
                   6067: #
1.417     raeburn  6068: #   $client       - Socket open on the client.
                   6069: # Returns:
                   6070: #    1           - Indicating processing should continue.
                   6071: #
                   6072: sub validate_instcode_handler {
                   6073:     my ($cmd, $tail, $client) = @_;
                   6074:     my $userinput = "$cmd:$tail";
1.423     raeburn  6075:     my ($dom,$instcode,$owner) = split(/:/, $tail);
1.422     raeburn  6076:     $instcode = &unescape($instcode);
                   6077:     $owner = &unescape($owner);
1.498     raeburn  6078:     my ($outcome,$description,$credits) = 
1.426     raeburn  6079:         &localenroll::validate_instcode($dom,$instcode,$owner);
1.498     raeburn  6080:     my $result = &escape($outcome).'&'.&escape($description).'&'.
                   6081:                  &escape($credits);
1.426     raeburn  6082:     &Reply($client, \$result, $userinput);
1.417     raeburn  6083: 
                   6084:     return 1;
                   6085: }
                   6086: &register_handler("autovalidateinstcode", \&validate_instcode_handler, 0, 1, 0);
                   6087: 
1.566     raeburn  6088: #
                   6089: #  Validate co-owner for cross-listed institutional code and
                   6090: #  institutional course code itself used for a LON-CAPA course.
                   6091: #
                   6092: # Formal Parameters:
                   6093: #   $cmd          - The command request that got us dispatched.
                   6094: #   $tail         - The tail of the command.  In this case,
                   6095: #                   this is a colon separated string containing:
                   6096: #      $dom            - Course's LON-CAPA domain
                   6097: #      $instcode       - Institutional course code for the course
                   6098: #      $inst_xlist     - Institutional course Id for the crosslisting
                   6099: #      $coowner        - Username of co-owner
                   6100: #      (values for all but $dom have been escaped). 
                   6101: #
                   6102: #   $client       - Socket open on the client.
                   6103: # Returns:
                   6104: #    1           - Indicating processing should continue.
                   6105: #
                   6106: sub validate_instcrosslist_handler  {
                   6107:     my ($cmd, $tail, $client) = @_;
                   6108:     my $userinput = "$cmd:$tail";
                   6109:     my ($dom,$instcode,$inst_xlist,$coowner) = split(/:/,$tail);
                   6110:     $instcode = &unescape($instcode);
                   6111:     $inst_xlist = &unescape($inst_xlist);
                   6112:     $coowner = &unescape($coowner);
                   6113:     my $outcome = &localenroll::validate_crosslist_access($dom,$instcode,
                   6114:                                                           $inst_xlist,$coowner);
                   6115:     &Reply($client, \$outcome, $userinput);
                   6116: 
                   6117:     return 1;
                   6118: }
                   6119: &register_handler("autovalidateinstcrosslist", \&validate_instcrosslist_handler, 0, 1, 0);
                   6120: 
1.248     foxr     6121: #   Get the official sections for which auto-enrollment is possible.
                   6122: #   Since the admin people won't know about 'unofficial sections' 
                   6123: #   we cannot auto-enroll on them.
                   6124: # Formal Parameters:
                   6125: #    $cmd     - The command request that got us dispatched here.
                   6126: #    $tail    - The remainder of the request.  In our case this
                   6127: #               will be split into:
                   6128: #               $coursecode   - The course name from the admin point of view.
                   6129: #               $cdom         - The course's domain(?).
                   6130: #    $client  - Socket open on the client.
                   6131: # Returns:
                   6132: #    1    - Indiciting processing should continue.
                   6133: #
                   6134: sub get_sections_handler {
                   6135:     my ($cmd, $tail, $client) = @_;
                   6136:     my $userinput = "$cmd:$tail";
                   6137: 
                   6138:     my ($coursecode, $cdom) = split(/:/, $tail);
                   6139:     my @secs = &localenroll::get_sections($coursecode,$cdom);
                   6140:     my $seclist = &escape(join(':',@secs));
                   6141: 
1.387     albertel 6142:     &Reply($client, \$seclist, $userinput);
1.248     foxr     6143:     
                   6144: 
                   6145:     return 1;
                   6146: }
                   6147: &register_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
                   6148: 
                   6149: #   Validate the owner of a new course section.  
                   6150: #
                   6151: # Formal Parameters:
                   6152: #   $cmd      - Command that got us dispatched.
                   6153: #   $tail     - the remainder of the command.  For us this consists of a
                   6154: #               colon separated string containing:
                   6155: #                  $inst    - Course Id from the institutions point of view.
                   6156: #                  $owner   - Proposed owner of the course.
                   6157: #                  $cdom    - Domain of the course (from the institutions
                   6158: #                             point of view?)..
                   6159: #   $client   - Socket open on the client.
                   6160: #
                   6161: # Returns:
                   6162: #   1        - Processing should continue.
                   6163: #
                   6164: sub validate_course_owner_handler {
                   6165:     my ($cmd, $tail, $client)  = @_;
                   6166:     my $userinput = "$cmd:$tail";
1.470     raeburn  6167:     my ($inst_course_id, $owner, $cdom, $coowners) = split(/:/, $tail);
                   6168:     
1.336     raeburn  6169:     $owner = &unescape($owner);
1.470     raeburn  6170:     $coowners = &unescape($coowners);
                   6171:     my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom,$coowners);
1.387     albertel 6172:     &Reply($client, \$outcome, $userinput);
1.248     foxr     6173: 
                   6174: 
                   6175: 
                   6176:     return 1;
                   6177: }
                   6178: &register_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
1.263     albertel 6179: 
1.248     foxr     6180: #
                   6181: #   Validate a course section in the official schedule of classes
                   6182: #   from the institutions point of view (part of autoenrollment).
                   6183: #
                   6184: # Formal Parameters:
                   6185: #   $cmd          - The command request that got us dispatched.
                   6186: #   $tail         - The tail of the command.  In this case,
                   6187: #                   this is a colon separated set of words that will be split
                   6188: #                   into:
                   6189: #                        $inst_course_id - The course/section id from the
                   6190: #                                          institutions point of view.
                   6191: #                        $cdom           - The domain from the institutions
                   6192: #                                          point of view.
                   6193: #   $client       - Socket open on the client.
                   6194: # Returns:
                   6195: #    1           - Indicating processing should continue.
                   6196: #
                   6197: sub validate_course_section_handler {
                   6198:     my ($cmd, $tail, $client) = @_;
                   6199:     my $userinput = "$cmd:$tail";
                   6200:     my ($inst_course_id, $cdom) = split(/:/, $tail);
                   6201: 
                   6202:     my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
1.387     albertel 6203:     &Reply($client, \$outcome, $userinput);
1.248     foxr     6204: 
                   6205: 
                   6206:     return 1;
                   6207: }
                   6208: &register_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
                   6209: 
                   6210: #
1.340     raeburn  6211: #   Validate course owner's access to enrollment data for specific class section. 
                   6212: #   
                   6213: #
                   6214: # Formal Parameters:
                   6215: #    $cmd     - The command request that got us dispatched.
                   6216: #    $tail    - The tail of the command.   In this case this is a colon separated
1.542     raeburn  6217: #               set of values that will be split into:
1.340     raeburn  6218: #               $inst_class  - Institutional code for the specific class section   
1.542     raeburn  6219: #               $ownerlist   - An escaped comma-separated list of username:domain 
                   6220: #                              of the course owner, and co-owner(s).
1.340     raeburn  6221: #               $cdom        - The domain of the course from the institution's
                   6222: #                              point of view.
                   6223: #    $client  - The socket open on the client.
                   6224: # Returns:
                   6225: #    1 - continue processing.
                   6226: #
                   6227: 
                   6228: sub validate_class_access_handler {
                   6229:     my ($cmd, $tail, $client) = @_;
                   6230:     my $userinput = "$cmd:$tail";
1.383     raeburn  6231:     my ($inst_class,$ownerlist,$cdom) = split(/:/, $tail);
1.392     raeburn  6232:     my $owners = &unescape($ownerlist);
1.341     albertel 6233:     my $outcome;
                   6234:     eval {
                   6235: 	local($SIG{__DIE__})='DEFAULT';
1.392     raeburn  6236: 	$outcome=&localenroll::check_section($inst_class,$owners,$cdom);
1.341     albertel 6237:     };
1.387     albertel 6238:     &Reply($client,\$outcome, $userinput);
1.340     raeburn  6239: 
                   6240:     return 1;
                   6241: }
                   6242: &register_handler("autovalidateclass_sec", \&validate_class_access_handler, 0, 1, 0);
                   6243: 
                   6244: #
1.567     raeburn  6245: #    Modify institutional sections (using customized &instsec_reformat()
                   6246: #    routine in localenroll.pm), to either clutter or declutter, for  
                   6247: #    purposes of ensuring an institutional course section (string) can
                   6248: #    be unambiguously separated into institutional course and section.
                   6249: #
                   6250: # Formal Parameters:
                   6251: #    $cmd     - The command request that got us dispatched.
                   6252: #    $tail    - The tail of the command.   In this case this is a colon separated
                   6253: #               set of values that will be split into:
                   6254: #               $cdom        - The LON-CAPA domain of the course.
                   6255: #               $action      - Either: clutter or declutter
                   6256: #                              clutter adds character(s) to eliminate ambiguity
                   6257: #                              declutter removes the added characters (e.g., for
                   6258: #                              display of the institutional course section string.
                   6259: #               $info        - A frozen hash in which keys are: 
                   6260: #                              LON-CAPA course number:Institutional course code
                   6261: #                              and values are a reference to an array of the
                   6262: #                              items to modify -- either institutional sections,
                   6263: #                              or institutional course sections (for crosslistings). 
                   6264: #    $client  - The socket open on the client.
                   6265: # Returns:
                   6266: #    1 - continue processing.
                   6267: #   
                   6268: 
                   6269: sub instsec_reformat_handler {
                   6270:     my ($cmd, $tail, $client) = @_;
                   6271:     my $userinput = "$cmd:$tail";
                   6272:     my ($cdom,$action,$info) = split(/:/,$tail);
                   6273:     my $instsecref = &Apache::lonnet::thaw_unescape($info);
                   6274:     my ($outcome,$result);
                   6275:     eval {
                   6276:         local($SIG{__DIE__})='DEFAULT';
                   6277:         $outcome=&localenroll::instsec_reformat($cdom,$action,$instsecref);
                   6278:         if ($outcome eq 'ok') {
                   6279:             if (ref($instsecref) eq 'HASH') {
                   6280:                 foreach my $key (keys(%{$instsecref})) {
                   6281:                     $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($instsecref->{$key}).'&';
                   6282:                 }
                   6283:                 $result =~ s/\&$//;
                   6284:             }
                   6285:         }
                   6286:     };
                   6287:     if (!$@) {
                   6288:         if ($outcome eq 'ok') {
                   6289:             &Reply( $client, \$result, $userinput);
                   6290:         } else {
                   6291:             &Reply($client,\$outcome, $userinput);
                   6292:         }
                   6293:     } else {
                   6294:         &Failure($client,"unknown_cmd\n",$userinput);
                   6295:     }
                   6296:     return 1;
                   6297: }
                   6298: &register_handler("autoinstsecreformat",\&instsec_reformat_handler, 0, 1, 0);
                   6299: 
                   6300: #
1.542     raeburn  6301: #   Validate course owner or co-owners(s) access to enrollment data for all sections
                   6302: #   and crosslistings for a particular course.
                   6303: #
                   6304: #
                   6305: # Formal Parameters:
                   6306: #    $cmd     - The command request that got us dispatched.
                   6307: #    $tail    - The tail of the command.   In this case this is a colon separated
                   6308: #               set of values that will be split into:
                   6309: #               $ownerlist   - An escaped comma-separated list of username:domain
                   6310: #                              of the course owner, and co-owner(s).
                   6311: #               $cdom        - The domain of the course from the institution's
                   6312: #                              point of view.
                   6313: #               $classes     - Frozen hash of institutional course sections and
                   6314: #                              crosslistings.
                   6315: #    $client  - The socket open on the client.
                   6316: # Returns:
                   6317: #    1 - continue processing.
                   6318: #
                   6319: 
                   6320: sub validate_classes_handler {
                   6321:     my ($cmd, $tail, $client) = @_;
                   6322:     my $userinput = "$cmd:$tail";
                   6323:     my ($ownerlist,$cdom,$classes) = split(/:/, $tail);
                   6324:     my $classesref = &Apache::lonnet::thaw_unescape($classes);
                   6325:     my $owners = &unescape($ownerlist);
                   6326:     my $result;
                   6327:     eval {
                   6328:         local($SIG{__DIE__})='DEFAULT';
                   6329:         my %validations;
                   6330:         my $response = &localenroll::check_instclasses($owners,$cdom,$classesref,
                   6331:                                                        \%validations);
                   6332:         if ($response eq 'ok') {
                   6333:             foreach my $key (keys(%validations)) {
                   6334:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
                   6335:             }
                   6336:             $result =~ s/\&$//;
                   6337:         } else {
                   6338:             $result = 'error';
                   6339:         }
                   6340:     };
                   6341:     if (!$@) {
                   6342:         &Reply($client, \$result, $userinput);
                   6343:     } else {
                   6344:         &Failure($client,"unknown_cmd\n",$userinput);
                   6345:     }
                   6346:     return 1;
                   6347: }
                   6348: &register_handler("autovalidateinstclasses", \&validate_classes_handler, 0, 1, 0);
                   6349: 
                   6350: #
1.340     raeburn  6351: #   Create a password for a new LON-CAPA user added by auto-enrollment.
                   6352: #   Only used for case where authentication method for new user is localauth
1.248     foxr     6353: #
                   6354: # Formal Parameters:
                   6355: #    $cmd     - The command request that got us dispatched.
                   6356: #    $tail    - The tail of the command.   In this case this is a colon separated
                   6357: #               set of words that will be split into:
1.340     raeburn  6358: #               $authparam - An authentication parameter (localauth parameter).
1.248     foxr     6359: #               $cdom      - The domain of the course from the institution's
                   6360: #                            point of view.
                   6361: #    $client  - The socket open on the client.
                   6362: # Returns:
                   6363: #    1 - continue processing.
                   6364: #
                   6365: sub create_auto_enroll_password_handler {
                   6366:     my ($cmd, $tail, $client) = @_;
                   6367:     my $userinput = "$cmd:$tail";
                   6368: 
                   6369:     my ($authparam, $cdom) = split(/:/, $userinput);
                   6370: 
                   6371:     my ($create_passwd,$authchk);
                   6372:     ($authparam,
                   6373:      $create_passwd,
                   6374:      $authchk) = &localenroll::create_password($authparam,$cdom);
                   6375: 
                   6376:     &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
                   6377: 	   $userinput);
                   6378: 
                   6379: 
                   6380:     return 1;
                   6381: }
                   6382: &register_handler("autocreatepassword", \&create_auto_enroll_password_handler, 
                   6383: 		  0, 1, 0);
                   6384: 
1.522     raeburn  6385: sub auto_export_grades_handler {
                   6386:     my ($cmd, $tail, $client) = @_;
                   6387:     my $userinput = "$cmd:$tail";
                   6388:     my ($cdom,$cnum,$info,$data) = split(/:/,$tail);
                   6389:     my $inforef = &Apache::lonnet::thaw_unescape($info);
                   6390:     my $dataref = &Apache::lonnet::thaw_unescape($data);
                   6391:     my ($outcome,$result);;
                   6392:     eval {
                   6393:         local($SIG{__DIE__})='DEFAULT';
                   6394:         my %rtnhash;
                   6395:         $outcome=&localenroll::export_grades($cdom,$cnum,$inforef,$dataref,\%rtnhash);
                   6396:         if ($outcome eq 'ok') {
                   6397:             foreach my $key (keys(%rtnhash)) {
                   6398:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
                   6399:             }
                   6400:             $result =~ s/\&$//;
                   6401:         }
                   6402:     };
                   6403:     if (!$@) {
                   6404:         if ($outcome eq 'ok') {
                   6405:             if ($cipher) {
                   6406:                 my $cmdlength=length($result);
                   6407:                 $result.="         ";
                   6408:                 my $encresult='';
                   6409:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   6410:                     $encresult.= unpack("H16",
                   6411:                                         $cipher->encrypt(substr($result,
                   6412:                                                                 $encidx,
                   6413:                                                                 8)));
                   6414:                 }
                   6415:                 &Reply( $client, "enc:$cmdlength:$encresult\n", $userinput);
                   6416:             } else {
                   6417:                 &Failure( $client, "error:no_key\n", $userinput);
                   6418:             }
                   6419:         } else {
                   6420:             &Reply($client, "$outcome\n", $userinput);
                   6421:         }
                   6422:     } else {
                   6423:         &Failure($client,"export_error\n",$userinput);
                   6424:     }
                   6425:     return 1;
                   6426: }
                   6427: &register_handler("autoexportgrades", \&auto_export_grades_handler,
1.536     raeburn  6428:                   1, 1, 0);
1.522     raeburn  6429: 
1.248     foxr     6430: #   Retrieve and remove temporary files created by/during autoenrollment.
                   6431: #
                   6432: # Formal Parameters:
                   6433: #    $cmd      - The command that got us dispatched.
                   6434: #    $tail     - The tail of the command.  In our case this is a colon 
                   6435: #                separated list that will be split into:
1.526     raeburn  6436: #                $filename - The name of the file to retrieve.
1.248     foxr     6437: #                            The filename is given as a path relative to
                   6438: #                            the LonCAPA temp file directory.
                   6439: #    $client   - Socket open on the client.
                   6440: #
                   6441: # Returns:
                   6442: #   1     - Continue processing.
                   6443: sub retrieve_auto_file_handler {
                   6444:     my ($cmd, $tail, $client)    = @_;
                   6445:     my $userinput                = "cmd:$tail";
                   6446: 
                   6447:     my ($filename)   = split(/:/, $tail);
                   6448: 
                   6449:     my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
1.521     raeburn  6450: 
                   6451:     if ($filename =~m{/\.\./}) {
                   6452:         &Failure($client, "refused\n", $userinput);
1.526     raeburn  6453:     } elsif ($filename !~ /^$LONCAPA::match_domain\_$LONCAPA::match_courseid\_.+_classlist\.xml$/) {
                   6454:         &Failure($client, "refused\n", $userinput);
1.521     raeburn  6455:     } elsif ( (-e $source) && ($filename ne '') ) {
1.248     foxr     6456: 	my $reply = '';
                   6457: 	if (open(my $fh,$source)) {
                   6458: 	    while (<$fh>) {
                   6459: 		chomp($_);
                   6460: 		$_ =~ s/^\s+//g;
                   6461: 		$_ =~ s/\s+$//g;
                   6462: 		$reply .= $_;
                   6463: 	    }
                   6464: 	    close($fh);
                   6465: 	    &Reply($client, &escape($reply)."\n", $userinput);
                   6466: 
                   6467: #   Does this have to be uncommented??!?  (RF).
                   6468: #
                   6469: #                                unlink($source);
                   6470: 	} else {
                   6471: 	    &Failure($client, "error\n", $userinput);
                   6472: 	}
                   6473:     } else {
                   6474: 	&Failure($client, "error\n", $userinput);
                   6475:     }
                   6476:     
                   6477: 
                   6478:     return 1;
                   6479: }
                   6480: &register_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
                   6481: 
1.423     raeburn  6482: sub crsreq_checks_handler {
                   6483:     my ($cmd, $tail, $client) = @_;
                   6484:     my $userinput = "$cmd:$tail";
                   6485:     my $dom = $tail;
                   6486:     my $result;
1.519     raeburn  6487:     my @reqtypes = ('official','unofficial','community','textbook','placement');
1.423     raeburn  6488:     eval {
                   6489:         local($SIG{__DIE__})='DEFAULT';
                   6490:         my %validations;
1.424     raeburn  6491:         my $response = &localenroll::crsreq_checks($dom,\@reqtypes,
                   6492:                                                    \%validations);
1.423     raeburn  6493:         if ($response eq 'ok') { 
                   6494:             foreach my $key (keys(%validations)) {
                   6495:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
                   6496:             }
                   6497:             $result =~ s/\&$//;
                   6498:         } else {
                   6499:             $result = 'error';
                   6500:         }
                   6501:     };
                   6502:     if (!$@) {
                   6503:         &Reply($client, \$result, $userinput);
                   6504:     } else {
                   6505:         &Failure($client,"unknown_cmd\n",$userinput);
                   6506:     }
                   6507:     return 1;
                   6508: }
                   6509: &register_handler("autocrsreqchecks", \&crsreq_checks_handler, 0, 1, 0);
                   6510: 
                   6511: sub validate_crsreq_handler {
                   6512:     my ($cmd, $tail, $client) = @_;
                   6513:     my $userinput = "$cmd:$tail";
1.508     raeburn  6514:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$customdata) = split(/:/, $tail);
1.423     raeburn  6515:     $instcode = &unescape($instcode);
                   6516:     $owner = &unescape($owner);
                   6517:     $crstype = &unescape($crstype);
                   6518:     $inststatuslist = &unescape($inststatuslist);
                   6519:     $instcode = &unescape($instcode);
                   6520:     $instseclist = &unescape($instseclist);
1.508     raeburn  6521:     my $custominfo = &Apache::lonnet::thaw_unescape($customdata);
1.423     raeburn  6522:     my $outcome;
                   6523:     eval {
                   6524:         local($SIG{__DIE__})='DEFAULT';
                   6525:         $outcome = &localenroll::validate_crsreq($dom,$owner,$crstype,
                   6526:                                                  $inststatuslist,$instcode,
1.508     raeburn  6527:                                                  $instseclist,$custominfo);
1.423     raeburn  6528:     };
                   6529:     if (!$@) {
                   6530:         &Reply($client, \$outcome, $userinput);
                   6531:     } else {
                   6532:         &Failure($client,"unknown_cmd\n",$userinput);
                   6533:     }
                   6534:     return 1;
                   6535: }
                   6536: &register_handler("autocrsreqvalidation", \&validate_crsreq_handler, 0, 1, 0);
                   6537: 
1.506     raeburn  6538: sub crsreq_update_handler {
                   6539:     my ($cmd, $tail, $client) = @_;
                   6540:     my $userinput = "$cmd:$tail";
1.509     raeburn  6541:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,$code,
                   6542:         $accessstart,$accessend,$infohashref) =
1.506     raeburn  6543:         split(/:/, $tail);
                   6544:     $crstype = &unescape($crstype);
                   6545:     $action = &unescape($action);
                   6546:     $ownername = &unescape($ownername);
                   6547:     $ownerdomain = &unescape($ownerdomain);
                   6548:     $fullname = &unescape($fullname);
                   6549:     $title = &unescape($title);
                   6550:     $code = &unescape($code);
1.509     raeburn  6551:     $accessstart = &unescape($accessstart);
                   6552:     $accessend = &unescape($accessend);
1.506     raeburn  6553:     my $incoming = &Apache::lonnet::thaw_unescape($infohashref);
                   6554:     my ($result,$outcome);
                   6555:     eval {
                   6556:         local($SIG{__DIE__})='DEFAULT';
                   6557:         my %rtnhash;
                   6558:         $outcome = &localenroll::crsreq_updates($cdom,$cnum,$crstype,$action,
                   6559:                                                 $ownername,$ownerdomain,$fullname,
1.509     raeburn  6560:                                                 $title,$code,$accessstart,$accessend,
                   6561:                                                 $incoming,\%rtnhash);
1.506     raeburn  6562:         if ($outcome eq 'ok') {
1.515     raeburn  6563:             my @posskeys = qw(createdweb createdmsg createdcustomized createdactions queuedweb queuedmsg formitems reviewweb validationjs onload javascript);
1.506     raeburn  6564:             foreach my $key (keys(%rtnhash)) {
                   6565:                 if (grep(/^\Q$key\E/,@posskeys)) {
                   6566:                     $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
                   6567:                 }
                   6568:             }
                   6569:             $result =~ s/\&$//;
                   6570:         }
                   6571:     };
                   6572:     if (!$@) {
                   6573:         if ($outcome eq 'ok') {
                   6574:             &Reply($client, \$result, $userinput);
                   6575:         } else {
                   6576:             &Reply($client, "format_error\n", $userinput);
                   6577:         }
                   6578:     } else {
                   6579:         &Failure($client,"unknown_cmd\n",$userinput);
                   6580:     }
                   6581:     return 1;
                   6582: }
                   6583: &register_handler("autocrsrequpdate", \&crsreq_update_handler, 0, 1, 0);
                   6584: 
1.248     foxr     6585: #
                   6586: #   Read and retrieve institutional code format (for support form).
                   6587: # Formal Parameters:
                   6588: #    $cmd        - Command that dispatched us.
                   6589: #    $tail       - Tail of the command.  In this case it conatins 
                   6590: #                  the course domain and the coursename.
                   6591: #    $client     - Socket open on the client.
                   6592: # Returns:
                   6593: #    1     - Continue processing.
                   6594: #
                   6595: sub get_institutional_code_format_handler {
                   6596:     my ($cmd, $tail, $client)   = @_;
                   6597:     my $userinput               = "$cmd:$tail";
                   6598: 
                   6599:     my $reply;
                   6600:     my($cdom,$course) = split(/:/,$tail);
                   6601:     my @pairs = split/\&/,$course;
                   6602:     my %instcodes = ();
                   6603:     my %codes = ();
                   6604:     my @codetitles = ();
                   6605:     my %cat_titles = ();
                   6606:     my %cat_order = ();
                   6607:     foreach (@pairs) {
                   6608: 	my ($key,$value) = split/=/,$_;
                   6609: 	$instcodes{&unescape($key)} = &unescape($value);
                   6610:     }
                   6611:     my $formatreply = &localenroll::instcode_format($cdom,
                   6612: 						    \%instcodes,
                   6613: 						    \%codes,
                   6614: 						    \@codetitles,
                   6615: 						    \%cat_titles,
                   6616: 						    \%cat_order);
                   6617:     if ($formatreply eq 'ok') {
1.365     albertel 6618: 	my $codes_str = &Apache::lonnet::hash2str(%codes);
                   6619: 	my $codetitles_str = &Apache::lonnet::array2str(@codetitles);
                   6620: 	my $cat_titles_str = &Apache::lonnet::hash2str(%cat_titles);
                   6621: 	my $cat_order_str = &Apache::lonnet::hash2str(%cat_order);
1.248     foxr     6622: 	&Reply($client,
                   6623: 	       $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
                   6624: 	       .$cat_order_str."\n",
                   6625: 	       $userinput);
                   6626:     } else {
                   6627: 	# this else branch added by RF since if not ok, lonc will
                   6628: 	# hang waiting on reply until timeout.
                   6629: 	#
                   6630: 	&Reply($client, "format_error\n", $userinput);
                   6631:     }
                   6632:     
                   6633:     return 1;
                   6634: }
1.265     albertel 6635: &register_handler("autoinstcodeformat",
                   6636: 		  \&get_institutional_code_format_handler,0,1,0);
1.246     foxr     6637: 
1.345     raeburn  6638: sub get_institutional_defaults_handler {
                   6639:     my ($cmd, $tail, $client)   = @_;
                   6640:     my $userinput               = "$cmd:$tail";
                   6641: 
                   6642:     my $dom = $tail;
                   6643:     my %defaults_hash;
                   6644:     my @code_order;
                   6645:     my $outcome;
                   6646:     eval {
                   6647:         local($SIG{__DIE__})='DEFAULT';
                   6648:         $outcome = &localenroll::instcode_defaults($dom,\%defaults_hash,
                   6649:                                                    \@code_order);
                   6650:     };
                   6651:     if (!$@) {
                   6652:         if ($outcome eq 'ok') {
                   6653:             my $result='';
                   6654:             while (my ($key,$value) = each(%defaults_hash)) {
                   6655:                 $result.=&escape($key).'='.&escape($value).'&';
                   6656:             }
                   6657:             $result .= 'code_order='.&escape(join('&',@code_order));
1.387     albertel 6658:             &Reply($client,\$result,$userinput);
1.345     raeburn  6659:         } else {
                   6660:             &Reply($client,"error\n", $userinput);
                   6661:         }
                   6662:     } else {
                   6663:         &Failure($client,"unknown_cmd\n",$userinput);
                   6664:     }
                   6665: }
                   6666: &register_handler("autoinstcodedefaults",
                   6667:                   \&get_institutional_defaults_handler,0,1,0);
                   6668: 
1.416     raeburn  6669: sub get_possible_instcodes_handler {
                   6670:     my ($cmd, $tail, $client)   = @_;
                   6671:     my $userinput               = "$cmd:$tail";
                   6672: 
                   6673:     my $reply;
                   6674:     my $cdom = $tail;
1.417     raeburn  6675:     my (@codetitles,%cat_titles,%cat_order,@code_order);
1.416     raeburn  6676:     my $formatreply = &localenroll::possible_instcodes($cdom,
                   6677:                                                        \@codetitles,
                   6678:                                                        \%cat_titles,
1.417     raeburn  6679:                                                        \%cat_order,
                   6680:                                                        \@code_order);
1.416     raeburn  6681:     if ($formatreply eq 'ok') {
                   6682:         my $result = join('&',map {&escape($_);} (@codetitles)).':';
1.417     raeburn  6683:         $result .= join('&',map {&escape($_);} (@code_order)).':';
1.416     raeburn  6684:         foreach my $key (keys(%cat_titles)) {
                   6685:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_titles{$key}).'&';
                   6686:         }
                   6687:         $result =~ s/\&$//;
                   6688:         $result .= ':';
                   6689:         foreach my $key (keys(%cat_order)) {
                   6690:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_order{$key}).'&';
                   6691:         }
                   6692:         $result =~ s/\&$//;
                   6693:         &Reply($client,\$result,$userinput);
                   6694:     } else {
                   6695:         &Reply($client, "format_error\n", $userinput);
                   6696:     }
                   6697:     return 1;
                   6698: }
                   6699: &register_handler("autopossibleinstcodes",
                   6700:                   \&get_possible_instcodes_handler,0,1,0);
                   6701: 
1.381     raeburn  6702: sub get_institutional_user_rules {
                   6703:     my ($cmd, $tail, $client)   = @_;
                   6704:     my $userinput               = "$cmd:$tail";
                   6705:     my $dom = &unescape($tail);
                   6706:     my (%rules_hash,@rules_order);
                   6707:     my $outcome;
                   6708:     eval {
                   6709:         local($SIG{__DIE__})='DEFAULT';
                   6710:         $outcome = &localenroll::username_rules($dom,\%rules_hash,\@rules_order);
                   6711:     };
                   6712:     if (!$@) {
                   6713:         if ($outcome eq 'ok') {
                   6714:             my $result;
                   6715:             foreach my $key (keys(%rules_hash)) {
                   6716:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6717:             }
                   6718:             $result =~ s/\&$//;
                   6719:             $result .= ':';
                   6720:             if (@rules_order > 0) {
                   6721:                 foreach my $item (@rules_order) {
                   6722:                     $result .= &escape($item).'&';
                   6723:                 }
                   6724:             }
                   6725:             $result =~ s/\&$//;
1.387     albertel 6726:             &Reply($client,\$result,$userinput);
1.381     raeburn  6727:         } else {
                   6728:             &Reply($client,"error\n", $userinput);
                   6729:         }
                   6730:     } else {
                   6731:         &Failure($client,"unknown_cmd\n",$userinput);
                   6732:     }
                   6733: }
                   6734: &register_handler("instuserrules",\&get_institutional_user_rules,0,1,0);
                   6735: 
1.389     raeburn  6736: sub get_institutional_id_rules {
                   6737:     my ($cmd, $tail, $client)   = @_;
                   6738:     my $userinput               = "$cmd:$tail";
                   6739:     my $dom = &unescape($tail);
                   6740:     my (%rules_hash,@rules_order);
                   6741:     my $outcome;
                   6742:     eval {
                   6743:         local($SIG{__DIE__})='DEFAULT';
                   6744:         $outcome = &localenroll::id_rules($dom,\%rules_hash,\@rules_order);
                   6745:     };
                   6746:     if (!$@) {
                   6747:         if ($outcome eq 'ok') {
                   6748:             my $result;
                   6749:             foreach my $key (keys(%rules_hash)) {
                   6750:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6751:             }
                   6752:             $result =~ s/\&$//;
                   6753:             $result .= ':';
                   6754:             if (@rules_order > 0) {
                   6755:                 foreach my $item (@rules_order) {
                   6756:                     $result .= &escape($item).'&';
                   6757:                 }
                   6758:             }
                   6759:             $result =~ s/\&$//;
                   6760:             &Reply($client,\$result,$userinput);
                   6761:         } else {
                   6762:             &Reply($client,"error\n", $userinput);
                   6763:         }
                   6764:     } else {
                   6765:         &Failure($client,"unknown_cmd\n",$userinput);
                   6766:     }
                   6767: }
                   6768: &register_handler("instidrules",\&get_institutional_id_rules,0,1,0);
                   6769: 
1.397     raeburn  6770: sub get_institutional_selfcreate_rules {
1.396     raeburn  6771:     my ($cmd, $tail, $client)   = @_;
                   6772:     my $userinput               = "$cmd:$tail";
                   6773:     my $dom = &unescape($tail);
                   6774:     my (%rules_hash,@rules_order);
                   6775:     my $outcome;
                   6776:     eval {
                   6777:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  6778:         $outcome = &localenroll::selfcreate_rules($dom,\%rules_hash,\@rules_order);
1.396     raeburn  6779:     };
                   6780:     if (!$@) {
                   6781:         if ($outcome eq 'ok') {
                   6782:             my $result;
                   6783:             foreach my $key (keys(%rules_hash)) {
                   6784:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6785:             }
                   6786:             $result =~ s/\&$//;
                   6787:             $result .= ':';
                   6788:             if (@rules_order > 0) {
                   6789:                 foreach my $item (@rules_order) {
                   6790:                     $result .= &escape($item).'&';
                   6791:                 }
                   6792:             }
                   6793:             $result =~ s/\&$//;
                   6794:             &Reply($client,\$result,$userinput);
                   6795:         } else {
                   6796:             &Reply($client,"error\n", $userinput);
                   6797:         }
                   6798:     } else {
                   6799:         &Failure($client,"unknown_cmd\n",$userinput);
                   6800:     }
                   6801: }
1.397     raeburn  6802: &register_handler("instemailrules",\&get_institutional_selfcreate_rules,0,1,0);
1.396     raeburn  6803: 
1.381     raeburn  6804: 
                   6805: sub institutional_username_check {
                   6806:     my ($cmd, $tail, $client)   = @_;
                   6807:     my $userinput               = "$cmd:$tail";
                   6808:     my %rulecheck;
                   6809:     my $outcome;
                   6810:     my ($udom,$uname,@rules) = split(/:/,$tail);
                   6811:     $udom = &unescape($udom);
                   6812:     $uname = &unescape($uname);
                   6813:     @rules = map {&unescape($_);} (@rules);
                   6814:     eval {
                   6815:         local($SIG{__DIE__})='DEFAULT';
                   6816:         $outcome = &localenroll::username_check($udom,$uname,\@rules,\%rulecheck);
                   6817:     };
                   6818:     if (!$@) {
                   6819:         if ($outcome eq 'ok') {
                   6820:             my $result='';
                   6821:             foreach my $key (keys(%rulecheck)) {
                   6822:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6823:             }
1.387     albertel 6824:             &Reply($client,\$result,$userinput);
1.381     raeburn  6825:         } else {
                   6826:             &Reply($client,"error\n", $userinput);
                   6827:         }
                   6828:     } else {
                   6829:         &Failure($client,"unknown_cmd\n",$userinput);
                   6830:     }
                   6831: }
                   6832: &register_handler("instrulecheck",\&institutional_username_check,0,1,0);
                   6833: 
1.389     raeburn  6834: sub institutional_id_check {
                   6835:     my ($cmd, $tail, $client)   = @_;
                   6836:     my $userinput               = "$cmd:$tail";
                   6837:     my %rulecheck;
                   6838:     my $outcome;
                   6839:     my ($udom,$id,@rules) = split(/:/,$tail);
                   6840:     $udom = &unescape($udom);
                   6841:     $id = &unescape($id);
                   6842:     @rules = map {&unescape($_);} (@rules);
                   6843:     eval {
                   6844:         local($SIG{__DIE__})='DEFAULT';
                   6845:         $outcome = &localenroll::id_check($udom,$id,\@rules,\%rulecheck);
                   6846:     };
                   6847:     if (!$@) {
                   6848:         if ($outcome eq 'ok') {
                   6849:             my $result='';
                   6850:             foreach my $key (keys(%rulecheck)) {
                   6851:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6852:             }
                   6853:             &Reply($client,\$result,$userinput);
                   6854:         } else {
                   6855:             &Reply($client,"error\n", $userinput);
                   6856:         }
                   6857:     } else {
                   6858:         &Failure($client,"unknown_cmd\n",$userinput);
                   6859:     }
                   6860: }
                   6861: &register_handler("instidrulecheck",\&institutional_id_check,0,1,0);
1.345     raeburn  6862: 
1.397     raeburn  6863: sub institutional_selfcreate_check {
1.396     raeburn  6864:     my ($cmd, $tail, $client)   = @_;
                   6865:     my $userinput               = "$cmd:$tail";
                   6866:     my %rulecheck;
                   6867:     my $outcome;
                   6868:     my ($udom,$email,@rules) = split(/:/,$tail);
                   6869:     $udom = &unescape($udom);
                   6870:     $email = &unescape($email);
                   6871:     @rules = map {&unescape($_);} (@rules);
                   6872:     eval {
                   6873:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  6874:         $outcome = &localenroll::selfcreate_check($udom,$email,\@rules,\%rulecheck);
1.396     raeburn  6875:     };
                   6876:     if (!$@) {
                   6877:         if ($outcome eq 'ok') {
                   6878:             my $result='';
                   6879:             foreach my $key (keys(%rulecheck)) {
                   6880:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6881:             }
                   6882:             &Reply($client,\$result,$userinput);
                   6883:         } else {
                   6884:             &Reply($client,"error\n", $userinput);
                   6885:         }
                   6886:     } else {
                   6887:         &Failure($client,"unknown_cmd\n",$userinput);
                   6888:     }
                   6889: }
1.397     raeburn  6890: &register_handler("instselfcreatecheck",\&institutional_selfcreate_check,0,1,0);
1.396     raeburn  6891: 
1.317     raeburn  6892: # Get domain specific conditions for import of student photographs to a course
                   6893: #
                   6894: # Retrieves information from photo_permission subroutine in localenroll.
                   6895: # Returns outcome (ok) if no processing errors, and whether course owner is 
                   6896: # required to accept conditions of use (yes/no).
                   6897: #
                   6898: #    
                   6899: sub photo_permission_handler {
                   6900:     my ($cmd, $tail, $client)   = @_;
                   6901:     my $userinput               = "$cmd:$tail";
                   6902:     my $cdom = $tail;
                   6903:     my ($perm_reqd,$conditions);
1.320     albertel 6904:     my $outcome;
                   6905:     eval {
                   6906: 	local($SIG{__DIE__})='DEFAULT';
                   6907: 	$outcome = &localenroll::photo_permission($cdom,\$perm_reqd,
                   6908: 						  \$conditions);
                   6909:     };
                   6910:     if (!$@) {
                   6911: 	&Reply($client, &escape($outcome.':'.$perm_reqd.':'. $conditions)."\n",
                   6912: 	       $userinput);
                   6913:     } else {
                   6914: 	&Failure($client,"unknown_cmd\n",$userinput);
                   6915:     }
                   6916:     return 1;
1.317     raeburn  6917: }
                   6918: &register_handler("autophotopermission",\&photo_permission_handler,0,1,0);
                   6919: 
                   6920: #
                   6921: # Checks if student photo is available for a user in the domain, in the user's
                   6922: # directory (in /userfiles/internal/studentphoto.jpg).
                   6923: # Uses localstudentphoto:fetch() to ensure there is an up to date copy of
                   6924: # the student's photo.   
                   6925: 
                   6926: sub photo_check_handler {
                   6927:     my ($cmd, $tail, $client)   = @_;
                   6928:     my $userinput               = "$cmd:$tail";
                   6929:     my ($udom,$uname,$pid) = split(/:/,$tail);
                   6930:     $udom = &unescape($udom);
                   6931:     $uname = &unescape($uname);
                   6932:     $pid = &unescape($pid);
                   6933:     my $path=&propath($udom,$uname).'/userfiles/internal/';
                   6934:     if (!-e $path) {
                   6935:         &mkpath($path);
                   6936:     }
                   6937:     my $response;
                   6938:     my $result = &localstudentphoto::fetch($udom,$uname,$pid,\$response);
                   6939:     $result .= ':'.$response;
                   6940:     &Reply($client, &escape($result)."\n",$userinput);
1.320     albertel 6941:     return 1;
1.317     raeburn  6942: }
                   6943: &register_handler("autophotocheck",\&photo_check_handler,0,1,0);
                   6944: 
                   6945: #
                   6946: # Retrieve information from localenroll about whether to provide a button     
                   6947: # for users who have enbled import of student photos to initiate an 
                   6948: # update of photo files for registered students. Also include 
                   6949: # comment to display alongside button.  
                   6950: 
                   6951: sub photo_choice_handler {
                   6952:     my ($cmd, $tail, $client) = @_;
                   6953:     my $userinput             = "$cmd:$tail";
                   6954:     my $cdom                  = &unescape($tail);
1.320     albertel 6955:     my ($update,$comment);
                   6956:     eval {
                   6957: 	local($SIG{__DIE__})='DEFAULT';
                   6958: 	($update,$comment)    = &localenroll::manager_photo_update($cdom);
                   6959:     };
                   6960:     if (!$@) {
                   6961: 	&Reply($client,&escape($update).':'.&escape($comment)."\n",$userinput);
                   6962:     } else {
                   6963: 	&Failure($client,"unknown_cmd\n",$userinput);
                   6964:     }
                   6965:     return 1;
1.317     raeburn  6966: }
                   6967: &register_handler("autophotochoice",\&photo_choice_handler,0,1,0);
                   6968: 
1.265     albertel 6969: #
                   6970: # Gets a student's photo to exist (in the correct image type) in the user's 
                   6971: # directory.
                   6972: # Formal Parameters:
                   6973: #    $cmd     - The command request that got us dispatched.
                   6974: #    $tail    - A colon separated set of words that will be split into:
                   6975: #               $domain - student's domain
                   6976: #               $uname  - student username
                   6977: #               $type   - image type desired
                   6978: #    $client  - The socket open on the client.
                   6979: # Returns:
                   6980: #    1 - continue processing.
1.317     raeburn  6981: 
1.265     albertel 6982: sub student_photo_handler {
                   6983:     my ($cmd, $tail, $client) = @_;
1.317     raeburn  6984:     my ($domain,$uname,$ext,$type) = split(/:/, $tail);
1.265     albertel 6985: 
1.317     raeburn  6986:     my $path=&propath($domain,$uname). '/userfiles/internal/';
                   6987:     my $filename = 'studentphoto.'.$ext;
                   6988:     if ($type eq 'thumbnail') {
                   6989:         $filename = 'studentphoto_tn.'.$ext;
                   6990:     }
                   6991:     if (-e $path.$filename) {
1.265     albertel 6992: 	&Reply($client,"ok\n","$cmd:$tail");
                   6993: 	return 1;
                   6994:     }
                   6995:     &mkpath($path);
1.317     raeburn  6996:     my $file;
                   6997:     if ($type eq 'thumbnail') {
1.320     albertel 6998: 	eval {
                   6999: 	    local($SIG{__DIE__})='DEFAULT';
                   7000: 	    $file=&localstudentphoto::fetch_thumbnail($domain,$uname);
                   7001: 	};
1.317     raeburn  7002:     } else {
                   7003:         $file=&localstudentphoto::fetch($domain,$uname);
                   7004:     }
1.265     albertel 7005:     if (!$file) {
                   7006: 	&Failure($client,"unavailable\n","$cmd:$tail");
                   7007: 	return 1;
                   7008:     }
1.317     raeburn  7009:     if (!-e $path.$filename) { &convert_photo($file,$path.$filename); }
                   7010:     if (-e $path.$filename) {
1.265     albertel 7011: 	&Reply($client,"ok\n","$cmd:$tail");
                   7012: 	return 1;
                   7013:     }
                   7014:     &Failure($client,"unable_to_convert\n","$cmd:$tail");
                   7015:     return 1;
                   7016: }
                   7017: &register_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
1.246     foxr     7018: 
1.361     raeburn  7019: sub inst_usertypes_handler {
                   7020:     my ($cmd, $domain, $client) = @_;
                   7021:     my $res;
                   7022:     my $userinput = $cmd.":".$domain; # For logging purposes.
1.370     albertel 7023:     my (%typeshash,@order,$result);
                   7024:     eval {
                   7025: 	local($SIG{__DIE__})='DEFAULT';
                   7026: 	$result=&localenroll::inst_usertypes($domain,\%typeshash,\@order);
                   7027:     };
                   7028:     if ($result eq 'ok') {
1.361     raeburn  7029:         if (keys(%typeshash) > 0) {
                   7030:             foreach my $key (keys(%typeshash)) {
                   7031:                 $res.=&escape($key).'='.&escape($typeshash{$key}).'&';
                   7032:             }
                   7033:         }
                   7034:         $res=~s/\&$//;
                   7035:         $res .= ':';
                   7036:         if (@order > 0) {
                   7037:             foreach my $item (@order) {
                   7038:                 $res .= &escape($item).'&';
                   7039:             }
                   7040:         }
                   7041:         $res=~s/\&$//;
                   7042:     }
1.387     albertel 7043:     &Reply($client, \$res, $userinput);
1.361     raeburn  7044:     return 1;
                   7045: }
                   7046: &register_handler("inst_usertypes", \&inst_usertypes_handler, 0, 1, 0);
                   7047: 
1.264     albertel 7048: # mkpath makes all directories for a file, expects an absolute path with a
                   7049: # file or a trailing / if just a dir is passed
                   7050: # returns 1 on success 0 on failure
                   7051: sub mkpath {
                   7052:     my ($file)=@_;
                   7053:     my @parts=split(/\//,$file,-1);
                   7054:     my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
                   7055:     for (my $i=3;$i<= ($#parts-1);$i++) {
1.265     albertel 7056: 	$now.='/'.$parts[$i]; 
1.264     albertel 7057: 	if (!-e $now) {
                   7058: 	    if  (!mkdir($now,0770)) { return 0; }
                   7059: 	}
                   7060:     }
                   7061:     return 1;
                   7062: }
                   7063: 
1.207     foxr     7064: #---------------------------------------------------------------
                   7065: #
                   7066: #   Getting, decoding and dispatching requests:
                   7067: #
                   7068: #
                   7069: #   Get a Request:
                   7070: #   Gets a Request message from the client.  The transaction
                   7071: #   is defined as a 'line' of text.  We remove the new line
                   7072: #   from the text line.  
1.226     foxr     7073: #
1.211     albertel 7074: sub get_request {
1.207     foxr     7075:     my $input = <$client>;
                   7076:     chomp($input);
1.226     foxr     7077: 
1.234     foxr     7078:     &Debug("get_request: Request = $input\n");
1.207     foxr     7079: 
                   7080:     &status('Processing '.$clientname.':'.$input);
                   7081: 
                   7082:     return $input;
                   7083: }
1.212     foxr     7084: #---------------------------------------------------------------
                   7085: #
                   7086: #  Process a request.  This sub should shrink as each action
                   7087: #  gets farmed out into a separat sub that is registered 
                   7088: #  with the dispatch hash.  
                   7089: #
                   7090: # Parameters:
                   7091: #    user_input   - The request received from the client (lonc).
1.525     raeburn  7092: #
1.212     foxr     7093: # Returns:
                   7094: #    true to keep processing, false if caller should exit.
                   7095: #
                   7096: sub process_request {
1.525     raeburn  7097:     my ($userinput) = @_; # Easier for now to break style than to
                   7098:                           # fix all the userinput -> user_input.
1.212     foxr     7099:     my $wasenc    = 0;		# True if request was encrypted.
                   7100: # ------------------------------------------------------------ See if encrypted
1.322     albertel 7101:     # for command
                   7102:     # sethost:<server>
                   7103:     # <command>:<args>
                   7104:     #   we just send it to the processor
                   7105:     # for
                   7106:     # sethost:<server>:<command>:<args>
                   7107:     #  we do the implict set host and then do the command
                   7108:     if ($userinput =~ /^sethost:/) {
                   7109: 	(my $cmd,my $newid,$userinput) = split(':',$userinput,3);
                   7110: 	if (defined($userinput)) {
                   7111: 	    &sethost("$cmd:$newid");
                   7112: 	} else {
                   7113: 	    $userinput = "$cmd:$newid";
                   7114: 	}
                   7115:     }
                   7116: 
1.212     foxr     7117:     if ($userinput =~ /^enc/) {
                   7118: 	$userinput = decipher($userinput);
                   7119: 	$wasenc=1;
                   7120: 	if(!$userinput) {	# Cipher not defined.
1.251     foxr     7121: 	    &Failure($client, "error: Encrypted data without negotated key\n");
1.212     foxr     7122: 	    return 0;
                   7123: 	}
                   7124:     }
                   7125:     Debug("process_request: $userinput\n");
                   7126:     
1.213     foxr     7127:     #  
                   7128:     #   The 'correct way' to add a command to lond is now to
                   7129:     #   write a sub to execute it and Add it to the command dispatch
                   7130:     #   hash via a call to register_handler..  The comments to that
                   7131:     #   sub should give you enough to go on to show how to do this
                   7132:     #   along with the examples that are building up as this code
                   7133:     #   is getting refactored.   Until all branches of the
                   7134:     #   if/elseif monster below have been factored out into
                   7135:     #   separate procesor subs, if the dispatch hash is missing
                   7136:     #   the command keyword, we will fall through to the remainder
                   7137:     #   of the if/else chain below in order to keep this thing in 
                   7138:     #   working order throughout the transmogrification.
                   7139: 
                   7140:     my ($command, $tail) = split(/:/, $userinput, 2);
                   7141:     chomp($command);
                   7142:     chomp($tail);
                   7143:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
1.214     foxr     7144:     $command =~ s/(\r)//;	# And this too for parameterless commands.
                   7145:     if(!$tail) {
                   7146: 	$tail ="";		# defined but blank.
                   7147:     }
1.213     foxr     7148: 
                   7149:     &Debug("Command received: $command, encoded = $wasenc");
                   7150: 
                   7151:     if(defined $Dispatcher{$command}) {
                   7152: 
                   7153: 	my $dispatch_info = $Dispatcher{$command};
                   7154: 	my $handler       = $$dispatch_info[0];
                   7155: 	my $need_encode   = $$dispatch_info[1];
                   7156: 	my $client_types  = $$dispatch_info[2];
                   7157: 	Debug("Matched dispatch hash: mustencode: $need_encode "
                   7158: 	      ."ClientType $client_types");
                   7159:       
                   7160: 	#  Validate the request:
                   7161:       
                   7162: 	my $ok = 1;
                   7163: 	my $requesterprivs = 0;
                   7164: 	if(&isClient()) {
                   7165: 	    $requesterprivs |= $CLIENT_OK;
                   7166: 	}
                   7167: 	if(&isManager()) {
                   7168: 	    $requesterprivs |= $MANAGER_OK;
                   7169: 	}
                   7170: 	if($need_encode && (!$wasenc)) {
                   7171: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
                   7172: 	    $ok = 0;
                   7173: 	}
                   7174: 	if(($client_types & $requesterprivs) == 0) {
                   7175: 	    Debug("Client not privileged to do this operation");
                   7176: 	    $ok = 0;
                   7177: 	}
1.525     raeburn  7178:         if ($ok) {
1.535     raeburn  7179:             my $realcommand = $command;
                   7180:             if ($command eq 'querysend') {
                   7181:                 my ($query,$rest)=split(/\:/,$tail,2);
                   7182:                 $query=~s/\n*$//g;
                   7183:                 my @possqueries = 
                   7184:                     qw(userlog courselog fetchenrollment institutionalphotos usersearch instdirsearch getinstuser getmultinstusers);
                   7185:                 if (grep(/^\Q$query\E$/,@possqueries)) {
                   7186:                     $command .= '_'.$query;
                   7187:                 } elsif ($query eq 'prepare activity log') {
                   7188:                     $command .= '_activitylog';
                   7189:                 }
                   7190:             }
1.525     raeburn  7191:             if (ref($trust{$command}) eq 'HASH') {
                   7192:                 my $donechecks;
                   7193:                 if ($trust{$command}{'anywhere'}) {
                   7194:                    $donechecks = 1;
                   7195:                 } elsif ($trust{$command}{'manageronly'}) {
                   7196:                     unless (&isManager()) {
                   7197:                         $ok = 0;
                   7198:                     }
                   7199:                     $donechecks = 1;
                   7200:                 } elsif ($trust{$command}{'institutiononly'}) {
                   7201:                     unless ($clientsameinst) {
                   7202:                         $ok = 0;
                   7203:                     }
                   7204:                     $donechecks = 1;
                   7205:                 } elsif ($clientsameinst) {
                   7206:                     $donechecks = 1;
                   7207:                 }
                   7208:                 unless ($donechecks) {
                   7209:                     foreach my $rule (keys(%{$trust{$command}})) {
                   7210:                         next if ($rule eq 'remote');
                   7211:                         if ($trust{$command}{$rule}) {
                   7212:                             if ($clientprohibited{$rule}) {
                   7213:                                 $ok = 0;
                   7214:                             } else {
                   7215:                                 $ok = 1;
                   7216:                                 $donechecks = 1;
                   7217:                                 last;
                   7218:                             }
                   7219:                         }
                   7220:                     }
                   7221:                 }
                   7222:                 unless ($donechecks) {
                   7223:                     if ($trust{$command}{'remote'}) {
                   7224:                         if ($clientremoteok) {
                   7225:                             $ok = 1;
                   7226:                         } else {
                   7227:                             $ok = 0;
                   7228:                         } 
                   7229:                     }
                   7230:                 }
                   7231:             }
1.535     raeburn  7232:             $command = $realcommand;
1.525     raeburn  7233:         }
1.213     foxr     7234: 
                   7235: 	if($ok) {
                   7236: 	    Debug("Dispatching to handler $command $tail");
                   7237: 	    my $keep_going = &$handler($command, $tail, $client);
                   7238: 	    return $keep_going;
                   7239: 	} else {
                   7240: 	    Debug("Refusing to dispatch because client did not match requirements");
                   7241: 	    Failure($client, "refused\n", $userinput);
                   7242: 	    return 1;
                   7243: 	}
1.525     raeburn  7244:     }
1.213     foxr     7245: 
1.262     foxr     7246:     print $client "unknown_cmd\n";
1.212     foxr     7247: # -------------------------------------------------------------------- complete
                   7248:     Debug("process_request - returning 1");
                   7249:     return 1;
                   7250: }
1.207     foxr     7251: #
                   7252: #   Decipher encoded traffic
                   7253: #  Parameters:
                   7254: #     input      - Encoded data.
                   7255: #  Returns:
                   7256: #     Decoded data or undef if encryption key was not yet negotiated.
                   7257: #  Implicit input:
                   7258: #     cipher  - This global holds the negotiated encryption key.
                   7259: #
1.211     albertel 7260: sub decipher {
1.207     foxr     7261:     my ($input)  = @_;
                   7262:     my $output = '';
1.212     foxr     7263:     
                   7264:     
1.207     foxr     7265:     if($cipher) {
                   7266: 	my($enc, $enclength, $encinput) = split(/:/, $input);
                   7267: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
                   7268: 	    $output .= 
                   7269: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
                   7270: 	}
                   7271: 	return substr($output, 0, $enclength);
                   7272:     } else {
                   7273: 	return undef;
                   7274:     }
                   7275: }
                   7276: 
                   7277: #
                   7278: #   Register a command processor.  This function is invoked to register a sub
                   7279: #   to process a request.  Once registered, the ProcessRequest sub can automatically
                   7280: #   dispatch requests to an appropriate sub, and do the top level validity checking
                   7281: #   as well:
                   7282: #    - Is the keyword recognized.
                   7283: #    - Is the proper client type attempting the request.
                   7284: #    - Is the request encrypted if it has to be.
                   7285: #   Parameters:
                   7286: #    $request_name         - Name of the request being registered.
                   7287: #                           This is the command request that will match
                   7288: #                           against the hash keywords to lookup the information
                   7289: #                           associated with the dispatch information.
                   7290: #    $procedure           - Reference to a sub to call to process the request.
                   7291: #                           All subs get called as follows:
                   7292: #                             Procedure($cmd, $tail, $replyfd, $key)
                   7293: #                             $cmd    - the actual keyword that invoked us.
                   7294: #                             $tail   - the tail of the request that invoked us.
                   7295: #                             $replyfd- File descriptor connected to the client
                   7296: #    $must_encode          - True if the request must be encoded to be good.
                   7297: #    $client_ok            - True if it's ok for a client to request this.
                   7298: #    $manager_ok           - True if it's ok for a manager to request this.
                   7299: # Side effects:
                   7300: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
                   7301: #      - On failure, the program will die as it's a bad internal bug to try to 
                   7302: #        register a duplicate command handler.
                   7303: #
1.211     albertel 7304: sub register_handler {
1.212     foxr     7305:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
1.207     foxr     7306: 
                   7307:     #  Don't allow duplication#
                   7308:    
                   7309:     if (defined $Dispatcher{$request_name}) {
                   7310: 	die "Attempting to define a duplicate request handler for $request_name\n";
                   7311:     }
                   7312:     #   Build the client type mask:
                   7313:     
                   7314:     my $client_type_mask = 0;
                   7315:     if($client_ok) {
                   7316: 	$client_type_mask  |= $CLIENT_OK;
                   7317:     }
                   7318:     if($manager_ok) {
                   7319: 	$client_type_mask  |= $MANAGER_OK;
                   7320:     }
                   7321:    
                   7322:     #  Enter the hash:
                   7323:       
                   7324:     my @entry = ($procedure, $must_encode, $client_type_mask);
                   7325:    
                   7326:     $Dispatcher{$request_name} = \@entry;
                   7327:    
                   7328: }
                   7329: 
                   7330: 
                   7331: #------------------------------------------------------------------
                   7332: 
                   7333: 
                   7334: 
                   7335: 
1.141     foxr     7336: #
1.96      foxr     7337: #  Convert an error return code from lcpasswd to a string value.
                   7338: #
                   7339: sub lcpasswdstrerror {
                   7340:     my $ErrorCode = shift;
1.97      foxr     7341:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96      foxr     7342: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
                   7343:     } else {
1.98      foxr     7344: 	return $passwderrors[$ErrorCode];
1.96      foxr     7345:     }
                   7346: }
                   7347: 
1.23      harris41 7348: # grabs exception and records it to log before exiting
                   7349: sub catchexception {
1.27      albertel 7350:     my ($error)=@_;
1.25      www      7351:     $SIG{'QUIT'}='DEFAULT';
                   7352:     $SIG{__DIE__}='DEFAULT';
1.165     albertel 7353:     &status("Catching exception");
1.190     albertel 7354:     &logthis("<font color='red'>CRITICAL: "
1.373     albertel 7355:      ."ABNORMAL EXIT. Child $$ for server ".$perlvar{'lonHostID'}." died through "
1.27      albertel 7356:      ."a crash with this error msg->[$error]</font>");
1.57      www      7357:     &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27      albertel 7358:     if ($client) { print $client "error: $error\n"; }
1.59      www      7359:     $server->close();
1.27      albertel 7360:     die($error);
1.23      harris41 7361: }
1.63      www      7362: sub timeout {
1.165     albertel 7363:     &status("Handling Timeout");
1.190     albertel 7364:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
1.63      www      7365:     &catchexception('Timeout');
                   7366: }
1.22      harris41 7367: # -------------------------------- Set signal handlers to record abnormal exits
                   7368: 
1.226     foxr     7369: 
1.22      harris41 7370: $SIG{'QUIT'}=\&catchexception;
                   7371: $SIG{__DIE__}=\&catchexception;
                   7372: 
1.81      matthew  7373: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95      harris41 7374: &status("Read loncapa.conf and loncapa_apache.conf");
                   7375: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141     foxr     7376: %perlvar=%{$perlvarref};
1.80      harris41 7377: undef $perlvarref;
1.19      www      7378: 
1.35      harris41 7379: # ----------------------------- Make sure this process is running from user=www
                   7380: my $wwwid=getpwnam('www');
                   7381: if ($wwwid!=$<) {
1.134     albertel 7382:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   7383:    my $subj="LON: $currenthostid User ID mismatch";
1.550     raeburn  7384:    system("echo 'User ID mismatch.  lond must be run as user www.' |".
                   7385:           " mail -s '$subj' $emailto > /dev/null");
1.35      harris41 7386:    exit 1;
                   7387: }
                   7388: 
1.19      www      7389: # --------------------------------------------- Check if other instance running
                   7390: 
                   7391: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
                   7392: 
                   7393: if (-e $pidfile) {
                   7394:    my $lfh=IO::File->new("$pidfile");
                   7395:    my $pide=<$lfh>;
                   7396:    chomp($pide);
1.29      harris41 7397:    if (kill 0 => $pide) { die "already running"; }
1.19      www      7398: }
1.1       albertel 7399: 
                   7400: # ------------------------------------------------------------- Read hosts file
                   7401: 
                   7402: 
                   7403: 
                   7404: # establish SERVER socket, bind and listen.
                   7405: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
                   7406:                                 Type      => SOCK_STREAM,
                   7407:                                 Proto     => 'tcp',
1.469     foxr     7408:                                 ReuseAddr     => 1,
1.1       albertel 7409:                                 Listen    => 10 )
1.29      harris41 7410:   or die "making socket: $@\n";
1.1       albertel 7411: 
                   7412: # --------------------------------------------------------- Do global variables
                   7413: 
                   7414: # global variables
                   7415: 
1.134     albertel 7416: my %children               = ();       # keys are current child process IDs
1.1       albertel 7417: 
                   7418: sub REAPER {                        # takes care of dead children
                   7419:     $SIG{CHLD} = \&REAPER;
1.165     albertel 7420:     &status("Handling child death");
1.178     foxr     7421:     my $pid;
                   7422:     do {
                   7423: 	$pid = waitpid(-1,&WNOHANG());
                   7424: 	if (defined($children{$pid})) {
                   7425: 	    &logthis("Child $pid died");
                   7426: 	    delete($children{$pid});
1.183     albertel 7427: 	} elsif ($pid > 0) {
1.178     foxr     7428: 	    &logthis("Unknown Child $pid died");
                   7429: 	}
                   7430:     } while ( $pid > 0 );
                   7431:     foreach my $child (keys(%children)) {
                   7432: 	$pid = waitpid($child,&WNOHANG());
                   7433: 	if ($pid > 0) {
                   7434: 	    &logthis("Child $child - $pid looks like we missed it's death");
                   7435: 	    delete($children{$pid});
                   7436: 	}
1.176     albertel 7437:     }
1.165     albertel 7438:     &status("Finished Handling child death");
1.1       albertel 7439: }
                   7440: 
                   7441: sub HUNTSMAN {                      # signal handler for SIGINT
1.165     albertel 7442:     &status("Killing children (INT)");
1.1       albertel 7443:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
                   7444:     kill 'INT' => keys %children;
1.59      www      7445:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1       albertel 7446:     my $execdir=$perlvar{'lonDaemons'};
                   7447:     unlink("$execdir/logs/lond.pid");
1.190     albertel 7448:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.165     albertel 7449:     &status("Done killing children");
1.1       albertel 7450:     exit;                           # clean up with dignity
                   7451: }
                   7452: 
                   7453: sub HUPSMAN {                      # signal handler for SIGHUP
                   7454:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
1.165     albertel 7455:     &status("Killing children for restart (HUP)");
1.1       albertel 7456:     kill 'INT' => keys %children;
1.59      www      7457:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.190     albertel 7458:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.134     albertel 7459:     my $execdir=$perlvar{'lonDaemons'};
1.30      harris41 7460:     unlink("$execdir/logs/lond.pid");
1.165     albertel 7461:     &status("Restarting self (HUP)");
1.1       albertel 7462:     exec("$execdir/lond");         # here we go again
                   7463: }
                   7464: 
1.144     foxr     7465: #
1.148     foxr     7466: #  Reload the Apache daemon's state.
1.150     foxr     7467: #  This is done by invoking /home/httpd/perl/apachereload
                   7468: #  a setuid perl script that can be root for us to do this job.
1.148     foxr     7469: #
                   7470: sub ReloadApache {
1.473     raeburn  7471: # --------------------------- Handle case of another apachereload process (locking)
1.474     raeburn  7472:     if (&LONCAPA::try_to_lock('/tmp/lock_apachereload')) {
                   7473:         my $execdir = $perlvar{'lonDaemons'};
                   7474:         my $script  = $execdir."/apachereload";
                   7475:         system($script);
                   7476:         unlink('/tmp/lock_apachereload'); #  Remove the lock file.
                   7477:     }
1.148     foxr     7478: }
                   7479: 
                   7480: #
1.144     foxr     7481: #   Called in response to a USR2 signal.
                   7482: #   - Reread hosts.tab
                   7483: #   - All children connected to hosts that were removed from hosts.tab
                   7484: #     are killed via SIGINT
                   7485: #   - All children connected to previously existing hosts are sent SIGUSR1
                   7486: #   - Our internal hosts hash is updated to reflect the new contents of
                   7487: #     hosts.tab causing connections from hosts added to hosts.tab to
                   7488: #     now be honored.
                   7489: #
                   7490: sub UpdateHosts {
1.165     albertel 7491:     &status("Reload hosts.tab");
1.147     foxr     7492:     logthis('<font color="blue"> Updating connections </font>');
1.148     foxr     7493:     #
                   7494:     #  The %children hash has the set of IP's we currently have children
                   7495:     #  on.  These need to be matched against records in the hosts.tab
                   7496:     #  Any ip's no longer in the table get killed off they correspond to
                   7497:     #  either dropped or changed hosts.  Note that the re-read of the table
                   7498:     #  will take care of new and changed hosts as connections come into being.
                   7499: 
1.371     albertel 7500:     &Apache::lonnet::reset_hosts_info();
1.532     raeburn  7501:     my %active;
1.148     foxr     7502: 
1.368     albertel 7503:     foreach my $child (keys(%children)) {
1.148     foxr     7504: 	my $childip = $children{$child};
1.374     albertel 7505: 	if ($childip ne '127.0.0.1'
                   7506: 	    && !defined(&Apache::lonnet::get_hosts_from_ip($childip))) {
1.149     foxr     7507: 	    logthis('<font color="blue"> UpdateHosts killing child '
                   7508: 		    ." $child for ip $childip </font>");
1.148     foxr     7509: 	    kill('INT', $child);
1.149     foxr     7510: 	} else {
1.532     raeburn  7511:             $active{$child} = $childip;
1.149     foxr     7512: 	    logthis('<font color="green"> keeping child for ip '
                   7513: 		    ." $childip (pid=$child) </font>");
1.148     foxr     7514: 	}
                   7515:     }
1.532     raeburn  7516: 
                   7517:     my %oldconf = %secureconf;
                   7518:     my %connchange;
1.555     raeburn  7519:     if (lonssl::Read_Connect_Config(\%secureconf,\%perlvar,\%crlchecked) eq 'ok') {
1.545     raeburn  7520:         logthis('<font color="blue"> Reloaded SSL connection rules and cleared CRL checking history </font>');
1.532     raeburn  7521:     } else {
1.545     raeburn  7522:         logthis('<font color="yellow"> Failed to reload SSL connection rules and clear CRL checking history </font>');
1.532     raeburn  7523:     }
                   7524:     if ((ref($oldconf{'connfrom'}) eq 'HASH') && (ref($secureconf{'connfrom'}) eq 'HASH')) {
                   7525:         foreach my $type ('dom','intdom','other') {
                   7526:             if ((($oldconf{'connfrom'}{$type} eq 'no') && ($secureconf{'connfrom'}{$type} eq 'req')) ||
                   7527:                 (($oldconf{'connfrom'}{$type} eq 'req') && ($secureconf{'connfrom'}{$type} eq 'no'))) {
                   7528:                 $connchange{$type} = 1;
                   7529:             }
                   7530:         }
                   7531:     }
                   7532:     if (keys(%connchange)) {
                   7533:         foreach my $child (keys(%active)) {
                   7534:             my $childip = $active{$child};
                   7535:             if ($childip ne '127.0.0.1') {
                   7536:                 my $childhostname  = gethostbyaddr(Socket::inet_aton($childip),AF_INET);
                   7537:                 if ($childhostname ne '') {
                   7538:                     my $childlonhost = &Apache::lonnet::get_server_homeID($childhostname);
                   7539:                     my ($samedom,$sameinst) = &set_client_info($childlonhost);
                   7540:                     if ($samedom) {
                   7541:                         if ($connchange{'dom'}) {
                   7542:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7543:                                    ." $child for ip $childip </font>");
                   7544:                             kill('INT', $child);
                   7545:                         }
                   7546:                     } elsif ($sameinst) {
                   7547:                         if ($connchange{'intdom'}) {
                   7548:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7549:                                    ." $child for ip $childip </font>");
                   7550:                            kill('INT', $child);
                   7551:                         }
                   7552:                     } else {
                   7553:                         if ($connchange{'other'}) {
                   7554:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7555:                                    ." $child for ip $childip </font>");
                   7556:                             kill('INT', $child);
                   7557:                         }
                   7558:                     }
                   7559:                 }
                   7560:             }
                   7561:         }
                   7562:     }
1.148     foxr     7563:     ReloadApache;
1.165     albertel 7564:     &status("Finished reloading hosts.tab");
1.144     foxr     7565: }
                   7566: 
1.57      www      7567: sub checkchildren {
1.165     albertel 7568:     &status("Checking on the children (sending signals)");
1.57      www      7569:     &initnewstatus();
                   7570:     &logstatus();
                   7571:     &logthis('Going to check on the children');
1.134     albertel 7572:     my $docdir=$perlvar{'lonDocRoot'};
1.61      harris41 7573:     foreach (sort keys %children) {
1.221     albertel 7574: 	#sleep 1;
1.57      www      7575:         unless (kill 'USR1' => $_) {
                   7576: 	    &logthis ('Child '.$_.' is dead');
                   7577:             &logstatus($$.' is dead');
1.221     albertel 7578: 	    delete($children{$_});
1.57      www      7579:         } 
1.61      harris41 7580:     }
1.63      www      7581:     sleep 5;
1.212     foxr     7582:     $SIG{ALRM} = sub { Debug("timeout"); 
                   7583: 		       die "timeout";  };
1.113     albertel 7584:     $SIG{__DIE__} = 'DEFAULT';
1.165     albertel 7585:     &status("Checking on the children (waiting for reports)");
1.63      www      7586:     foreach (sort keys %children) {
                   7587:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113     albertel 7588:           eval {
                   7589:             alarm(300);
1.63      www      7590: 	    &logthis('Child '.$_.' did not respond');
1.67      albertel 7591: 	    kill 9 => $_;
1.131     albertel 7592: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   7593: 	    #$subj="LON: $currenthostid killed lond process $_";
                   7594: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
                   7595: 	    #$execdir=$perlvar{'lonDaemons'};
                   7596: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.221     albertel 7597: 	    delete($children{$_});
1.113     albertel 7598: 	    alarm(0);
                   7599: 	  }
1.63      www      7600:         }
                   7601:     }
1.113     albertel 7602:     $SIG{ALRM} = 'DEFAULT';
1.155     albertel 7603:     $SIG{__DIE__} = \&catchexception;
1.165     albertel 7604:     &status("Finished checking children");
1.221     albertel 7605:     &logthis('Finished Checking children');
1.57      www      7606: }
                   7607: 
1.1       albertel 7608: # --------------------------------------------------------------------- Logging
                   7609: 
                   7610: sub logthis {
                   7611:     my $message=shift;
                   7612:     my $execdir=$perlvar{'lonDaemons'};
                   7613:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
                   7614:     my $now=time;
                   7615:     my $local=localtime($now);
1.58      www      7616:     $lastlog=$local.': '.$message;
1.1       albertel 7617:     print $fh "$local ($$): $message\n";
                   7618: }
                   7619: 
1.77      foxr     7620: # ------------------------- Conditional log if $DEBUG true.
                   7621: sub Debug {
                   7622:     my $message = shift;
                   7623:     if($DEBUG) {
                   7624: 	&logthis($message);
                   7625:     }
                   7626: }
1.161     foxr     7627: 
                   7628: #
                   7629: #   Sub to do replies to client.. this gives a hook for some
                   7630: #   debug tracing too:
                   7631: #  Parameters:
                   7632: #     fd      - File open on client.
                   7633: #     reply   - Text to send to client.
                   7634: #     request - Original request from client.
                   7635: #
1.490     droeschl 7636: #NOTE $reply must be terminated by exactly *one* \n. If $reply is a reference
                   7637: #this is done automatically ($$reply must not contain any \n in this case). 
                   7638: #If $reply is a string the caller has to ensure this.
1.161     foxr     7639: sub Reply {
1.192     foxr     7640:     my ($fd, $reply, $request) = @_;
1.387     albertel 7641:     if (ref($reply)) {
                   7642: 	print $fd $$reply;
                   7643: 	print $fd "\n";
                   7644: 	if ($DEBUG) { Debug("Request was $request  Reply was $$reply"); }
                   7645:     } else {
                   7646: 	print $fd $reply;
                   7647: 	if ($DEBUG) { Debug("Request was $request  Reply was $reply"); }
                   7648:     }
1.212     foxr     7649:     $Transactions++;
                   7650: }
                   7651: 
                   7652: 
                   7653: #
                   7654: #    Sub to report a failure.
                   7655: #    This function:
                   7656: #     -   Increments the failure statistic counters.
                   7657: #     -   Invokes Reply to send the error message to the client.
                   7658: # Parameters:
                   7659: #    fd       - File descriptor open on the client
                   7660: #    reply    - Reply text to emit.
                   7661: #    request  - The original request message (used by Reply
                   7662: #               to debug if that's enabled.
                   7663: # Implicit outputs:
                   7664: #    $Failures- The number of failures is incremented.
                   7665: #    Reply (invoked here) sends a message to the 
                   7666: #    client:
                   7667: #
                   7668: sub Failure {
                   7669:     my $fd      = shift;
                   7670:     my $reply   = shift;
                   7671:     my $request = shift;
                   7672:    
                   7673:     $Failures++;
                   7674:     Reply($fd, $reply, $request);      # That's simple eh?
1.161     foxr     7675: }
1.57      www      7676: # ------------------------------------------------------------------ Log status
                   7677: 
                   7678: sub logstatus {
1.178     foxr     7679:     &status("Doing logging");
                   7680:     my $docdir=$perlvar{'lonDocRoot'};
                   7681:     {
                   7682: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
1.200     matthew  7683:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
1.178     foxr     7684:         $fh->close();
                   7685:     }
1.221     albertel 7686:     &status("Finished $$.txt");
                   7687:     {
                   7688: 	open(LOG,">>$docdir/lon-status/londstatus.txt");
                   7689: 	flock(LOG,LOCK_EX);
                   7690: 	print LOG $$."\t".$clientname."\t".$currenthostid."\t"
                   7691: 	    .$status."\t".$lastlog."\t $keymode\n";
1.275     albertel 7692: 	flock(LOG,LOCK_UN);
1.221     albertel 7693: 	close(LOG);
                   7694:     }
1.178     foxr     7695:     &status("Finished logging");
1.57      www      7696: }
                   7697: 
                   7698: sub initnewstatus {
                   7699:     my $docdir=$perlvar{'lonDocRoot'};
                   7700:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
1.460     foxr     7701:     my $now=time();
1.57      www      7702:     my $local=localtime($now);
                   7703:     print $fh "LOND status $local - parent $$\n\n";
1.64      www      7704:     opendir(DIR,"$docdir/lon-status/londchld");
1.134     albertel 7705:     while (my $filename=readdir(DIR)) {
1.64      www      7706:         unlink("$docdir/lon-status/londchld/$filename");
                   7707:     }
                   7708:     closedir(DIR);
1.57      www      7709: }
                   7710: 
                   7711: # -------------------------------------------------------------- Status setting
                   7712: 
                   7713: sub status {
                   7714:     my $what=shift;
                   7715:     my $now=time;
                   7716:     my $local=localtime($now);
1.178     foxr     7717:     $status=$local.': '.$what;
                   7718:     $0='lond: '.$what.' '.$local;
1.57      www      7719: }
1.11      www      7720: 
1.13      www      7721: # -------------------------------------------------------------- Talk to lonsql
                   7722: 
1.234     foxr     7723: sub sql_reply {
1.12      harris41 7724:     my ($cmd)=@_;
1.234     foxr     7725:     my $answer=&sub_sql_reply($cmd);
                   7726:     if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
1.12      harris41 7727:     return $answer;
                   7728: }
                   7729: 
1.234     foxr     7730: sub sub_sql_reply {
1.12      harris41 7731:     my ($cmd)=@_;
                   7732:     my $unixsock="mysqlsock";
                   7733:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
                   7734:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                   7735:                                       Type    => SOCK_STREAM,
                   7736:                                       Timeout => 10)
                   7737:        or return "con_lost";
1.319     www      7738:     print $sclient "$cmd:$currentdomainid\n";
1.12      harris41 7739:     my $answer=<$sclient>;
                   7740:     chomp($answer);
                   7741:     if (!$answer) { $answer="con_lost"; }
                   7742:     return $answer;
                   7743: }
                   7744: 
1.1       albertel 7745: # --------------------------------------- Is this the home server of an author?
1.11      www      7746: 
1.1       albertel 7747: sub ishome {
                   7748:     my $author=shift;
                   7749:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   7750:     my ($udom,$uname)=split(/\//,$author);
                   7751:     my $proname=propath($udom,$uname);
                   7752:     if (-e $proname) {
                   7753: 	return 'owner';
                   7754:     } else {
                   7755:         return 'not_owner';
                   7756:     }
                   7757: }
                   7758: 
                   7759: # ======================================================= Continue main program
                   7760: # ---------------------------------------------------- Fork once and dissociate
                   7761: 
1.134     albertel 7762: my $fpid=fork;
1.1       albertel 7763: exit if $fpid;
1.29      harris41 7764: die "Couldn't fork: $!" unless defined ($fpid);
1.1       albertel 7765: 
1.29      harris41 7766: POSIX::setsid() or die "Can't start new session: $!";
1.1       albertel 7767: 
                   7768: # ------------------------------------------------------- Write our PID on disk
                   7769: 
1.134     albertel 7770: my $execdir=$perlvar{'lonDaemons'};
1.1       albertel 7771: open (PIDSAVE,">$execdir/logs/lond.pid");
                   7772: print PIDSAVE "$$\n";
                   7773: close(PIDSAVE);
1.190     albertel 7774: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.57      www      7775: &status('Starting');
1.1       albertel 7776: 
1.106     foxr     7777: 
1.1       albertel 7778: 
                   7779: # ----------------------------------------------------- Install signal handlers
                   7780: 
1.57      www      7781: 
1.1       albertel 7782: $SIG{CHLD} = \&REAPER;
                   7783: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   7784: $SIG{HUP}  = \&HUPSMAN;
1.57      www      7785: $SIG{USR1} = \&checkchildren;
1.144     foxr     7786: $SIG{USR2} = \&UpdateHosts;
1.106     foxr     7787: 
1.148     foxr     7788: #  Read the host hashes:
1.368     albertel 7789: &Apache::lonnet::load_hosts_tab();
1.447     raeburn  7790: my %iphost = &Apache::lonnet::get_iphost(1);
1.106     foxr     7791: 
1.480     raeburn  7792: $dist=`$perlvar{'lonDaemons'}/distprobe`;
1.286     albertel 7793: 
1.471     raeburn  7794: my $arch = `uname -i`;
1.475     raeburn  7795: chomp($arch);
1.471     raeburn  7796: if ($arch eq 'unknown') {
                   7797:     $arch = `uname -m`;
1.475     raeburn  7798:     chomp($arch);
1.471     raeburn  7799: }
                   7800: 
1.555     raeburn  7801: unless (lonssl::Read_Connect_Config(\%secureconf,\%perlvar,\%crlchecked) eq 'ok') {
1.532     raeburn  7802:     &logthis('<font color="blue">No connectionrules table. Will fallback to loncapa.conf</font>');
                   7803: }
                   7804: 
1.106     foxr     7805: # --------------------------------------------------------------
                   7806: #   Accept connections.  When a connection comes in, it is validated
                   7807: #   and if good, a child process is created to process transactions
                   7808: #   along the connection.
                   7809: 
1.1       albertel 7810: while (1) {
1.165     albertel 7811:     &status('Starting accept');
1.106     foxr     7812:     $client = $server->accept() or next;
1.165     albertel 7813:     &status('Accepted '.$client.' off to spawn');
1.386     albertel 7814:     make_new_child($client);
1.165     albertel 7815:     &status('Finished spawning');
1.1       albertel 7816: }
                   7817: 
1.212     foxr     7818: sub make_new_child {
                   7819:     my $pid;
                   7820: #    my $cipher;     # Now global
                   7821:     my $sigset;
1.178     foxr     7822: 
1.212     foxr     7823:     $client = shift;
                   7824:     &status('Starting new child '.$client);
                   7825:     &logthis('<font color="green"> Attempting to start child ('.$client.
                   7826: 	     ")</font>");    
                   7827:     # block signal for fork
                   7828:     $sigset = POSIX::SigSet->new(SIGINT);
                   7829:     sigprocmask(SIG_BLOCK, $sigset)
                   7830:         or die "Can't block SIGINT for fork: $!\n";
1.178     foxr     7831: 
1.212     foxr     7832:     die "fork: $!" unless defined ($pid = fork);
1.178     foxr     7833: 
1.212     foxr     7834:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
                   7835: 	                               # connection liveness.
1.178     foxr     7836: 
1.212     foxr     7837:     #
                   7838:     #  Figure out who we're talking to so we can record the peer in 
                   7839:     #  the pid hash.
                   7840:     #
                   7841:     my $caller = getpeername($client);
                   7842:     my ($port,$iaddr);
                   7843:     if (defined($caller) && length($caller) > 0) {
                   7844: 	($port,$iaddr)=unpack_sockaddr_in($caller);
                   7845:     } else {
                   7846: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
                   7847:     }
                   7848:     if (defined($iaddr)) {
                   7849: 	$clientip  = inet_ntoa($iaddr);
                   7850: 	Debug("Connected with $clientip");
                   7851:     } else {
                   7852: 	&logthis("Unable to determine clientip");
                   7853: 	$clientip='Unavailable';
                   7854:     }
                   7855:     
                   7856:     if ($pid) {
                   7857:         # Parent records the child's birth and returns.
                   7858:         sigprocmask(SIG_UNBLOCK, $sigset)
                   7859:             or die "Can't unblock SIGINT for fork: $!\n";
                   7860:         $children{$pid} = $clientip;
                   7861:         &status('Started child '.$pid);
1.462     foxr     7862: 	close($client);
1.212     foxr     7863:         return;
                   7864:     } else {
                   7865:         # Child can *not* return from this subroutine.
                   7866:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
                   7867:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
                   7868:                                 #don't get intercepted
                   7869:         $SIG{USR1}= \&logstatus;
                   7870:         $SIG{ALRM}= \&timeout;
1.468     foxr     7871: 	#
                   7872: 	# Block sigpipe as it gets thrownon socket disconnect and we want to 
                   7873: 	# deal with that as a read faiure instead.
                   7874: 	#
                   7875: 	my $blockset = POSIX::SigSet->new(SIGPIPE);
                   7876: 	sigprocmask(SIG_BLOCK, $blockset);
                   7877: 
1.212     foxr     7878:         $lastlog='Forked ';
                   7879:         $status='Forked';
1.178     foxr     7880: 
1.212     foxr     7881:         # unblock signals
                   7882:         sigprocmask(SIG_UNBLOCK, $sigset)
                   7883:             or die "Can't unblock SIGINT for fork: $!\n";
1.178     foxr     7884: 
1.212     foxr     7885: #        my $tmpsnum=0;            # Now global
                   7886: #---------------------------------------------------- kerberos 5 initialization
                   7887:         &Authen::Krb5::init_context();
1.511     raeburn  7888: 
                   7889:         my $no_ets;
1.571     raeburn  7890:         if ($dist =~ /^(?:centos|rhes|scientific|oracle|rocky|alma)(\d+)/) {
1.511     raeburn  7891:             if ($1 >= 7) {
                   7892:                 $no_ets = 1;
                   7893:             }
                   7894:         } elsif ($dist =~ /^suse(\d+\.\d+)$/) {
                   7895:             if (($1 eq '9.3') || ($1 >= 12.2)) {
                   7896:                 $no_ets = 1; 
                   7897:             }
1.514     raeburn  7898:         } elsif ($dist =~ /^sles(\d+)$/) {
                   7899:             if ($1 > 11) {
                   7900:                 $no_ets = 1;
                   7901:             }
1.511     raeburn  7902:         } elsif ($dist =~ /^fedora(\d+)$/) {
                   7903:             if ($1 < 7) {
                   7904:                 $no_ets = 1;
                   7905:             }
                   7906:         }
                   7907:         unless ($no_ets) {
1.286     albertel 7908: 	    &Authen::Krb5::init_ets();
                   7909: 	}
1.209     albertel 7910: 
1.212     foxr     7911: 	&status('Accepted connection');
                   7912: # =============================================================================
                   7913:             # do something with the connection
                   7914: # -----------------------------------------------------------------------------
                   7915: 	# see if we know client and 'check' for spoof IP by ineffective challenge
1.178     foxr     7916: 
1.278     albertel 7917: 	my $outsideip=$clientip;
                   7918: 	if ($clientip eq '127.0.0.1') {
1.368     albertel 7919: 	    $outsideip=&Apache::lonnet::get_host_ip($perlvar{'lonHostID'});
1.278     albertel 7920: 	}
1.412     foxr     7921: 	&ReadManagerTable();
1.368     albertel 7922: 	my $clientrec=defined(&Apache::lonnet::get_hosts_from_ip($outsideip));
1.278     albertel 7923: 	my $ismanager=($managers{$outsideip}    ne undef);
1.432     raeburn  7924: 	$clientname  = "[unknown]";
1.212     foxr     7925: 	if($clientrec) {	# Establish client type.
                   7926: 	    $ConnectionType = "client";
1.368     albertel 7927: 	    $clientname = (&Apache::lonnet::get_hosts_from_ip($outsideip))[-1];
1.212     foxr     7928: 	    if($ismanager) {
                   7929: 		$ConnectionType = "both";
                   7930: 	    }
                   7931: 	} else {
                   7932: 	    $ConnectionType = "manager";
1.278     albertel 7933: 	    $clientname = $managers{$outsideip};
1.212     foxr     7934: 	}
1.556     raeburn  7935: 	my $clientok;
1.178     foxr     7936: 
1.212     foxr     7937: 	if ($clientrec || $ismanager) {
                   7938: 	    &status("Waiting for init from $clientip $clientname");
                   7939: 	    &logthis('<font color="yellow">INFO: Connection, '.
                   7940: 		     $clientip.
                   7941: 		  " ($clientname) connection type = $ConnectionType </font>" );
                   7942: 	    &status("Connecting $clientip  ($clientname))"); 
                   7943: 	    my $remotereq=<$client>;
                   7944: 	    chomp($remotereq);
                   7945: 	    Debug("Got init: $remotereq");
1.337     albertel 7946: 
1.212     foxr     7947: 	    if ($remotereq =~ /^init/) {
                   7948: 		&sethost("sethost:$perlvar{'lonHostID'}");
                   7949: 		#
                   7950: 		#  If the remote is attempting a local init... give that a try:
                   7951: 		#
1.432     raeburn  7952: 		(my $i, my $inittype, $clientversion) = split(/:/, $remotereq);
1.492     droeschl 7953:         # For LON-CAPA 2.9, the  client session will have sent its LON-CAPA
                   7954:         # version when initiating the connection. For LON-CAPA 2.8 and older,
                   7955:         # the version is retrieved from the global %loncaparevs in lonnet.pm.            
1.494     droeschl 7956:         # $clientversion contains path to keyfile if $inittype eq 'local'
                   7957:         # it's overridden below in this case
1.492     droeschl 7958:         $clientversion ||= $Apache::lonnet::loncaparevs{$clientname};
1.209     albertel 7959: 
1.212     foxr     7960: 		# If the connection type is ssl, but I didn't get my
                   7961: 		# certificate files yet, then I'll drop  back to 
                   7962: 		# insecure (if allowed).
1.532     raeburn  7963: 
                   7964:                 if ($inittype eq "ssl") {
                   7965:                     my $context;
                   7966:                     if ($clientsamedom) {
                   7967:                         $context = 'dom';
                   7968:                         if ($secureconf{'connfrom'}{'dom'} eq 'no') {
                   7969:                             $inittype = "";
                   7970:                         }
                   7971:                     } elsif ($clientsameinst) {
                   7972:                         $context = 'intdom';
                   7973:                         if ($secureconf{'connfrom'}{'intdom'} eq 'no') {
                   7974:                             $inittype = "";
                   7975:                         }
                   7976:                     } else {
                   7977:                         $context = 'other';
                   7978:                         if ($secureconf{'connfrom'}{'other'} eq 'no') {
                   7979:                             $inittype = "";
                   7980:                         }
                   7981:                     }
                   7982:                     if ($inittype eq '') {
                   7983:                         &logthis("<font color=\"blue\"> Domain config set "
                   7984:                                 ."to no ssl for $clientname (context: $context)"
                   7985:                                 ." -- trying insecure auth</font>");
                   7986:                     }
                   7987:                 }
                   7988: 
1.212     foxr     7989: 		if($inittype eq "ssl") {
                   7990: 		    my ($ca, $cert) = lonssl::CertificateFile;
                   7991: 		    my $kfile       = lonssl::KeyFile;
                   7992: 		    if((!$ca)   || 
                   7993: 		       (!$cert) || 
                   7994: 		       (!$kfile)) {
                   7995: 			$inittype = ""; # This forces insecure attempt.
                   7996: 			&logthis("<font color=\"blue\"> Certificates not "
                   7997: 				 ."installed -- trying insecure auth</font>");
1.224     foxr     7998: 		    } else {	# SSL certificates are in place so
1.212     foxr     7999: 		    }		# Leave the inittype alone.
                   8000: 		}
                   8001: 
                   8002: 		if($inittype eq "local") {
1.432     raeburn  8003:                     $clientversion = $perlvar{'lonVersion'};
1.212     foxr     8004: 		    my $key = LocalConnection($client, $remotereq);
                   8005: 		    if($key) {
                   8006: 			Debug("Got local key $key");
                   8007: 			$clientok     = 1;
                   8008: 			my $cipherkey = pack("H32", $key);
                   8009: 			$cipher       = new IDEA($cipherkey);
                   8010: 			print $client "ok:local\n";
1.442     www      8011: 			&logthis('<font color="green">'
1.212     foxr     8012: 				 . "Successful local authentication </font>");
                   8013: 			$keymode = "local"
1.178     foxr     8014: 		    } else {
1.212     foxr     8015: 			Debug("Failed to get local key");
                   8016: 			$clientok = 0;
                   8017: 			shutdown($client, 3);
                   8018: 			close $client;
1.178     foxr     8019: 		    }
1.212     foxr     8020: 		} elsif ($inittype eq "ssl") {
1.532     raeburn  8021: 		    my $key = SSLConnection($client,$clientname);
1.212     foxr     8022: 		    if ($key) {
                   8023: 			$clientok = 1;
                   8024: 			my $cipherkey = pack("H32", $key);
                   8025: 			$cipher       = new IDEA($cipherkey);
                   8026: 			&logthis('<font color="green">'
                   8027: 				 ."Successfull ssl authentication with $clientname </font>");
                   8028: 			$keymode = "ssl";
                   8029: 	     
1.178     foxr     8030: 		    } else {
1.212     foxr     8031: 			$clientok = 0;
                   8032: 			close $client;
1.178     foxr     8033: 		    }
1.212     foxr     8034: 	   
                   8035: 		} else {
                   8036: 		    my $ok = InsecureConnection($client);
                   8037: 		    if($ok) {
                   8038: 			$clientok = 1;
                   8039: 			&logthis('<font color="green">'
                   8040: 				 ."Successful insecure authentication with $clientname </font>");
                   8041: 			print $client "ok\n";
                   8042: 			$keymode = "insecure";
1.178     foxr     8043: 		    } else {
1.212     foxr     8044: 			&logthis('<font color="yellow">'
                   8045: 				  ."Attempted insecure connection disallowed </font>");
                   8046: 			close $client;
                   8047: 			$clientok = 0;
1.178     foxr     8048: 		    }
                   8049: 		}
1.212     foxr     8050: 	    } else {
                   8051: 		&logthis(
                   8052: 			 "<font color='blue'>WARNING: "
                   8053: 			 ."$clientip failed to initialize: >$remotereq< </font>");
                   8054: 		&status('No init '.$clientip);
                   8055: 	    }
                   8056: 	} else {
                   8057: 	    &logthis(
                   8058: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
                   8059: 	    &status('Hung up on '.$clientip);
                   8060: 	}
                   8061:  
                   8062: 	if ($clientok) {
                   8063: # ---------------- New known client connecting, could mean machine online again
1.368     albertel 8064: 	    if (&Apache::lonnet::get_host_ip($currenthostid) ne $clientip 
1.367     albertel 8065: 		&& $clientip ne '127.0.0.1') {
1.375     albertel 8066: 		&Apache::lonnet::reconlonc($clientname);
1.212     foxr     8067: 	    }
                   8068: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
                   8069: 	    &status('Will listen to '.$clientname);
                   8070: # ------------------------------------------------------------ Process requests
                   8071: 	    my $keep_going = 1;
                   8072: 	    my $user_input;
1.556     raeburn  8073: 
1.212     foxr     8074: 	    while(($user_input = get_request) && $keep_going) {
                   8075: 		alarm(120);
                   8076: 		Debug("Main: Got $user_input\n");
                   8077: 		$keep_going = &process_request($user_input);
1.178     foxr     8078: 		alarm(0);
1.569     raeburn  8079: 		&status('Listening to '.$clientname." ($keymode)");
1.161     foxr     8080: 	    }
1.212     foxr     8081: 
1.59      www      8082: # --------------------------------------------- client unknown or fishy, refuse
1.212     foxr     8083: 	}  else {
1.161     foxr     8084: 	    print $client "refused\n";
                   8085: 	    $client->close();
1.190     albertel 8086: 	    &logthis("<font color='blue'>WARNING: "
1.161     foxr     8087: 		     ."Rejected client $clientip, closing connection</font>");
                   8088: 	}
1.525     raeburn  8089:     }
1.161     foxr     8090:     
1.1       albertel 8091: # =============================================================================
1.161     foxr     8092:     
1.190     albertel 8093:     &logthis("<font color='red'>CRITICAL: "
1.161     foxr     8094: 	     ."Disconnect from $clientip ($clientname)</font>");    
1.569     raeburn  8095: 
                   8096: 
1.161     foxr     8097:     # this exit is VERY important, otherwise the child will become
                   8098:     # a producer of more and more children, forking yourself into
                   8099:     # process death.
                   8100:     exit;
1.106     foxr     8101:     
1.78      foxr     8102: }
1.532     raeburn  8103: 
                   8104: #
                   8105: #  Used to determine if a particular client is from the same domain
1.556     raeburn  8106: #  as the current server, or from the same internet domain, and
                   8107: #  also if the client can host sessions for the domain's users.
                   8108: #  A hash is populated with keys set to commands sent by the client
                   8109: #  which may not be executed for this domain.
1.532     raeburn  8110: #
                   8111: #  Optional input -- the client to check for domain and internet domain.
                   8112: #  If not specified, defaults to the package variable: $clientname
                   8113: #
                   8114: #  If called in array context will not set package variables, but will
                   8115: #  instead return an array of two values - (a) true if client is in the
1.556     raeburn  8116: #  same domain as the server, and (b) true if client is in the same 
                   8117: #  internet domain.
1.532     raeburn  8118: #
                   8119: #  If called in scalar context, sets package variables for current client:
                   8120: #
1.556     raeburn  8121: #  $clienthomedom    - LonCAPA domain of homeID for client.
                   8122: #  $clientsamedom    - LonCAPA domain same for this host and client.
                   8123: #  $clientintdom     - LonCAPA "internet domain" for client.
                   8124: #  $clientsameinst   - LonCAPA "internet domain" same for this host & client.
                   8125: #  $clientremoteok   - If current domain permits hosting on this client: 1
                   8126: #  %clientprohibited - Commands prohibited for domain's users for this client.
                   8127: #
                   8128: #  if the host and client have the same "internet domain", then the value
                   8129: #  of $clientremoteok is not used, and no commands are prohibited.
1.532     raeburn  8130: #
                   8131: #  returns 1 to indicate package variables have been set for current client.
                   8132: #
                   8133: 
                   8134: sub set_client_info {
                   8135:     my ($lonhost) = @_;
                   8136:     $lonhost ||= $clientname;
                   8137:     my $clienthost = &Apache::lonnet::hostname($lonhost);
                   8138:     my $clientserverhomeID = &Apache::lonnet::get_server_homeID($clienthost);
                   8139:     my $homedom = &Apache::lonnet::host_domain($clientserverhomeID);
                   8140:     my $samedom = 0;
1.557     raeburn  8141:     if ($perlvar{'lonDefDomain'} eq $homedom) {
1.532     raeburn  8142:         $samedom = 1;
                   8143:     }
                   8144:     my $intdom = &Apache::lonnet::internet_dom($clientserverhomeID);
                   8145:     my $sameinst = 0;
                   8146:     if ($intdom ne '') {
                   8147:         my $internet_names = &Apache::lonnet::get_internet_names($currenthostid);
                   8148:         if (ref($internet_names) eq 'ARRAY') {
                   8149:             if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   8150:                 $sameinst = 1;
                   8151:             }
                   8152:         }
                   8153:     }
                   8154:     if (wantarray) {
                   8155:         return ($samedom,$sameinst);
                   8156:     } else {
                   8157:         $clienthomedom = $homedom;
                   8158:         $clientsamedom = $samedom;
                   8159:         $clientintdom = $intdom;
                   8160:         $clientsameinst = $sameinst;
1.556     raeburn  8161:         if ($clientsameinst) {
                   8162:             undef($clientremoteok);
                   8163:             undef(%clientprohibited);
                   8164:         } else {
                   8165:             $clientremoteok = &get_remote_hostable($currentdomainid);
                   8166:             %clientprohibited = &get_prohibited($currentdomainid);
                   8167:         }
1.532     raeburn  8168:         return 1;
                   8169:     }
                   8170: }
                   8171: 
1.261     foxr     8172: #
                   8173: #   Determine if a user is an author for the indicated domain.
                   8174: #
                   8175: # Parameters:
                   8176: #    domain          - domain to check in .
                   8177: #    user            - Name of user to check.
                   8178: #
                   8179: # Return:
                   8180: #     1             - User is an author for domain.
                   8181: #     0             - User is not an author for domain.
                   8182: sub is_author {
                   8183:     my ($domain, $user) = @_;
                   8184: 
                   8185:     &Debug("is_author: $user @ $domain");
                   8186: 
                   8187:     my $hashref = &tie_user_hash($domain, $user, "roles",
                   8188: 				 &GDBM_READER());
                   8189: 
                   8190:     #  Author role should show up as a key /domain/_au
1.78      foxr     8191: 
1.321     albertel 8192:     my $value;
1.487     foxr     8193:     if ($hashref) {
1.78      foxr     8194: 
1.487     foxr     8195: 	my $key    = "/$domain/_au";
                   8196: 	if (defined($hashref)) {
                   8197: 	    $value = $hashref->{$key};
                   8198: 	    if(!untie_user_hash($hashref)) {
                   8199: 		return 'error: ' .  ($!+0)." untie (GDBM) Failed";
                   8200: 	    }
                   8201: 	}
                   8202: 	
                   8203: 	if(defined($value)) {
                   8204: 	    &Debug("$user @ $domain is an author");
                   8205: 	}
                   8206:     } else {
                   8207: 	return 'error: '.($!+0)." tie (GDBM) Failed";
1.261     foxr     8208:     }
                   8209: 
                   8210:     return defined($value);
                   8211: }
1.78      foxr     8212: #
                   8213: #   Checks to see if the input roleput request was to set
1.482     www      8214: # an author role.  If so, creates construction space 
1.78      foxr     8215: # Parameters:
                   8216: #    request   - The request sent to the rolesput subchunk.
                   8217: #                We're looking for  /domain/_au
                   8218: #    domain    - The domain in which the user is having roles doctored.
                   8219: #    user      - Name of the user for which the role is being put.
                   8220: #    authtype  - The authentication type associated with the user.
                   8221: #
1.289     albertel 8222: sub manage_permissions {
1.192     foxr     8223:     my ($request, $domain, $user, $authtype) = @_;
1.78      foxr     8224:     # See if the request is of the form /$domain/_au
1.289     albertel 8225:     if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
1.484     raeburn  8226:         my $path=$perlvar{'lonDocRoot'}."/priv/$domain";
1.482     www      8227:         unless (-e $path) {        
                   8228:            mkdir($path);
                   8229:         }
                   8230:         unless (-e $path.'/'.$user) {
                   8231:            mkdir($path.'/'.$user);
                   8232:         }
1.78      foxr     8233:     }
                   8234: }
1.222     foxr     8235: 
                   8236: 
                   8237: #
                   8238: #  Return the full path of a user password file, whether it exists or not.
                   8239: # Parameters:
                   8240: #   domain     - Domain in which the password file lives.
                   8241: #   user       - name of the user.
                   8242: # Returns:
                   8243: #    Full passwd path:
                   8244: #
                   8245: sub password_path {
                   8246:     my ($domain, $user) = @_;
1.264     albertel 8247:     return &propath($domain, $user).'/passwd';
1.222     foxr     8248: }
                   8249: 
                   8250: #   Password Filename
                   8251: #   Returns the path to a passwd file given domain and user... only if
                   8252: #  it exists.
                   8253: # Parameters:
                   8254: #   domain    - Domain in which to search.
                   8255: #   user      - username.
                   8256: # Returns:
                   8257: #   - If the password file exists returns its path.
                   8258: #   - If the password file does not exist, returns undefined.
                   8259: #
                   8260: sub password_filename {
                   8261:     my ($domain, $user) = @_;
                   8262: 
                   8263:     Debug ("PasswordFilename called: dom = $domain user = $user");
                   8264: 
                   8265:     my $path  = &password_path($domain, $user);
                   8266:     Debug("PasswordFilename got path: $path");
                   8267:     if(-e $path) {
                   8268: 	return $path;
                   8269:     } else {
                   8270: 	return undef;
                   8271:     }
                   8272: }
                   8273: 
                   8274: #
                   8275: #   Rewrite the contents of the user's passwd file.
                   8276: #  Parameters:
                   8277: #    domain    - domain of the user.
                   8278: #    name      - User's name.
                   8279: #    contents  - New contents of the file.
1.533     raeburn  8280: #    saveold   - (optional). If true save old file in a passwd.bak file.
1.222     foxr     8281: # Returns:
                   8282: #   0    - Failed.
                   8283: #   1    - Success.
                   8284: #
                   8285: sub rewrite_password_file {
1.533     raeburn  8286:     my ($domain, $user, $contents, $saveold) = @_;
1.222     foxr     8287: 
                   8288:     my $file = &password_filename($domain, $user);
                   8289:     if (defined $file) {
1.533     raeburn  8290:         if ($saveold) {
                   8291:             my $bakfile = $file.'.bak';
                   8292:             if (CopyFile($file,$bakfile)) {
                   8293:                 chmod(0400,$bakfile);
                   8294:                 &logthis("Old password saved in passwd.bak for internally authenticated user: $user:$domain");
                   8295:             } else {
                   8296:                 &logthis("Failed to save old password in passwd.bak for internally authenticated user: $user:$domain");
                   8297:             }
                   8298:         }
1.222     foxr     8299: 	my $pf = IO::File->new(">$file");
                   8300: 	if($pf) {
                   8301: 	    print $pf "$contents\n";
                   8302: 	    return 1;
                   8303: 	} else {
                   8304: 	    return 0;
                   8305: 	}
                   8306:     } else {
                   8307: 	return 0;
                   8308:     }
                   8309: 
                   8310: }
                   8311: 
1.78      foxr     8312: #
1.222     foxr     8313: #   get_auth_type - Determines the authorization type of a user in a domain.
1.78      foxr     8314: 
                   8315: #     Returns the authorization type or nouser if there is no such user.
                   8316: #
1.436     raeburn  8317: sub get_auth_type {
1.192     foxr     8318:     my ($domain, $user)  = @_;
1.78      foxr     8319: 
1.222     foxr     8320:     Debug("get_auth_type( $domain, $user ) \n");
1.78      foxr     8321:     my $proname    = &propath($domain, $user); 
                   8322:     my $passwdfile = "$proname/passwd";
                   8323:     if( -e $passwdfile ) {
                   8324: 	my $pf = IO::File->new($passwdfile);
                   8325: 	my $realpassword = <$pf>;
                   8326: 	chomp($realpassword);
1.79      foxr     8327: 	Debug("Password info = $realpassword\n");
1.78      foxr     8328: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79      foxr     8329: 	Debug("Authtype = $authtype, content = $contentpwd\n");
1.259     raeburn  8330: 	return "$authtype:$contentpwd";     
1.224     foxr     8331:     } else {
1.79      foxr     8332: 	Debug("Returning nouser");
1.78      foxr     8333: 	return "nouser";
                   8334:     }
1.1       albertel 8335: }
                   8336: 
1.220     foxr     8337: #
                   8338: #  Validate a user given their domain, name and password.  This utility
                   8339: #  function is used by both  AuthenticateHandler and ChangePasswordHandler
                   8340: #  to validate the login credentials of a user.
                   8341: # Parameters:
                   8342: #    $domain    - The domain being logged into (this is required due to
                   8343: #                 the capability for multihomed systems.
                   8344: #    $user      - The name of the user being validated.
                   8345: #    $password  - The user's propoposed password.
                   8346: #
                   8347: # Returns:
                   8348: #     1        - The domain,user,pasword triplet corresponds to a valid
                   8349: #                user.
                   8350: #     0        - The domain,user,password triplet is not a valid user.
                   8351: #
                   8352: sub validate_user {
1.396     raeburn  8353:     my ($domain, $user, $password, $checkdefauth) = @_;
1.220     foxr     8354: 
                   8355:     # Why negative ~pi you may well ask?  Well this function is about
                   8356:     # authentication, and therefore very important to get right.
                   8357:     # I've initialized the flag that determines whether or not I've 
                   8358:     # validated correctly to a value it's not supposed to get.
                   8359:     # At the end of this function. I'll ensure that it's not still that
                   8360:     # value so we don't just wind up returning some accidental value
                   8361:     # as a result of executing an unforseen code path that
1.249     foxr     8362:     # did not set $validated.  At the end of valid execution paths,
                   8363:     # validated shoule be 1 for success or 0 for failuer.
1.220     foxr     8364: 
                   8365:     my $validated = -3.14159;
                   8366: 
                   8367:     #  How we authenticate is determined by the type of authentication
                   8368:     #  the user has been assigned.  If the authentication type is
                   8369:     #  "nouser", the user does not exist so we will return 0.
                   8370: 
1.222     foxr     8371:     my $contents = &get_auth_type($domain, $user);
1.220     foxr     8372:     my ($howpwd, $contentpwd) = split(/:/, $contents);
                   8373: 
                   8374:     my $null = pack("C",0);	# Used by kerberos auth types.
                   8375: 
1.395     raeburn  8376:     if ($howpwd eq 'nouser') {
1.396     raeburn  8377:         if ($checkdefauth) {
                   8378:             my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   8379:             if ($domdefaults{'auth_def'} eq 'localauth') {
                   8380:                 $howpwd = $domdefaults{'auth_def'};
                   8381:                 $contentpwd = $domdefaults{'auth_arg_def'};
                   8382:             } elsif ((($domdefaults{'auth_def'} eq 'krb4') || 
                   8383:                       ($domdefaults{'auth_def'} eq 'krb5')) &&
                   8384:                      ($domdefaults{'auth_arg_def'} ne '')) {
                   8385:                 $howpwd = $domdefaults{'auth_def'};
                   8386:                 $contentpwd = $domdefaults{'auth_arg_def'}; 
                   8387:             }
1.395     raeburn  8388:         }
1.533     raeburn  8389:     }
1.220     foxr     8390:     if ($howpwd ne 'nouser') {
                   8391: 	if($howpwd eq "internal") { # Encrypted is in local password file.
1.518     raeburn  8392:             if (length($contentpwd) == 13) {
                   8393:                 $validated = (crypt($password,$contentpwd) eq $contentpwd);
                   8394:                 if ($validated) {
1.533     raeburn  8395:                     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   8396:                     if ($domdefaults{'intauth_switch'}) {
                   8397:                         my $ncpass = &hash_passwd($domain,$password);
                   8398:                         my $saveold;
                   8399:                         if ($domdefaults{'intauth_switch'} == 2) {
                   8400:                             $saveold = 1;
                   8401:                         }
                   8402:                         if (&rewrite_password_file($domain,$user,"$howpwd:$ncpass",$saveold)) {
                   8403:                             &update_passwd_history($user,$domain,$howpwd,'conversion');
                   8404:                             &logthis("Validated password hashed with bcrypt for $user:$domain");
                   8405:                         }
1.518     raeburn  8406:                     }
                   8407:                 }
                   8408:             } else {
1.533     raeburn  8409:                 $validated = &check_internal_passwd($password,$contentpwd,$domain,$user);
1.518     raeburn  8410:             }
1.220     foxr     8411: 	}
                   8412: 	elsif ($howpwd eq "unix") { # User is a normal unix user.
                   8413: 	    $contentpwd = (getpwnam($user))[1];
                   8414: 	    if($contentpwd) {
                   8415: 		if($contentpwd eq 'x') { # Shadow password file...
                   8416: 		    my $pwauth_path = "/usr/local/sbin/pwauth";
                   8417: 		    open PWAUTH,  "|$pwauth_path" or
                   8418: 			die "Cannot invoke authentication";
                   8419: 		    print PWAUTH "$user\n$password\n";
                   8420: 		    close PWAUTH;
                   8421: 		    $validated = ! $?;
                   8422: 
                   8423: 		} else { 	         # Passwords in /etc/passwd. 
                   8424: 		    $validated = (crypt($password,
                   8425: 					$contentpwd) eq $contentpwd);
                   8426: 		}
                   8427: 	    } else {
                   8428: 		$validated = 0;
                   8429: 	    }
1.439     raeburn  8430: 	} elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
                   8431:             my $checkwithkrb5 = 0;
                   8432:             if ($dist =~/^fedora(\d+)$/) {
                   8433:                 if ($1 > 11) {
                   8434:                     $checkwithkrb5 = 1;
                   8435:                 }
                   8436:             } elsif ($dist =~ /^suse([\d.]+)$/) {
                   8437:                 if ($1 > 11.1) {
                   8438:                     $checkwithkrb5 = 1; 
                   8439:                 }
                   8440:             }
                   8441:             if ($checkwithkrb5) {
                   8442:                 $validated = &krb5_authen($password,$null,$user,$contentpwd);
                   8443:             } else {
                   8444:                 $validated = &krb4_authen($password,$null,$user,$contentpwd);
                   8445:             }
1.224     foxr     8446: 	} elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
1.439     raeburn  8447:             $validated = &krb5_authen($password,$null,$user,$contentpwd);
1.224     foxr     8448: 	} elsif ($howpwd eq "localauth") { 
1.220     foxr     8449: 	    #  Authenticate via installation specific authentcation method:
                   8450: 	    $validated = &localauth::localauth($user, 
                   8451: 					       $password, 
1.353     albertel 8452: 					       $contentpwd,
                   8453: 					       $domain);
1.358     albertel 8454: 	    if ($validated < 0) {
1.357     albertel 8455: 		&logthis("localauth for $contentpwd $user:$domain returned a $validated");
                   8456: 		$validated = 0;
                   8457: 	    }
1.224     foxr     8458: 	} else {			# Unrecognized auth is also bad.
1.220     foxr     8459: 	    $validated = 0;
                   8460: 	}
                   8461:     } else {
                   8462: 	$validated = 0;
                   8463:     }
                   8464:     #
                   8465:     #  $validated has the correct stat of the authentication:
                   8466:     #
                   8467: 
                   8468:     unless ($validated != -3.14159) {
1.249     foxr     8469: 	#  I >really really< want to know if this happens.
                   8470: 	#  since it indicates that user authentication is badly
                   8471: 	#  broken in some code path.
                   8472:         #
                   8473: 	die "ValidateUser - failed to set the value of validated $domain, $user $password";
1.220     foxr     8474:     }
                   8475:     return $validated;
                   8476: }
                   8477: 
1.518     raeburn  8478: sub check_internal_passwd {
1.533     raeburn  8479:     my ($plainpass,$stored,$domain,$user) = @_;
1.518     raeburn  8480:     my (undef,$method,@rest) = split(/!/,$stored);
1.533     raeburn  8481:     if ($method eq 'bcrypt') {
1.518     raeburn  8482:         my $result = &hash_passwd($domain,$plainpass,@rest);
                   8483:         if ($result ne $stored) {
                   8484:             return 0;
                   8485:         }
1.533     raeburn  8486:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   8487:         if ($domdefaults{'intauth_check'}) {
                   8488:             # Upgrade to a larger number of rounds if necessary
                   8489:             my $defaultcost = $domdefaults{'intauth_cost'};
                   8490:             if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
                   8491:                 $defaultcost = 10;
                   8492:             }
                   8493:             if (int($rest[0])<int($defaultcost)) {
                   8494:                 if ($domdefaults{'intauth_check'} == 1) { 
                   8495:                     my $ncpass = &hash_passwd($domain,$plainpass);
                   8496:                     if (&rewrite_password_file($domain,$user,"internal:$ncpass")) {
                   8497:                         &update_passwd_history($user,$domain,'internal','update cost');
                   8498:                         &logthis("Validated password hashed with bcrypt for $user:$domain");
                   8499:                     }
                   8500:                     return 1;
                   8501:                 } elsif ($domdefaults{'intauth_check'} == 2) {
                   8502:                     return 0;
                   8503:                 }
                   8504:             }
                   8505:         } else {
                   8506:             return 1;
1.518     raeburn  8507:         }
                   8508:     }
                   8509:     return 0;
                   8510: }
                   8511: 
                   8512: sub get_last_authchg {
                   8513:     my ($domain,$user) = @_;
                   8514:     my $lastmod;
                   8515:     my $logname = &propath($domain,$user).'/passwd.log';
                   8516:     if (-e "$logname") {
                   8517:         $lastmod = (stat("$logname"))[9];
                   8518:     }
                   8519:     return $lastmod;
                   8520: }
                   8521: 
1.439     raeburn  8522: sub krb4_authen {
                   8523:     my ($password,$null,$user,$contentpwd) = @_;
                   8524:     my $validated = 0;
                   8525:     if (!($password =~ /$null/) ) {  # Null password not allowed.
                   8526:         eval {
                   8527:             require Authen::Krb4;
                   8528:         };
                   8529:         if (!$@) {
                   8530:             my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
                   8531:                                                        "",
                   8532:                                                        $contentpwd,,
                   8533:                                                        'krbtgt',
                   8534:                                                        $contentpwd,
                   8535:                                                        1,
                   8536:                                                        $password);
                   8537:             if(!$k4error) {
                   8538:                 $validated = 1;
                   8539:             } else {
                   8540:                 $validated = 0;
                   8541:                 &logthis('krb4: '.$user.', '.$contentpwd.', '.
                   8542:                           &Authen::Krb4::get_err_txt($Authen::Krb4::error));
                   8543:             }
                   8544:         } else {
                   8545:             $validated = krb5_authen($password,$null,$user,$contentpwd);
                   8546:         }
                   8547:     }
                   8548:     return $validated;
                   8549: }
                   8550: 
                   8551: sub krb5_authen {
                   8552:     my ($password,$null,$user,$contentpwd) = @_;
                   8553:     my $validated = 0;
                   8554:     if(!($password =~ /$null/)) { # Null password not allowed.
                   8555:         my $krbclient = &Authen::Krb5::parse_name($user.'@'
                   8556:                                                   .$contentpwd);
                   8557:         my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
                   8558:         my $krbserver  = &Authen::Krb5::parse_name($krbservice);
                   8559:         my $credentials= &Authen::Krb5::cc_default();
                   8560:         $credentials->initialize(&Authen::Krb5::parse_name($user.'@'
                   8561:                                                             .$contentpwd));
                   8562:         my $krbreturn;
                   8563:         if (exists(&Authen::Krb5::get_init_creds_password)) {
                   8564:             $krbreturn =
                   8565:                 &Authen::Krb5::get_init_creds_password($krbclient,$password,
                   8566:                                                           $krbservice);
                   8567:             $validated = (ref($krbreturn) eq 'Authen::Krb5::Creds');
                   8568:         } else {
                   8569:             $krbreturn  =
                   8570:                 &Authen::Krb5::get_in_tkt_with_password($krbclient,$krbserver,
                   8571:                                                          $password,$credentials);
                   8572:             $validated = ($krbreturn == 1);
                   8573:         }
                   8574:         if (!$validated) {
                   8575:             &logthis('krb5: '.$user.', '.$contentpwd.', '.
                   8576:                      &Authen::Krb5::error());
                   8577:         }
                   8578:     }
                   8579:     return $validated;
                   8580: }
1.220     foxr     8581: 
1.84      albertel 8582: sub addline {
                   8583:     my ($fname,$hostid,$ip,$newline)=@_;
                   8584:     my $contents;
                   8585:     my $found=0;
1.355     albertel 8586:     my $expr='^'.quotemeta($hostid).':'.quotemeta($ip).':';
1.134     albertel 8587:     my $sh;
1.84      albertel 8588:     if ($sh=IO::File->new("$fname.subscription")) {
                   8589: 	while (my $subline=<$sh>) {
                   8590: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
                   8591: 	}
                   8592: 	$sh->close();
                   8593:     }
                   8594:     $sh=IO::File->new(">$fname.subscription");
                   8595:     if ($contents) { print $sh $contents; }
                   8596:     if ($newline) { print $sh $newline; }
                   8597:     $sh->close();
                   8598:     return $found;
1.86      www      8599: }
                   8600: 
1.234     foxr     8601: sub get_chat {
1.324     raeburn  8602:     my ($cdom,$cname,$udom,$uname,$group)=@_;
1.310     albertel 8603: 
1.87      www      8604:     my @entries=();
1.324     raeburn  8605:     my $namespace = 'nohist_chatroom';
                   8606:     my $namespace_inroom = 'nohist_inchatroom';
1.335     albertel 8607:     if ($group ne '') {
1.324     raeburn  8608:         $namespace .= '_'.$group;
                   8609:         $namespace_inroom .= '_'.$group;
                   8610:     }
                   8611:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 8612: 				 &GDBM_READER());
                   8613:     if ($hashref) {
                   8614: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.311     albertel 8615: 	&untie_user_hash($hashref);
1.123     www      8616:     }
1.124     www      8617:     my @participants=();
1.134     albertel 8618:     my $cutoff=time-60;
1.324     raeburn  8619:     $hashref = &tie_user_hash($cdom, $cname, $namespace_inroom,
1.310     albertel 8620: 			      &GDBM_WRCREAT());
                   8621:     if ($hashref) {
                   8622:         $hashref->{$uname.':'.$udom}=time;
                   8623:         foreach my $user (sort(keys(%$hashref))) {
                   8624: 	    if ($hashref->{$user}>$cutoff) {
                   8625: 		push(@participants, 'active_participant:'.$user);
1.123     www      8626:             }
                   8627:         }
1.311     albertel 8628:         &untie_user_hash($hashref);
1.86      www      8629:     }
1.124     www      8630:     return (@participants,@entries);
1.86      www      8631: }
                   8632: 
1.234     foxr     8633: sub chat_add {
1.324     raeburn  8634:     my ($cdom,$cname,$newchat,$group)=@_;
1.88      albertel 8635:     my @entries=();
1.142     www      8636:     my $time=time;
1.324     raeburn  8637:     my $namespace = 'nohist_chatroom';
                   8638:     my $logfile = 'chatroom.log';
1.335     albertel 8639:     if ($group ne '') {
1.324     raeburn  8640:         $namespace .= '_'.$group;
                   8641:         $logfile = 'chatroom_'.$group.'.log';
                   8642:     }
                   8643:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 8644: 				 &GDBM_WRCREAT());
                   8645:     if ($hashref) {
                   8646: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.88      albertel 8647: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
                   8648: 	my ($thentime,$idnum)=split(/\_/,$lastid);
                   8649: 	my $newid=$time.'_000000';
                   8650: 	if ($thentime==$time) {
                   8651: 	    $idnum=~s/^0+//;
                   8652: 	    $idnum++;
                   8653: 	    $idnum=substr('000000'.$idnum,-6,6);
                   8654: 	    $newid=$time.'_'.$idnum;
                   8655: 	}
1.310     albertel 8656: 	$hashref->{$newid}=$newchat;
1.88      albertel 8657: 	my $expired=$time-3600;
1.310     albertel 8658: 	foreach my $comment (keys(%$hashref)) {
                   8659: 	    my ($thistime) = ($comment=~/(\d+)\_/);
1.88      albertel 8660: 	    if ($thistime<$expired) {
1.310     albertel 8661: 		delete $hashref->{$comment};
1.88      albertel 8662: 	    }
                   8663: 	}
1.310     albertel 8664: 	{
                   8665: 	    my $proname=&propath($cdom,$cname);
1.324     raeburn  8666: 	    if (open(CHATLOG,">>$proname/$logfile")) { 
1.310     albertel 8667: 		print CHATLOG ("$time:".&unescape($newchat)."\n");
                   8668: 	    }
                   8669: 	    close(CHATLOG);
1.142     www      8670: 	}
1.311     albertel 8671: 	&untie_user_hash($hashref);
1.86      www      8672:     }
1.84      albertel 8673: }
                   8674: 
                   8675: sub unsub {
                   8676:     my ($fname,$clientip)=@_;
                   8677:     my $result;
1.188     foxr     8678:     my $unsubs = 0;		# Number of successful unsubscribes:
                   8679: 
                   8680: 
                   8681:     # An old way subscriptions were handled was to have a 
                   8682:     # subscription marker file:
                   8683: 
                   8684:     Debug("Attempting unlink of $fname.$clientname");
1.161     foxr     8685:     if (unlink("$fname.$clientname")) {
1.188     foxr     8686: 	$unsubs++;		# Successful unsub via marker file.
                   8687:     } 
                   8688: 
                   8689:     # The more modern way to do it is to have a subscription list
                   8690:     # file:
                   8691: 
1.84      albertel 8692:     if (-e "$fname.subscription") {
1.161     foxr     8693: 	my $found=&addline($fname,$clientname,$clientip,'');
1.188     foxr     8694: 	if ($found) { 
                   8695: 	    $unsubs++;
                   8696: 	}
                   8697:     } 
                   8698: 
                   8699:     #  If either or both of these mechanisms succeeded in unsubscribing a 
                   8700:     #  resource we can return ok:
                   8701: 
                   8702:     if($unsubs) {
                   8703: 	$result = "ok\n";
1.84      albertel 8704:     } else {
1.188     foxr     8705: 	$result = "not_subscribed\n";
1.84      albertel 8706:     }
1.188     foxr     8707: 
1.84      albertel 8708:     return $result;
                   8709: }
                   8710: 
1.101     www      8711: sub currentversion {
                   8712:     my $fname=shift;
                   8713:     my $version=-1;
                   8714:     my $ulsdir='';
                   8715:     if ($fname=~/^(.+)\/[^\/]+$/) {
                   8716:        $ulsdir=$1;
                   8717:     }
1.114     albertel 8718:     my ($fnamere1,$fnamere2);
                   8719:     # remove version if already specified
1.101     www      8720:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114     albertel 8721:     # get the bits that go before and after the version number
                   8722:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
                   8723: 	$fnamere1=$1;
                   8724: 	$fnamere2='.'.$2;
                   8725:     }
1.101     www      8726:     if (-e $fname) { $version=1; }
                   8727:     if (-e $ulsdir) {
1.134     albertel 8728: 	if(-d $ulsdir) {
                   8729: 	    if (opendir(LSDIR,$ulsdir)) {
                   8730: 		my $ulsfn;
                   8731: 		while ($ulsfn=readdir(LSDIR)) {
1.101     www      8732: # see if this is a regular file (ignore links produced earlier)
1.134     albertel 8733: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
                   8734: 		    unless (-l $thisfile) {
1.160     www      8735: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134     albertel 8736: 			    if ($1>$version) { $version=$1; }
                   8737: 			}
                   8738: 		    }
                   8739: 		}
                   8740: 		closedir(LSDIR);
                   8741: 		$version++;
                   8742: 	    }
                   8743: 	}
                   8744:     }
                   8745:     return $version;
1.101     www      8746: }
                   8747: 
                   8748: sub thisversion {
                   8749:     my $fname=shift;
                   8750:     my $version=-1;
                   8751:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
                   8752: 	$version=$1;
                   8753:     }
                   8754:     return $version;
                   8755: }
                   8756: 
1.84      albertel 8757: sub subscribe {
                   8758:     my ($userinput,$clientip)=@_;
                   8759:     my $result;
1.293     albertel 8760:     my ($cmd,$fname)=split(/:/,$userinput,2);
1.84      albertel 8761:     my $ownership=&ishome($fname);
                   8762:     if ($ownership eq 'owner') {
1.101     www      8763: # explitly asking for the current version?
                   8764:         unless (-e $fname) {
                   8765:             my $currentversion=&currentversion($fname);
                   8766: 	    if (&thisversion($fname)==$currentversion) {
                   8767:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
                   8768: 		    my $root=$1;
                   8769:                     my $extension=$2;
                   8770:                     symlink($root.'.'.$extension,
                   8771:                             $root.'.'.$currentversion.'.'.$extension);
1.102     www      8772:                     unless ($extension=~/\.meta$/) {
                   8773:                        symlink($root.'.'.$extension.'.meta',
                   8774:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
                   8775: 		    }
1.101     www      8776:                 }
                   8777:             }
                   8778:         }
1.84      albertel 8779: 	if (-e $fname) {
                   8780: 	    if (-d $fname) {
                   8781: 		$result="directory\n";
                   8782: 	    } else {
1.161     foxr     8783: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134     albertel 8784: 		my $now=time;
1.161     foxr     8785: 		my $found=&addline($fname,$clientname,$clientip,
                   8786: 				   "$clientname:$clientip:$now\n");
1.84      albertel 8787: 		if ($found) { $result="$fname\n"; }
                   8788: 		# if they were subscribed to only meta data, delete that
                   8789:                 # subscription, when you subscribe to a file you also get
                   8790:                 # the metadata
                   8791: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
                   8792: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
1.476     raeburn  8793:                 my $protocol = $Apache::lonnet::protocol{$perlvar{'lonHostID'}};
                   8794:                 $protocol = 'http' if ($protocol ne 'https');
                   8795: 		$fname=$protocol.'://'.&Apache::lonnet::hostname($perlvar{'lonHostID'})."/".$fname;
1.84      albertel 8796: 		$result="$fname\n";
                   8797: 	    }
                   8798: 	} else {
                   8799: 	    $result="not_found\n";
                   8800: 	}
                   8801:     } else {
                   8802: 	$result="rejected\n";
                   8803:     }
                   8804:     return $result;
                   8805: }
1.287     foxr     8806: #  Change the passwd of a unix user.  The caller must have
                   8807: #  first verified that the user is a loncapa user.
                   8808: #
                   8809: # Parameters:
                   8810: #    user      - Unix user name to change.
                   8811: #    pass      - New password for the user.
                   8812: # Returns:
                   8813: #    ok    - if success
                   8814: #    other - Some meaningfule error message string.
                   8815: # NOTE:
                   8816: #    invokes a setuid script to change the passwd.
                   8817: sub change_unix_password {
                   8818:     my ($user, $pass) = @_;
                   8819: 
                   8820:     &Debug("change_unix_password");
                   8821:     my $execdir=$perlvar{'lonDaemons'};
                   8822:     &Debug("Opening lcpasswd pipeline");
                   8823:     my $pf = IO::File->new("|$execdir/lcpasswd > "
                   8824: 			   ."$perlvar{'lonDaemons'}"
                   8825: 			   ."/logs/lcpasswd.log");
                   8826:     print $pf "$user\n$pass\n$pass\n";
                   8827:     close $pf;
                   8828:     my $err = $?;
                   8829:     return ($err < @passwderrors) ? $passwderrors[$err] : 
                   8830: 	"pwchange_falure - unknown error";
                   8831: 
                   8832:     
                   8833: }
                   8834: 
1.91      albertel 8835: 
                   8836: sub make_passwd_file {
1.518     raeburn  8837:     my ($uname,$udom,$umode,$npass,$passfilename,$action)=@_;
1.390     raeburn  8838:     my $result="ok";
1.91      albertel 8839:     if ($umode eq 'krb4' or $umode eq 'krb5') {
                   8840: 	{
                   8841: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8842: 	    if ($pf) {
                   8843: 		print $pf "$umode:$npass\n";
1.518     raeburn  8844:                 &update_passwd_history($uname,$udom,$umode,$action);
1.261     foxr     8845: 	    } else {
                   8846: 		$result = "pass_file_failed_error";
                   8847: 	    }
1.91      albertel 8848: 	}
                   8849:     } elsif ($umode eq 'internal') {
1.518     raeburn  8850:         my $ncpass = &hash_passwd($udom,$npass);
1.91      albertel 8851: 	{
                   8852: 	    &Debug("Creating internal auth");
                   8853: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8854: 	    if($pf) {
1.518     raeburn  8855: 		print $pf "internal:$ncpass\n";
                   8856:                 &update_passwd_history($uname,$udom,$umode,$action); 
1.261     foxr     8857: 	    } else {
                   8858: 		$result = "pass_file_failed_error";
                   8859: 	    }
1.91      albertel 8860: 	}
                   8861:     } elsif ($umode eq 'localauth') {
                   8862: 	{
                   8863: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8864: 	    if($pf) {
                   8865: 		print $pf "localauth:$npass\n";
1.524     raeburn  8866:                 &update_passwd_history($uname,$udom,$umode,$action);
1.261     foxr     8867: 	    } else {
                   8868: 		$result = "pass_file_failed_error";
                   8869: 	    }
1.91      albertel 8870: 	}
                   8871:     } elsif ($umode eq 'unix') {
1.502     raeburn  8872: 	&logthis(">>>Attempt to create unix account blocked -- unix auth not available for new users.");
                   8873: 	$result="no_new_unix_accounts";
1.91      albertel 8874:     } elsif ($umode eq 'none') {
                   8875: 	{
1.223     foxr     8876: 	    my $pf = IO::File->new("> $passfilename");
1.261     foxr     8877: 	    if($pf) {
                   8878: 		print $pf "none:\n";
                   8879: 	    } else {
                   8880: 		$result = "pass_file_failed_error";
                   8881: 	    }
1.91      albertel 8882: 	}
1.543     raeburn  8883:     } elsif ($umode eq 'lti') {
                   8884:         my $pf = IO::File->new(">$passfilename");
                   8885:         if($pf) {
                   8886:             print $pf "lti:\n";
                   8887:             &update_passwd_history($uname,$udom,$umode,$action);
                   8888:         } else {
                   8889:             $result = "pass_file_failed_error";
                   8890:         }
1.91      albertel 8891:     } else {
1.390     raeburn  8892: 	$result="auth_mode_error";
1.91      albertel 8893:     }
                   8894:     return $result;
1.121     albertel 8895: }
                   8896: 
1.265     albertel 8897: sub convert_photo {
                   8898:     my ($start,$dest)=@_;
                   8899:     system("convert $start $dest");
                   8900: }
                   8901: 
1.121     albertel 8902: sub sethost {
                   8903:     my ($remotereq) = @_;
                   8904:     my (undef,$hostid)=split(/:/,$remotereq);
1.322     albertel 8905:     # ignore sethost if we are already correct
                   8906:     if ($hostid eq $currenthostid) {
                   8907: 	return 'ok';
                   8908:     }
                   8909: 
1.121     albertel 8910:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
1.368     albertel 8911:     if (&Apache::lonnet::get_host_ip($perlvar{'lonHostID'}) 
                   8912: 	eq &Apache::lonnet::get_host_ip($hostid)) {
1.200     matthew  8913: 	$currenthostid  =$hostid;
1.369     albertel 8914: 	$currentdomainid=&Apache::lonnet::host_domain($hostid);
1.556     raeburn  8915:         &set_client_info();
1.443     www      8916: #	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
1.121     albertel 8917:     } else {
                   8918: 	&logthis("Requested host id $hostid not an alias of ".
                   8919: 		 $perlvar{'lonHostID'}." refusing connection");
                   8920: 	return 'unable_to_set';
                   8921:     }
                   8922:     return 'ok';
                   8923: }
                   8924: 
                   8925: sub version {
                   8926:     my ($userinput)=@_;
                   8927:     $remoteVERSION=(split(/:/,$userinput))[1];
                   8928:     return "version:$VERSION";
1.127     albertel 8929: }
1.178     foxr     8930: 
1.447     raeburn  8931: sub get_usersession_config {
                   8932:     my ($dom,$name) = @_;
                   8933:     my ($usersessionconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8934:     if (defined($cached)) {
                   8935:         return $usersessionconf;
                   8936:     } else {
                   8937:         my %domconfig = &Apache::lonnet::get_dom('configuration',['usersessions'],$dom);
1.525     raeburn  8938:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'usersessions'},3600);
                   8939:         return $domconfig{'usersessions'};
1.447     raeburn  8940:     }
                   8941:     return;
                   8942: }
1.200     matthew  8943: 
1.534     raeburn  8944: sub get_usersearch_config {
                   8945:     my ($dom,$name) = @_;
                   8946:     my ($usersearchconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8947:     if (defined($cached)) {
                   8948:         return $usersearchconf;
                   8949:     } else {
                   8950:         my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$dom);
                   8951:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'directorysrch'},600);
                   8952:         return $domconfig{'directorysrch'};
                   8953:     }
                   8954:     return;
                   8955: }
                   8956: 
1.525     raeburn  8957: sub get_prohibited {
                   8958:     my ($dom) = @_;
                   8959:     my $name = 'trust';
                   8960:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8961:     unless (defined($cached)) {
                   8962:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$dom);
                   8963:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'trust'},3600);
                   8964:         $trustconfig = $domconfig{'trust'};
                   8965:     }
                   8966:     my %prohibited;
                   8967:     if (ref($trustconfig)) {
                   8968:         foreach my $prefix (keys(%{$trustconfig})) {
                   8969:             if (ref($trustconfig->{$prefix}) eq 'HASH') {
                   8970:                 my $reject;
                   8971:                 if (ref($trustconfig->{$prefix}->{'exc'}) eq 'ARRAY') {
                   8972:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'exc'}})) {
                   8973:                         $reject = 1;
                   8974:                     }
                   8975:                 }
                   8976:                 if (ref($trustconfig->{$prefix}->{'inc'}) eq 'ARRAY') {
                   8977:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'inc'}})) {
                   8978:                         $reject = 0;
                   8979:                     } else {
                   8980:                         $reject = 1;
                   8981:                     }
                   8982:                 }
                   8983:                 if ($reject) {
                   8984:                     $prohibited{$prefix} = 1;
                   8985:                 }
                   8986:             }
                   8987:         }
                   8988:     }
                   8989:     return %prohibited;
                   8990: }
1.450     raeburn  8991: 
1.556     raeburn  8992: sub get_remote_hostable {
                   8993:     my ($dom) = @_;
                   8994:     my $result;
                   8995:     if ($clientintdom) {
                   8996:         $result = 1;
                   8997:         my $remsessconf = &get_usersession_config($dom,'remotesession');
                   8998:         if (ref($remsessconf) eq 'HASH') {
                   8999:             if (ref($remsessconf->{'remote'}) eq 'HASH') {
                   9000:                 if (ref($remsessconf->{'remote'}->{'excludedomain'}) eq 'ARRAY') {
                   9001:                     if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'excludedomain'}})) {
                   9002:                         $result = 0;
                   9003:                     }
                   9004:                 }
                   9005:                 if (ref($remsessconf->{'remote'}->{'includedomain'}) eq 'ARRAY') {
                   9006:                     if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'includedomain'}})) {
                   9007:                         $result = 1;
                   9008:                     } else {
                   9009:                         $result = 0;
                   9010:                     }
                   9011:                 }
                   9012:             }
                   9013:         }
                   9014:     }
                   9015:     return $result;
                   9016: }
                   9017: 
1.471     raeburn  9018: sub distro_and_arch {
                   9019:     return $dist.':'.$arch;
                   9020: }
                   9021: 
1.61      harris41 9022: # ----------------------------------- POD (plain old documentation, CPAN style)
                   9023: 
                   9024: =head1 NAME
                   9025: 
                   9026: lond - "LON Daemon" Server (port "LOND" 5663)
                   9027: 
                   9028: =head1 SYNOPSIS
                   9029: 
1.74      harris41 9030: Usage: B<lond>
                   9031: 
                   9032: Should only be run as user=www.  This is a command-line script which
                   9033: is invoked by B<loncron>.  There is no expectation that a typical user
                   9034: will manually start B<lond> from the command-line.  (In other words,
                   9035: DO NOT START B<lond> YOURSELF.)
1.61      harris41 9036: 
                   9037: =head1 DESCRIPTION
                   9038: 
1.74      harris41 9039: There are two characteristics associated with the running of B<lond>,
                   9040: PROCESS MANAGEMENT (starting, stopping, handling child processes)
                   9041: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
                   9042: subscriptions, etc).  These are described in two large
                   9043: sections below.
                   9044: 
                   9045: B<PROCESS MANAGEMENT>
                   9046: 
1.61      harris41 9047: Preforker - server who forks first. Runs as a daemon. HUPs.
                   9048: Uses IDEA encryption
                   9049: 
1.74      harris41 9050: B<lond> forks off children processes that correspond to the other servers
                   9051: in the network.  Management of these processes can be done at the
                   9052: parent process level or the child process level.
                   9053: 
                   9054: B<logs/lond.log> is the location of log messages.
                   9055: 
                   9056: The process management is now explained in terms of linux shell commands,
                   9057: subroutines internal to this code, and signal assignments:
                   9058: 
                   9059: =over 4
                   9060: 
                   9061: =item *
                   9062: 
                   9063: PID is stored in B<logs/lond.pid>
                   9064: 
                   9065: This is the process id number of the parent B<lond> process.
                   9066: 
                   9067: =item *
                   9068: 
                   9069: SIGTERM and SIGINT
                   9070: 
                   9071: Parent signal assignment:
                   9072:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   9073: 
                   9074: Child signal assignment:
                   9075:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
                   9076: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
                   9077:  to restart a new child.)
                   9078: 
                   9079: Command-line invocations:
                   9080:  B<kill> B<-s> SIGTERM I<PID>
                   9081:  B<kill> B<-s> SIGINT I<PID>
                   9082: 
                   9083: Subroutine B<HUNTSMAN>:
                   9084:  This is only invoked for the B<lond> parent I<PID>.
                   9085: This kills all the children, and then the parent.
                   9086: The B<lonc.pid> file is cleared.
                   9087: 
                   9088: =item *
                   9089: 
                   9090: SIGHUP
                   9091: 
                   9092: Current bug:
                   9093:  This signal can only be processed the first time
                   9094: on the parent process.  Subsequent SIGHUP signals
                   9095: have no effect.
                   9096: 
                   9097: Parent signal assignment:
                   9098:  $SIG{HUP}  = \&HUPSMAN;
                   9099: 
                   9100: Child signal assignment:
                   9101:  none (nothing happens)
                   9102: 
                   9103: Command-line invocations:
                   9104:  B<kill> B<-s> SIGHUP I<PID>
                   9105: 
                   9106: Subroutine B<HUPSMAN>:
                   9107:  This is only invoked for the B<lond> parent I<PID>,
                   9108: This kills all the children, and then the parent.
                   9109: The B<lond.pid> file is cleared.
                   9110: 
                   9111: =item *
                   9112: 
                   9113: SIGUSR1
                   9114: 
                   9115: Parent signal assignment:
                   9116:  $SIG{USR1} = \&USRMAN;
                   9117: 
                   9118: Child signal assignment:
                   9119:  $SIG{USR1}= \&logstatus;
                   9120: 
                   9121: Command-line invocations:
                   9122:  B<kill> B<-s> SIGUSR1 I<PID>
                   9123: 
                   9124: Subroutine B<USRMAN>:
                   9125:  When invoked for the B<lond> parent I<PID>,
                   9126: SIGUSR1 is sent to all the children, and the status of
                   9127: each connection is logged.
1.144     foxr     9128: 
                   9129: =item *
                   9130: 
                   9131: SIGUSR2
                   9132: 
                   9133: Parent Signal assignment:
                   9134:     $SIG{USR2} = \&UpdateHosts
                   9135: 
                   9136: Child signal assignment:
                   9137:     NONE
                   9138: 
1.74      harris41 9139: 
                   9140: =item *
                   9141: 
                   9142: SIGCHLD
                   9143: 
                   9144: Parent signal assignment:
                   9145:  $SIG{CHLD} = \&REAPER;
                   9146: 
                   9147: Child signal assignment:
                   9148:  none
                   9149: 
                   9150: Command-line invocations:
                   9151:  B<kill> B<-s> SIGCHLD I<PID>
                   9152: 
                   9153: Subroutine B<REAPER>:
                   9154:  This is only invoked for the B<lond> parent I<PID>.
                   9155: Information pertaining to the child is removed.
                   9156: The socket port is cleaned up.
                   9157: 
                   9158: =back
                   9159: 
                   9160: B<SERVER-SIDE ACTIVITIES>
                   9161: 
                   9162: Server-side information can be accepted in an encrypted or non-encrypted
                   9163: method.
                   9164: 
                   9165: =over 4
                   9166: 
                   9167: =item ping
                   9168: 
                   9169: Query a client in the hosts.tab table; "Are you there?"
                   9170: 
                   9171: =item pong
                   9172: 
                   9173: Respond to a ping query.
                   9174: 
                   9175: =item ekey
                   9176: 
                   9177: Read in encrypted key, make cipher.  Respond with a buildkey.
                   9178: 
                   9179: =item load
                   9180: 
                   9181: Respond with CPU load based on a computation upon /proc/loadavg.
                   9182: 
                   9183: =item currentauth
                   9184: 
                   9185: Reply with current authentication information (only over an
                   9186: encrypted channel).
                   9187: 
                   9188: =item auth
                   9189: 
                   9190: Only over an encrypted channel, reply as to whether a user's
                   9191: authentication information can be validated.
                   9192: 
                   9193: =item passwd
                   9194: 
                   9195: Allow for a password to be set.
                   9196: 
                   9197: =item makeuser
                   9198: 
                   9199: Make a user.
                   9200: 
1.517     raeburn  9201: =item changeuserauth
1.74      harris41 9202: 
                   9203: Allow for authentication mechanism and password to be changed.
                   9204: 
                   9205: =item home
1.61      harris41 9206: 
1.74      harris41 9207: Respond to a question "are you the home for a given user?"
                   9208: 
                   9209: =item update
                   9210: 
                   9211: Update contents of a subscribed resource.
                   9212: 
                   9213: =item unsubscribe
                   9214: 
                   9215: The server is unsubscribing from a resource.
                   9216: 
                   9217: =item subscribe
                   9218: 
                   9219: The server is subscribing to a resource.
                   9220: 
                   9221: =item log
                   9222: 
                   9223: Place in B<logs/lond.log>
                   9224: 
                   9225: =item put
                   9226: 
                   9227: stores hash in namespace
                   9228: 
1.496     raeburn  9229: =item rolesput
1.74      harris41 9230: 
                   9231: put a role into a user's environment
                   9232: 
                   9233: =item get
                   9234: 
                   9235: returns hash with keys from array
                   9236: reference filled in from namespace
                   9237: 
                   9238: =item eget
                   9239: 
                   9240: returns hash with keys from array
                   9241: reference filled in from namesp (encrypts the return communication)
                   9242: 
                   9243: =item rolesget
                   9244: 
                   9245: get a role from a user's environment
                   9246: 
                   9247: =item del
                   9248: 
                   9249: deletes keys out of array from namespace
                   9250: 
                   9251: =item keys
                   9252: 
                   9253: returns namespace keys
                   9254: 
                   9255: =item dump
                   9256: 
                   9257: dumps the complete (or key matching regexp) namespace into a hash
                   9258: 
                   9259: =item store
                   9260: 
                   9261: stores hash permanently
                   9262: for this url; hashref needs to be given and should be a \%hashname; the
                   9263: remaining args aren't required and if they aren't passed or are '' they will
                   9264: be derived from the ENV
                   9265: 
                   9266: =item restore
                   9267: 
                   9268: returns a hash for a given url
                   9269: 
                   9270: =item querysend
                   9271: 
                   9272: Tells client about the lonsql process that has been launched in response
                   9273: to a sent query.
                   9274: 
                   9275: =item queryreply
                   9276: 
                   9277: Accept information from lonsql and make appropriate storage in temporary
                   9278: file space.
                   9279: 
                   9280: =item idput
                   9281: 
                   9282: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
                   9283: for each student, defined perhaps by the institutional Registrar.)
                   9284: 
                   9285: =item idget
                   9286: 
                   9287: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
                   9288: for each student, defined perhaps by the institutional Registrar.)
                   9289: 
1.517     raeburn  9290: =item iddel
                   9291: 
                   9292: Deletes one or more ids in a domain's id database.
                   9293: 
1.74      harris41 9294: =item tmpput
                   9295: 
                   9296: Accept and store information in temporary space.
                   9297: 
                   9298: =item tmpget
                   9299: 
                   9300: Send along temporarily stored information.
                   9301: 
                   9302: =item ls
                   9303: 
                   9304: List part of a user's directory.
                   9305: 
1.135     foxr     9306: =item pushtable
                   9307: 
                   9308: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
                   9309: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
                   9310: must be restored manually in case of a problem with the new table file.
                   9311: pushtable requires that the request be encrypted and validated via
                   9312: ValidateManager.  The form of the command is:
                   9313: enc:pushtable tablename <tablecontents> \n
                   9314: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
                   9315: cleartext newline.
                   9316: 
1.74      harris41 9317: =item Hanging up (exit or init)
                   9318: 
                   9319: What to do when a client tells the server that they (the client)
                   9320: are leaving the network.
                   9321: 
                   9322: =item unknown command
                   9323: 
                   9324: If B<lond> is sent an unknown command (not in the list above),
                   9325: it replys to the client "unknown_cmd".
1.135     foxr     9326: 
1.74      harris41 9327: 
                   9328: =item UNKNOWN CLIENT
                   9329: 
                   9330: If the anti-spoofing algorithm cannot verify the client,
                   9331: the client is rejected (with a "refused" message sent
                   9332: to the client, and the connection is closed.
                   9333: 
                   9334: =back
1.61      harris41 9335: 
                   9336: =head1 PREREQUISITES
                   9337: 
                   9338: IO::Socket
                   9339: IO::File
                   9340: Apache::File
                   9341: POSIX
                   9342: Crypt::IDEA
                   9343: GDBM_File
                   9344: Authen::Krb4
1.91      albertel 9345: Authen::Krb5
1.61      harris41 9346: 
                   9347: =head1 COREQUISITES
                   9348: 
1.490     droeschl 9349: none
                   9350: 
1.61      harris41 9351: =head1 OSNAMES
                   9352: 
                   9353: linux
                   9354: 
                   9355: =head1 SCRIPT CATEGORIES
                   9356: 
                   9357: Server/Process
                   9358: 
                   9359: =cut
1.409     foxr     9360: 
                   9361: 
                   9362: =pod
                   9363: 
                   9364: =head1 LOG MESSAGES
                   9365: 
                   9366: The messages below can be emitted in the lond log.  This log is located
                   9367: in ~httpd/perl/logs/lond.log  Many log messages have HTML encapsulation
                   9368: to provide coloring if examined from inside a web page. Some do not.
                   9369: Where color is used, the colors are; Red for sometihhng to get excited
                   9370: about and to follow up on. Yellow for something to keep an eye on to
                   9371: be sure it does not get worse, Green,and Blue for informational items.
                   9372: 
                   9373: In the discussions below, sometimes reference is made to ~httpd
                   9374: when describing file locations.  There isn't really an httpd 
                   9375: user, however there is an httpd directory that gets installed in the
                   9376: place that user home directories go.  On linux, this is usually
                   9377: (always?) /home/httpd.
                   9378: 
                   9379: 
                   9380: Some messages are colorless.  These are usually (not always)
                   9381: Green/Blue color level messages.
                   9382: 
                   9383: =over 2
                   9384: 
                   9385: =item (Red)  LocalConnection rejecting non local: <ip> ne 127.0.0.1
                   9386: 
                   9387: A local connection negotiation was attempted by
                   9388: a host whose IP address was not 127.0.0.1.
                   9389: The socket is closed and the child will exit.
                   9390: lond has three ways to establish an encyrption
                   9391: key with a client:
                   9392: 
                   9393: =over 2
                   9394: 
                   9395: =item local 
                   9396: 
                   9397: The key is written and read from a file.
                   9398: This is only valid for connections from localhost.
                   9399: 
                   9400: =item insecure 
                   9401: 
                   9402: The key is generated by the server and
                   9403: transmitted to the client.
                   9404: 
                   9405: =item  ssl (secure)
                   9406: 
                   9407: An ssl connection is negotiated with the client,
                   9408: the key is generated by the server and sent to the 
                   9409: client across this ssl connection before the
                   9410: ssl connectionis terminated and clear text
                   9411: transmission resumes.
                   9412: 
                   9413: =back
                   9414: 
                   9415: =item (Red) LocalConnection: caller is insane! init = <init> and type = <type>
                   9416: 
                   9417: The client is local but has not sent an initialization
                   9418: string that is the literal "init:local"  The connection
                   9419: is closed and the child exits.
                   9420: 
                   9421: =item Red CRITICAL Can't get key file <error>        
                   9422: 
                   9423: SSL key negotiation is being attempted but the call to
1.549     raeburn  9424: lonssl::KeyFile failed.  This usually means that the
1.409     foxr     9425: configuration file is not correctly defining or protecting
                   9426: the directories/files lonCertificateDirectory or
                   9427: lonnetPrivateKey
                   9428: <error> is a string that describes the reason that
                   9429: the key file could not be located.
                   9430: 
                   9431: =item (Red) CRITICAL  Can't get certificates <error>  
                   9432: 
                   9433: SSL key negotiation failed because we were not able to retrives our certificate
                   9434: or the CA's certificate in the call to lonssl::CertificateFile
                   9435: <error> is the textual reason this failed.  Usual reasons:
                   9436: 
                   9437: =over 2
1.490     droeschl 9438: 
1.409     foxr     9439: =item Apache config file for loncapa  incorrect:
1.490     droeschl 9440: 
1.409     foxr     9441: one of the variables 
                   9442: lonCertificateDirectory, lonnetCertificateAuthority, or lonnetCertificate
                   9443: undefined or incorrect
                   9444: 
                   9445: =item Permission error:
                   9446: 
                   9447: The directory pointed to by lonCertificateDirectory is not readable by lond
                   9448: 
                   9449: =item Permission error:
                   9450: 
                   9451: Files in the directory pointed to by lonCertificateDirectory are not readable by lond.
                   9452: 
                   9453: =item Installation error:                         
                   9454: 
                   9455: Either the certificate authority file or the certificate have not
                   9456: been installed in lonCertificateDirectory.
                   9457: 
                   9458: =item (Red) CRITICAL SSL Socket promotion failed:  <err> 
                   9459: 
                   9460: The promotion of the connection from plaintext to SSL failed
                   9461: <err> is the reason for the failure.  There are two
                   9462: system calls involved in the promotion (one of which failed), 
                   9463: a dup to produce
                   9464: a second fd on the raw socket over which the encrypted data
                   9465: will flow and IO::SOcket::SSL->new_from_fd which creates
                   9466: the SSL connection on the duped fd.
                   9467: 
                   9468: =item (Blue)   WARNING client did not respond to challenge 
                   9469: 
                   9470: This occurs on an insecure (non SSL) connection negotiation request.
                   9471: lond generates some number from the time, the PID and sends it to
                   9472: the client.  The client must respond by echoing this information back.
                   9473: If the client does not do so, that's a violation of the challenge
                   9474: protocols and the connection will be failed.
                   9475: 
                   9476: =item (Red) No manager table. Nobody can manage!!    
                   9477: 
                   9478: lond has the concept of privileged hosts that
                   9479: can perform remote management function such
                   9480: as update the hosts.tab.   The manager hosts
                   9481: are described in the 
                   9482: ~httpd/lonTabs/managers.tab file.
                   9483: this message is logged if this file is missing.
                   9484: 
                   9485: 
                   9486: =item (Green) Registering manager <dnsname> as <cluster_name> with <ipaddress>
                   9487: 
                   9488: Reports the successful parse and registration
                   9489: of a specific manager. 
                   9490: 
                   9491: =item Green existing host <clustername:dnsname>  
                   9492: 
                   9493: The manager host is already defined in the hosts.tab
                   9494: the information in that table, rather than the info in the
                   9495: manager table will be used to determine the manager's ip.
                   9496: 
                   9497: =item (Red) Unable to craete <filename>                 
                   9498: 
                   9499: lond has been asked to create new versions of an administrative
                   9500: file (by a manager).  When this is done, the new file is created
                   9501: in a temp file and then renamed into place so that there are always
                   9502: usable administrative files, even if the update fails.  This failure
                   9503: message means that the temp file could not be created.
                   9504: The update is abandoned, and the old file is available for use.
                   9505: 
                   9506: =item (Green) CopyFile from <oldname> to <newname> failed
                   9507: 
                   9508: In an update of administrative files, the copy of the existing file to a
                   9509: backup file failed.  The installation of the new file may still succeed,
                   9510: but there will not be a back up file to rever to (this should probably
                   9511: be yellow).
                   9512: 
                   9513: =item (Green) Pushfile: backed up <oldname> to <newname>
                   9514: 
                   9515: See above, the backup of the old administrative file succeeded.
                   9516: 
                   9517: =item (Red)  Pushfile: Unable to install <filename> <reason>
                   9518: 
                   9519: The new administrative file could not be installed.  In this case,
                   9520: the old administrative file is still in use.
                   9521: 
                   9522: =item (Green) Installed new < filename>.                      
                   9523: 
                   9524: The new administrative file was successfullly installed.                                               
                   9525: 
                   9526: =item (Red) Reinitializing lond pid=<pid>                    
                   9527: 
                   9528: The lonc child process <pid> will be sent a USR2 
                   9529: signal.
                   9530: 
                   9531: =item (Red) Reinitializing self                                    
                   9532: 
                   9533: We've been asked to re-read our administrative files,and
                   9534: are doing so.
                   9535: 
                   9536: =item (Yellow) error:Invalid process identifier <ident>  
                   9537: 
                   9538: A reinit command was received, but the target part of the 
                   9539: command was not valid.  It must be either
                   9540: 'lond' or 'lonc' but was <ident>
                   9541: 
                   9542: =item (Green) isValideditCommand checking: Command = <command> Key = <key> newline = <newline>
                   9543: 
                   9544: Checking to see if lond has been handed a valid edit
                   9545: command.  It is possible the edit command is not valid
                   9546: in that case there are no log messages to indicate that.
                   9547: 
                   9548: =item Result of password change for  <username> pwchange_success
                   9549: 
                   9550: The password for <username> was
                   9551: successfully changed.
                   9552: 
                   9553: =item Unable to open <user> passwd to change password
                   9554: 
                   9555: Could not rewrite the 
                   9556: internal password file for a user
                   9557: 
                   9558: =item Result of password change for <user> : <result>
1.490     droeschl 9559: 
1.409     foxr     9560: A unix password change for <user> was attempted 
                   9561: and the pipe returned <result>  
                   9562: 
                   9563: =item LWP GET: <message> for <fname> (<remoteurl>)
                   9564: 
                   9565: The lightweight process fetch for a resource failed
                   9566: with <message> the local filename that should
                   9567: have existed/been created was  <fname> the
                   9568: corresponding URI: <remoteurl>  This is emitted in several
                   9569: places.
                   9570: 
                   9571: =item Unable to move <transname> to <destname>     
                   9572: 
                   9573: From fetch_user_file_handler - the user file was replicated but could not
                   9574: be mv'd to its final location.
                   9575: 
                   9576: =item Looking for <domain> <username>              
                   9577: 
                   9578: From user_has_session_handler - This should be a Debug call instead
                   9579: it indicates lond is about to check whether the specified user has a 
                   9580: session active on the specified domain on the local host.
                   9581: 
                   9582: =item Client <ip> (<name>) hanging up: <input>     
                   9583: 
                   9584: lond has been asked to exit by its client.  The <ip> and <name> identify the
                   9585: client systemand <input> is the full exit command sent to the server.
                   9586: 
                   9587: =item Red CRITICAL: ABNORMAL EXIT. child <pid> for server <hostname> died through a crass with this error->[<message>].
1.490     droeschl 9588: 
1.409     foxr     9589: A lond child terminated.  NOte that this termination can also occur when the
                   9590: child receives the QUIT or DIE signals.  <pid> is the process id of the child,
                   9591: <hostname> the host lond is working for, and <message> the reason the child died
                   9592: to the best of our ability to get it (I would guess that any numeric value
                   9593: represents and errno value).  This is immediately followed by
                   9594: 
                   9595: =item  Famous last words: Catching exception - <log> 
                   9596: 
                   9597: Where log is some recent information about the state of the child.
                   9598: 
                   9599: =item Red CRITICAL: TIME OUT <pid>                     
                   9600: 
                   9601: Some timeout occured for server <pid>.  THis is normally a timeout on an LWP
                   9602: doing an HTTP::GET.
                   9603: 
                   9604: =item child <pid> died                              
                   9605: 
                   9606: The reaper caught a SIGCHILD for the lond child process <pid>
                   9607: This should be modified to also display the IP of the dying child
                   9608: $children{$pid}
                   9609: 
                   9610: =item Unknown child 0 died                           
                   9611: A child died but the wait for it returned a pid of zero which really should not
                   9612: ever happen. 
                   9613: 
                   9614: =item Child <which> - <pid> looks like we missed it's death 
                   9615: 
                   9616: When a sigchild is received, the reaper process checks all children to see if they are
                   9617: alive.  If children are dying quite quickly, the lack of signal queuing can mean
                   9618: that a signal hearalds the death of more than one child.  If so this message indicates
                   9619: which other one died. <which> is the ip of a dead child
                   9620: 
                   9621: =item Free socket: <shutdownretval>                
                   9622: 
                   9623: The HUNTSMAN sub was called due to a SIGINT in a child process.  The socket is being shutdown.
                   9624: for whatever reason, <shutdownretval> is printed but in fact shutdown() is not documented
                   9625: to return anything. This is followed by: 
                   9626: 
                   9627: =item Red CRITICAL: Shutting down                       
                   9628: 
                   9629: Just prior to exit.
                   9630: 
                   9631: =item Free socket: <shutdownretval>                 
                   9632: 
                   9633: The HUPSMAN sub was called due to a SIGHUP.  all children get killsed, and lond execs itself.
                   9634: This is followed by:
                   9635: 
                   9636: =item (Red) CRITICAL: Restarting                         
                   9637: 
                   9638: lond is about to exec itself to restart.
                   9639: 
                   9640: =item (Blue) Updating connections                        
                   9641: 
                   9642: (In response to a USR2).  All the children (except the one for localhost)
                   9643: are about to be killed, the hosts tab reread, and Apache reloaded via apachereload.
                   9644: 
                   9645: =item (Blue) UpdateHosts killing child <pid> for ip <ip>   
                   9646: 
                   9647: Due to USR2 as above.
                   9648: 
                   9649: =item (Green) keeping child for ip <ip> (pid = <pid>)    
                   9650: 
                   9651: In response to USR2 as above, the child indicated is not being restarted because
                   9652: it's assumed that we'll always need a child for the localhost.
                   9653: 
                   9654: 
                   9655: =item Going to check on the children                
                   9656: 
                   9657: Parent is about to check on the health of the child processes.
                   9658: Note that this is in response to a USR1 sent to the parent lond.
                   9659: there may be one or more of the next two messages:
                   9660: 
                   9661: =item <pid> is dead                                 
                   9662: 
                   9663: A child that we have in our child hash as alive has evidently died.
                   9664: 
                   9665: =item  Child <pid> did not respond                   
                   9666: 
                   9667: In the health check the child <pid> did not update/produce a pid_.txt
                   9668: file when sent it's USR1 signal.  That process is killed with a 9 signal, as it's
                   9669: assumed to be hung in some un-fixable way.
                   9670: 
                   9671: =item Finished checking children                   
1.490     droeschl 9672: 
1.409     foxr     9673: Master processs's USR1 processing is cojmplete.
                   9674: 
                   9675: =item (Red) CRITICAL: ------- Starting ------            
                   9676: 
                   9677: (There are more '-'s on either side).  Lond has forked itself off to 
                   9678: form a new session and is about to start actual initialization.
                   9679: 
                   9680: =item (Green) Attempting to start child (<client>)       
                   9681: 
                   9682: Started a new child process for <client>.  Client is IO::Socket object
                   9683: connected to the child.  This was as a result of a TCP/IP connection from a client.
                   9684: 
                   9685: =item Unable to determine who caller was, getpeername returned nothing
1.490     droeschl 9686: 
1.409     foxr     9687: In child process initialization.  either getpeername returned undef or
                   9688: a zero sized object was returned.  Processing continues, but in my opinion,
                   9689: this should be cause for the child to exit.
                   9690: 
                   9691: =item Unable to determine clientip                  
                   9692: 
                   9693: In child process initialization.  The peer address from getpeername was not defined.
                   9694: The client address is stored as "Unavailable" and processing continues.
                   9695: 
                   9696: =item (Yellow) INFO: Connection <ip> <name> connection type = <type>
1.490     droeschl 9697: 
1.409     foxr     9698: In child initialization.  A good connectionw as received from <ip>.
                   9699: 
                   9700: =over 2
                   9701: 
                   9702: =item <name> 
                   9703: 
                   9704: is the name of the client from hosts.tab.
                   9705: 
                   9706: =item <type> 
                   9707: 
                   9708: Is the connection type which is either 
                   9709: 
                   9710: =over 2
                   9711: 
                   9712: =item manager 
                   9713: 
                   9714: The connection is from a manager node, not in hosts.tab
                   9715: 
                   9716: =item client  
                   9717: 
                   9718: the connection is from a non-manager in the hosts.tab
                   9719: 
                   9720: =item both
                   9721: 
                   9722: The connection is from a manager in the hosts.tab.
                   9723: 
                   9724: =back
                   9725: 
                   9726: =back
                   9727: 
                   9728: =item (Blue) Certificates not installed -- trying insecure auth
                   9729: 
                   9730: One of the certificate file, key file or
                   9731: certificate authority file could not be found for a client attempting
                   9732: SSL connection intiation.  COnnection will be attemptied in in-secure mode.
                   9733: (this would be a system with an up to date lond that has not gotten a 
                   9734: certificate from us).
                   9735: 
                   9736: =item (Green)  Successful local authentication            
                   9737: 
                   9738: A local connection successfully negotiated the encryption key. 
                   9739: In this case the IDEA key is in a file (that is hopefully well protected).
                   9740: 
                   9741: =item (Green) Successful ssl authentication with <client>  
                   9742: 
                   9743: The client (<client> is the peer's name in hosts.tab), has successfully
                   9744: negotiated an SSL connection with this child process.
                   9745: 
                   9746: =item (Green) Successful insecure authentication with <client>
1.490     droeschl 9747: 
1.409     foxr     9748: 
                   9749: The client has successfully negotiated an  insecure connection withthe child process.
                   9750: 
                   9751: =item (Yellow) Attempted insecure connection disallowed    
                   9752: 
                   9753: The client attempted and failed to successfully negotiate a successful insecure
                   9754: connection.  This can happen either because the variable londAllowInsecure is false
                   9755: or undefined, or becuse the child did not successfully echo back the challenge
                   9756: string.
                   9757: 
                   9758: 
                   9759: =back
                   9760: 
1.441     raeburn  9761: =back
                   9762: 
1.409     foxr     9763: 
                   9764: =cut

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