Annotation of loncom/lond, revision 1.568

1.1       albertel    1: #!/usr/bin/perl
                      2: # The LearningOnline Network
                      3: # lond "LON Daemon" Server (port "LOND" 5663)
1.60      www         4: #
1.568   ! raeburn     5: # $Id: lond,v 1.567 2021/06/15 20:52:27 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.568   ! raeburn    68: my $VERSION='$Revision: 1.567 $'; #' 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,},
                    269:                makeuser => {remote => 1, enroll => 1, domroles => 1,},
                    270:                mkdiruserfile => {remote => 1, enroll => 1,},
                    271:                newput => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1,},
                    272:                passwd => {remote => 1},
                    273:                ping => {anywhere => 1},
                    274:                pong => {anywhere => 1},
                    275:                pushfile => {manageronly => 1},
                    276:                put => {remote => 1, enroll => 1, domroles => 1, msg => 1, content => 1, shared => 1},
                    277:                putdom => {remote => 1, domroles => 1,},
                    278:                putstore => {remote => 1, enroll => 1},
                    279:                queryreply => {anywhere => 1},
                    280:                querysend => {anywhere => 1},
1.535     raeburn   281:                querysend_activitylog => {remote => 1},
                    282:                querysend_allusers => {remote => 1, domroles => 1},
                    283:                querysend_courselog => {remote => 1},
                    284:                querysend_fetchenrollment => {remote => 1},
                    285:                querysend_getinstuser => {remote => 1},
                    286:                querysend_getmultinstusers => {remote => 1},
                    287:                querysend_instdirsearch => {remote => 1, domroles => 1, coaurem => 1},
                    288:                querysend_institutionalphotos => {remote => 1},
                    289:                querysend_portfolio_metadata => {remote => 1, content => 1},
                    290:                querysend_userlog => {remote => 1, domroles => 1},
                    291:                querysend_usersearch => {remote => 1, enroll => 1, coaurem => 1},
1.525     raeburn   292:                quit => {anywhere => 1},
                    293:                readlonnetglobal => {institutiononly => 1},
                    294:                reinit => {manageronly => 1}, #not used currently
                    295:                removeuserfile => {remote => 1, enroll => 1},
                    296:                renameuserfile => {remote => 1,},
                    297:                restore => {remote => 1, enroll => 1, reqcrs => 1,},
                    298:                rolesdel => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
                    299:                rolesput => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
1.527     raeburn   300:                servercerts => {institutiononly => 1},
1.528     raeburn   301:                serverdistarch => {anywhere => 1},
1.525     raeburn   302:                serverhomeID => {anywhere => 1},
                    303:                serverloncaparev => {anywhere => 1},
                    304:                servertimezone => {remote => 1, enroll => 1},
                    305:                setannounce => {remote => 1, domroles => 1},
                    306:                sethost => {anywhere => 1},
                    307:                store => {remote => 1, enroll => 1, reqcrs => 1,},
                    308:                studentphoto => {remote => 1, enroll => 1},
                    309:                sub => {content => 1,},
1.552     raeburn   310:                tmpdel => {institutiononly => 1},
                    311:                tmpget => {institutiononly => 1},
                    312:                tmpput => {remote => 1, othcoau => 1},
1.525     raeburn   313:                tokenauthuserfile => {anywhere => 1},
                    314:                unsub => {content => 1,},
                    315:                update => {shared => 1},
1.564     raeburn   316:                updatebalcookie => {institutiononly => 1},
1.525     raeburn   317:                updateclickers => {remote => 1},
                    318:                userhassession => {anywhere => 1},
                    319:                userload => {anywhere => 1},
                    320:                version => {anywhere => 1}, #not used
                    321:             );
                    322: 
                    323: #
1.207     foxr      324: #   Statistics that are maintained and dislayed in the status line.
                    325: #
1.212     foxr      326: my $Transactions = 0;		# Number of attempted transactions.
                    327: my $Failures     = 0;		# Number of transcations failed.
1.207     foxr      328: 
                    329: #   ResetStatistics: 
                    330: #      Resets the statistics counters:
                    331: #
                    332: sub ResetStatistics {
                    333:     $Transactions = 0;
                    334:     $Failures     = 0;
                    335: }
                    336: 
1.200     matthew   337: #------------------------------------------------------------------------
                    338: #
                    339: #   LocalConnection
                    340: #     Completes the formation of a locally authenticated connection.
                    341: #     This function will ensure that the 'remote' client is really the
                    342: #     local host.  If not, the connection is closed, and the function fails.
                    343: #     If so, initcmd is parsed for the name of a file containing the
                    344: #     IDEA session key.  The fie is opened, read, deleted and the session
                    345: #     key returned to the caller.
                    346: #
                    347: # Parameters:
                    348: #   $Socket      - Socket open on client.
                    349: #   $initcmd     - The full text of the init command.
                    350: #
                    351: # Returns:
                    352: #     IDEA session key on success.
                    353: #     undef on failure.
                    354: #
                    355: sub LocalConnection {
                    356:     my ($Socket, $initcmd) = @_;
1.373     albertel  357:     Debug("Attempting local connection: $initcmd client: $clientip");
1.277     albertel  358:     if($clientip ne "127.0.0.1") {
1.200     matthew   359: 	&logthis('<font color="red"> LocalConnection rejecting non local: '
1.373     albertel  360: 		 ."$clientip ne 127.0.0.1 </font>");
1.200     matthew   361: 	close $Socket;
                    362: 	return undef;
1.224     foxr      363:     }  else {
1.200     matthew   364: 	chomp($initcmd);	# Get rid of \n in filename.
                    365: 	my ($init, $type, $name) = split(/:/, $initcmd);
                    366: 	Debug(" Init command: $init $type $name ");
                    367: 
                    368: 	# Require that $init = init, and $type = local:  Otherwise
                    369: 	# the caller is insane:
                    370: 
                    371: 	if(($init ne "init") && ($type ne "local")) {
                    372: 	    &logthis('<font color = "red"> LocalConnection: caller is insane! '
                    373: 		     ."init = $init, and type = $type </font>");
                    374: 	    close($Socket);;
                    375: 	    return undef;
                    376: 		
                    377: 	}
                    378: 	#  Now get the key filename:
                    379: 
                    380: 	my $IDEAKey = lonlocal::ReadKeyFile($name);
                    381: 	return $IDEAKey;
                    382:     }
                    383: }
                    384: #------------------------------------------------------------------------------
                    385: #
                    386: #  SSLConnection
                    387: #   Completes the formation of an ssh authenticated connection. The
                    388: #   socket is promoted to an ssl socket.  If this promotion and the associated
                    389: #   certificate exchange are successful, the IDEA key is generated and sent
                    390: #   to the remote peer via the SSL tunnel. The IDEA key is also returned to
                    391: #   the caller after the SSL tunnel is torn down.
                    392: #
                    393: # Parameters:
                    394: #   Name              Type             Purpose
                    395: #   $Socket          IO::Socket::INET  Plaintext socket.
                    396: #
                    397: # Returns:
                    398: #    IDEA key on success.
                    399: #    undef on failure.
                    400: #
                    401: sub SSLConnection {
                    402:     my $Socket   = shift;
                    403: 
                    404:     Debug("SSLConnection: ");
                    405:     my $KeyFile         = lonssl::KeyFile();
                    406:     if(!$KeyFile) {
                    407: 	my $err = lonssl::LastError();
                    408: 	&logthis("<font color=\"red\"> CRITICAL"
                    409: 		 ."Can't get key file $err </font>");
                    410: 	return undef;
                    411:     }
                    412:     my ($CACertificate,
                    413: 	$Certificate) = lonssl::CertificateFile();
                    414: 
                    415: 
                    416:     # If any of the key, certificate or certificate authority 
                    417:     # certificate filenames are not defined, this can't work.
                    418: 
                    419:     if((!$Certificate) || (!$CACertificate)) {
                    420: 	my $err = lonssl::LastError();
                    421: 	&logthis("<font color=\"red\"> CRITICAL"
                    422: 		 ."Can't get certificates: $err </font>");
                    423: 
                    424: 	return undef;
                    425:     }
                    426:     Debug("Key: $KeyFile CA: $CACertificate Cert: $Certificate");
                    427: 
                    428:     # Indicate to our peer that we can procede with
                    429:     # a transition to ssl authentication:
                    430: 
                    431:     print $Socket "ok:ssl\n";
                    432: 
                    433:     Debug("Approving promotion -> ssl");
                    434:     #  And do so:
                    435: 
1.545     raeburn   436:     my $CRLFile;
                    437:     unless ($crlchecked{$clientname}) {
                    438:         $CRLFile = lonssl::CRLFile();
                    439:         $crlchecked{$clientname} = 1;
                    440:     }
                    441: 
1.200     matthew   442:     my $SSLSocket = lonssl::PromoteServerSocket($Socket,
                    443: 						$CACertificate,
                    444: 						$Certificate,
1.544     raeburn   445: 						$KeyFile,
1.545     raeburn   446: 						$clientname,
1.546     raeburn   447:                                                 $CRLFile,
                    448:                                                 $clientversion);
1.200     matthew   449:     if(! ($SSLSocket) ) {	# SSL socket promotion failed.
                    450: 	my $err = lonssl::LastError();
                    451: 	&logthis("<font color=\"red\"> CRITICAL "
                    452: 		 ."SSL Socket promotion failed: $err </font>");
                    453: 	return undef;
                    454:     }
                    455:     Debug("SSL Promotion successful");
                    456: 
                    457:     # 
                    458:     #  The only thing we'll use the socket for is to send the IDEA key
                    459:     #  to the peer:
                    460: 
                    461:     my $Key = lonlocal::CreateCipherKey();
                    462:     print $SSLSocket "$Key\n";
                    463: 
                    464:     lonssl::Close($SSLSocket); 
                    465: 
                    466:     Debug("Key exchange complete: $Key");
                    467: 
                    468:     return $Key;
                    469: }
                    470: #
                    471: #     InsecureConnection: 
                    472: #        If insecure connections are allowd,
                    473: #        exchange a challenge with the client to 'validate' the
                    474: #        client (not really, but that's the protocol):
                    475: #        We produce a challenge string that's sent to the client.
                    476: #        The client must then echo the challenge verbatim to us.
                    477: #
                    478: #  Parameter:
                    479: #      Socket      - Socket open on the client.
                    480: #  Returns:
                    481: #      1           - success.
                    482: #      0           - failure (e.g.mismatch or insecure not allowed).
                    483: #
                    484: sub InsecureConnection {
                    485:     my $Socket  =  shift;
                    486: 
                    487:     #   Don't even start if insecure connections are not allowed.
1.532     raeburn   488:     #   return 0 if Insecure connections not allowed.
                    489:     #
                    490:     if (ref($secureconf{'connfrom'}) eq 'HASH') {
                    491:         if ($clientsamedom) {
                    492:             if ($secureconf{'connfrom'}{'dom'} eq 'req') {
                    493:                 return 0;
                    494:             } 
                    495:         } elsif ($clientsameinst) {
                    496:             if ($secureconf{'connfrom'}{'intdom'} eq 'req') {
                    497:                 return 0;
                    498:             }
                    499:         } else {
                    500:             if ($secureconf{'connfrom'}{'other'} eq 'req') {
                    501:                 return 0;
                    502:             }
                    503:         }
                    504:     } elsif (!$perlvar{londAllowInsecure}) {
1.200     matthew   505: 	return 0;
                    506:     }
                    507: 
                    508:     #   Fabricate a challenge string and send it..
                    509: 
                    510:     my $challenge = "$$".time;	# pid + time.
                    511:     print $Socket "$challenge\n";
                    512:     &status("Waiting for challenge reply");
                    513: 
                    514:     my $answer = <$Socket>;
                    515:     $answer    =~s/\W//g;
                    516:     if($challenge eq $answer) {
                    517: 	return 1;
1.224     foxr      518:     } else {
1.200     matthew   519: 	logthis("<font color='blue'>WARNING client did not respond to challenge</font>");
                    520: 	&status("No challenge reqply");
                    521: 	return 0;
                    522:     }
                    523:     
                    524: 
                    525: }
1.251     foxr      526: #
                    527: #   Safely execute a command (as long as it's not a shel command and doesn
                    528: #   not require/rely on shell escapes.   The function operates by doing a
                    529: #   a pipe based fork and capturing stdout and stderr  from the pipe.
                    530: #
                    531: # Formal Parameters:
                    532: #     $line                    - A line of text to be executed as a command.
                    533: # Returns:
                    534: #     The output from that command.  If the output is multiline the caller
                    535: #     must know how to split up the output.
                    536: #
                    537: #
                    538: sub execute_command {
                    539:     my ($line)    = @_;
                    540:     my @words     = split(/\s/, $line);	# Bust the command up into words.
                    541:     my $output    = "";
                    542: 
                    543:     my $pid = open(CHILD, "-|");
                    544:     
                    545:     if($pid) {			# Parent process
                    546: 	Debug("In parent process for execute_command");
                    547: 	my @data = <CHILD>;	# Read the child's outupt...
                    548: 	close CHILD;
                    549: 	foreach my $output_line (@data) {
                    550: 	    Debug("Adding $output_line");
                    551: 	    $output .= $output_line; # Presumably has a \n on it.
                    552: 	}
                    553: 
                    554:     } else {			# Child process
                    555: 	close (STDERR);
                    556: 	open  (STDERR, ">&STDOUT");# Combine stderr, and stdout...
                    557: 	exec(@words);		# won't return.
                    558:     }
                    559:     return $output;
                    560: }
                    561: 
1.200     matthew   562: 
1.140     foxr      563: #   GetCertificate: Given a transaction that requires a certificate,
                    564: #   this function will extract the certificate from the transaction
                    565: #   request.  Note that at this point, the only concept of a certificate
                    566: #   is the hostname to which we are connected.
                    567: #
                    568: #   Parameter:
                    569: #      request   - The request sent by our client (this parameterization may
                    570: #                  need to change when we really use a certificate granting
                    571: #                  authority.
                    572: #
                    573: sub GetCertificate {
                    574:     my $request = shift;
                    575: 
                    576:     return $clientip;
                    577: }
1.161     foxr      578: 
1.178     foxr      579: #
                    580: #   Return true if client is a manager.
                    581: #
                    582: sub isManager {
                    583:     return (($ConnectionType eq "manager") || ($ConnectionType eq "both"));
                    584: }
                    585: #
                    586: #   Return tru if client can do client functions
                    587: #
                    588: sub isClient {
                    589:     return (($ConnectionType eq "client") || ($ConnectionType eq "both"));
                    590: }
1.161     foxr      591: 
                    592: 
1.156     foxr      593: #
                    594: #   ReadManagerTable: Reads in the current manager table. For now this is
                    595: #                     done on each manager authentication because:
                    596: #                     - These authentications are not frequent
                    597: #                     - This allows dynamic changes to the manager table
                    598: #                       without the need to signal to the lond.
                    599: #
                    600: sub ReadManagerTable {
                    601: 
1.412     foxr      602:     &Debug("Reading manager table");
1.156     foxr      603:     #   Clean out the old table first..
                    604: 
1.166     foxr      605:    foreach my $key (keys %managers) {
                    606:       delete $managers{$key};
                    607:    }
                    608: 
                    609:    my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
                    610:    if (!open (MANAGERS, $tablename)) {
1.473     raeburn   611:        my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
                    612:        if (&Apache::lonnet::is_LC_dns($hostname)) {
1.472     raeburn   613:            &logthis('<font color="red">No manager table.  Nobody can manage!!</font>');
                    614:        }
                    615:        return;
1.166     foxr      616:    }
                    617:    while(my $host = <MANAGERS>) {
                    618:       chomp($host);
                    619:       if ($host =~ "^#") {                  # Comment line.
                    620:          next;
                    621:       }
1.368     albertel  622:       if (!defined &Apache::lonnet::get_host_ip($host)) { # This is a non cluster member
1.161     foxr      623: 	    #  The entry is of the form:
                    624: 	    #    cluname:hostname
                    625: 	    #  cluname - A 'cluster hostname' is needed in order to negotiate
                    626: 	    #            the host key.
                    627: 	    #  hostname- The dns name of the host.
                    628: 	    #
1.166     foxr      629:           my($cluname, $dnsname) = split(/:/, $host);
                    630:           
                    631:           my $ip = gethostbyname($dnsname);
                    632:           if(defined($ip)) {                 # bad names don't deserve entry.
                    633:             my $hostip = inet_ntoa($ip);
                    634:             $managers{$hostip} = $cluname;
                    635:             logthis('<font color="green"> registering manager '.
                    636:                     "$dnsname as $cluname with $hostip </font>\n");
                    637:          }
                    638:       } else {
                    639:          logthis('<font color="green"> existing host'." $host</font>\n");
1.472     raeburn   640:          $managers{&Apache::lonnet::get_host_ip($host)} = $host;  # Use info from cluster tab if cluster memeber
1.166     foxr      641:       }
                    642:    }
1.156     foxr      643: }
1.140     foxr      644: 
                    645: #
                    646: #  ValidManager: Determines if a given certificate represents a valid manager.
                    647: #                in this primitive implementation, the 'certificate' is
                    648: #                just the connecting loncapa client name.  This is checked
                    649: #                against a valid client list in the configuration.
                    650: #
                    651: #                  
                    652: sub ValidManager {
                    653:     my $certificate = shift; 
                    654: 
1.163     foxr      655:     return isManager;
1.140     foxr      656: }
                    657: #
1.143     foxr      658: #  CopyFile:  Called as part of the process of installing a 
                    659: #             new configuration file.  This function copies an existing
                    660: #             file to a backup file.
                    661: # Parameters:
                    662: #     oldfile  - Name of the file to backup.
                    663: #     newfile  - Name of the backup file.
                    664: # Return:
                    665: #     0   - Failure (errno has failure reason).
                    666: #     1   - Success.
                    667: #
                    668: sub CopyFile {
1.192     foxr      669: 
                    670:     my ($oldfile, $newfile) = @_;
1.143     foxr      671: 
1.281     matthew   672:     if (! copy($oldfile,$newfile)) {
                    673:         return 0;
1.143     foxr      674:     }
1.281     matthew   675:     chmod(0660, $newfile);
                    676:     return 1;
1.143     foxr      677: }
1.157     foxr      678: #
                    679: #  Host files are passed out with externally visible host IPs.
                    680: #  If, for example, we are behind a fire-wall or NAT host, our 
                    681: #  internally visible IP may be different than the externally
                    682: #  visible IP.  Therefore, we always adjust the contents of the
                    683: #  host file so that the entry for ME is the IP that we believe
                    684: #  we have.  At present, this is defined as the entry that
                    685: #  DNS has for us.  If by some chance we are not able to get a
                    686: #  DNS translation for us, then we assume that the host.tab file
                    687: #  is correct.  
                    688: #    BUGBUGBUG - in the future, we really should see if we can
                    689: #       easily query the interface(s) instead.
                    690: # Parameter(s):
                    691: #     contents    - The contents of the host.tab to check.
                    692: # Returns:
                    693: #     newcontents - The adjusted contents.
                    694: #
                    695: #
                    696: sub AdjustHostContents {
                    697:     my $contents  = shift;
                    698:     my $adjusted;
                    699:     my $me        = $perlvar{'lonHostID'};
                    700: 
1.354     albertel  701:     foreach my $line (split(/\n/,$contents)) {
1.472     raeburn   702: 	if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/) ||
                    703:              ($line =~ /^\s*\^/))) {
1.157     foxr      704: 	    chomp($line);
                    705: 	    my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
                    706: 	    if ($id eq $me) {
1.354     albertel  707: 		my $ip = gethostbyname($name);
                    708: 		my $ipnew = inet_ntoa($ip);
                    709: 		$ip = $ipnew;
1.157     foxr      710: 		#  Reconstruct the host line and append to adjusted:
                    711: 		
1.354     albertel  712: 		my $newline = "$id:$domain:$role:$name:$ip";
                    713: 		if($maxcon ne "") { # Not all hosts have loncnew tuning params
                    714: 		    $newline .= ":$maxcon:$idleto:$mincon";
                    715: 		}
                    716: 		$adjusted .= $newline."\n";
1.157     foxr      717: 		
1.354     albertel  718: 	    } else {		# Not me, pass unmodified.
                    719: 		$adjusted .= $line."\n";
                    720: 	    }
1.157     foxr      721: 	} else {                  # Blank or comment never re-written.
                    722: 	    $adjusted .= $line."\n";	# Pass blanks and comments as is.
                    723: 	}
1.354     albertel  724:     }
                    725:     return $adjusted;
1.157     foxr      726: }
1.143     foxr      727: #
                    728: #   InstallFile: Called to install an administrative file:
1.412     foxr      729: #       - The file is created int a temp directory called <name>.tmp
                    730: #       - lcinstall file is called to install the file.
                    731: #         since the web app has no direct write access to the table directory
1.143     foxr      732: #
                    733: #  Parameters:
                    734: #       Name of the file
                    735: #       File Contents.
                    736: #  Return:
                    737: #      nonzero - success.
                    738: #      0       - failure and $! has an errno.
1.412     foxr      739: # Assumptions:
                    740: #    File installtion is a relatively infrequent
1.143     foxr      741: #
                    742: sub InstallFile {
1.192     foxr      743: 
                    744:     my ($Filename, $Contents) = @_;
1.412     foxr      745: #     my $TempFile = $Filename.".tmp";
                    746:     my $exedir = $perlvar{'lonDaemons'};
                    747:     my $tmpdir = $exedir.'/tmp/';
                    748:     my $TempFile = $tmpdir."TempTableFile.tmp";
1.143     foxr      749: 
                    750:     #  Open the file for write:
                    751: 
                    752:     my $fh = IO::File->new("> $TempFile"); # Write to temp.
                    753:     if(!(defined $fh)) {
                    754: 	&logthis('<font color="red"> Unable to create '.$TempFile."</font>");
                    755: 	return 0;
                    756:     }
                    757:     #  write the contents of the file:
                    758: 
                    759:     print $fh ($Contents); 
                    760:     $fh->close;			# In case we ever have a filesystem w. locking
                    761: 
1.412     foxr      762:     chmod(0664, $TempFile);	# Everyone can write it.
                    763: 
                    764:     # Use lcinstall file to put the file in the table directory...
                    765: 
                    766:     &Debug("Opening pipe to $exedir/lcinstallfile $TempFile $Filename");
                    767:     my $pf = IO::File->new("| $exedir/lcinstallfile   $TempFile $Filename > $exedir/logs/lcinstallfile.log");
                    768:     close $pf;
                    769:     my $err = $?;
                    770:     &Debug("Status is $err");
                    771:     if ($err != 0) {
                    772: 	my $msg = $err;
                    773: 	if ($err < @installerrors) {
                    774: 	    $msg = $installerrors[$err];
                    775: 	}
                    776: 	&logthis("Install failed for table file $Filename : $msg");
                    777: 	return 0;
                    778:     }
                    779: 
                    780:     # Remove the temp file:
1.143     foxr      781: 
1.412     foxr      782:     unlink($TempFile);
1.143     foxr      783: 
                    784:     return 1;
                    785: }
1.200     matthew   786: 
                    787: 
1.169     foxr      788: #
                    789: #   ConfigFileFromSelector: converts a configuration file selector
1.411     foxr      790: #                 into a configuration file pathname.
1.472     raeburn   791: #                 Supports the following file selectors: 
                    792: #                 hosts, domain, dns_hosts, dns_domain  
1.411     foxr      793: #
1.169     foxr      794: #
                    795: #  Parameters:
                    796: #      selector  - Configuration file selector.
                    797: #  Returns:
                    798: #      Full path to the file or undef if the selector is invalid.
                    799: #
                    800: sub ConfigFileFromSelector {
                    801:     my $selector   = shift;
                    802:     my $tablefile;
                    803: 
1.549     raeburn   804:     if ($selector eq 'loncapaCAcrl') {
                    805:         my $tabledir = $perlvar{'lonCertificateDirectory'};
                    806:         if (-d $tabledir) {
                    807:             $tablefile =  $tabledir.'/'.$selector.'.pem';
                    808:         }
                    809:     } else {
                    810:         my $tabledir = $perlvar{'lonTabDir'}.'/';
                    811:         if (($selector eq "hosts") || ($selector eq "domain") || 
                    812:             ($selector eq "dns_hosts") || ($selector eq "dns_domain")) {
                    813: 	    $tablefile =  $tabledir.$selector.'.tab';
                    814:         }
1.169     foxr      815:     }
                    816:     return $tablefile;
                    817: }
1.143     foxr      818: #
1.141     foxr      819: #   PushFile:  Called to do an administrative push of a file.
                    820: #              - Ensure the file being pushed is one we support.
                    821: #              - Backup the old file to <filename.saved>
                    822: #              - Separate the contents of the new file out from the
                    823: #                rest of the request.
                    824: #              - Write the new file.
                    825: #  Parameter:
                    826: #     Request - The entire user request.  This consists of a : separated
                    827: #               string pushfile:tablename:contents.
                    828: #     NOTE:  The contents may have :'s in it as well making things a bit
                    829: #            more interesting... but not much.
                    830: #  Returns:
                    831: #     String to send to client ("ok" or "refused" if bad file).
                    832: #
                    833: sub PushFile {
1.510     raeburn   834:     my $request = shift;
1.141     foxr      835:     my ($command, $filename, $contents) = split(":", $request, 3);
1.412     foxr      836:     &Debug("PushFile");
1.141     foxr      837:     
1.549     raeburn   838:     #  At this point in time, pushes for only the following tables and
                    839:     #  CRL file are supported:
1.141     foxr      840:     #   hosts.tab  ($filename eq host).
                    841:     #   domain.tab ($filename eq domain).
1.472     raeburn   842:     #   dns_hosts.tab ($filename eq dns_host).
1.554     raeburn   843:     #   dns_domain.tab ($filename eq dns_domain).
                    844:     #   loncapaCAcrl.pem ($filename eq loncapaCAcrl).
1.141     foxr      845:     # Construct the destination filename or reject the request.
                    846:     #
                    847:     # lonManage is supposed to ensure this, however this session could be
                    848:     # part of some elaborate spoof that managed somehow to authenticate.
                    849:     #
                    850: 
1.169     foxr      851: 
                    852:     my $tablefile = ConfigFileFromSelector($filename);
                    853:     if(! (defined $tablefile)) {
1.141     foxr      854: 	return "refused";
                    855:     }
1.412     foxr      856: 
1.157     foxr      857:     #  If the file being pushed is the host file, we adjust the entry for ourself so that the
                    858:     #  IP will be our current IP as looked up in dns.  Note this is only 99% good as it's possible
                    859:     #  to conceive of conditions where we don't have a DNS entry locally.  This is possible in a 
                    860:     #  network sense but it doesn't make much sense in a LonCAPA sense so we ignore (for now)
                    861:     #  that possibilty.
                    862: 
                    863:     if($filename eq "host") {
                    864: 	$contents = AdjustHostContents($contents);
1.549     raeburn   865:     } elsif (($filename eq 'dns_host') || ($filename eq 'dns_domain') ||
                    866:              ($filename eq 'loncapaCAcrl')) {
1.510     raeburn   867:         if ($contents eq '') {
                    868:             &logthis('<font color="red"> Pushfile: unable to install '
                    869:                     .$tablefile." - no data received from push. </font>");
                    870:             return 'error: push had no data';
                    871:         }
                    872:         if (&Apache::lonnet::get_host_ip($clientname)) {
                    873:             my $clienthost = &Apache::lonnet::hostname($clientname);
                    874:             if ($managers{$clientip} eq $clientname) {
                    875:                 my $clientprotocol = $Apache::lonnet::protocol{$clientname};
                    876:                 $clientprotocol = 'http' if ($clientprotocol ne 'https');
1.549     raeburn   877:                 my $url;
                    878:                 if ($filename eq 'loncapaCAcrl') {
                    879:                     $url = '/adm/dns/loncapaCRL';
                    880:                 } else {
                    881:                     $url = '/adm/'.$filename;
                    882:                     $url =~ s{_}{/};
                    883:                 }
1.510     raeburn   884:                 my $request=new HTTP::Request('GET',"$clientprotocol://$clienthost$url");
1.523     raeburn   885:                 my $response = LONCAPA::LWPReq::makerequest($clientname,$request,'',\%perlvar,60,0);
1.510     raeburn   886:                 if ($response->is_error()) {
                    887:                     &logthis('<font color="red"> Pushfile: unable to install '
                    888:                             .$tablefile." - error attempting to pull data. </font>");
                    889:                     return 'error: pull failed';
                    890:                 } else {
                    891:                     my $result = $response->content;
                    892:                     chomp($result);
                    893:                     unless ($result eq $contents) {
                    894:                         &logthis('<font color="red"> Pushfile: unable to install '
                    895:                                 .$tablefile." - pushed data and pulled data differ. </font>");
                    896:                         my $pushleng = length($contents);
                    897:                         my $pullleng = length($result);
                    898:                         if ($pushleng != $pullleng) {
                    899:                             return "error: $pushleng vs $pullleng bytes";
                    900:                         } else {
                    901:                             return "error: mismatch push and pull";
                    902:                         }
                    903:                     }
                    904:                 }
                    905:             }
                    906:         }
1.157     foxr      907:     }
                    908: 
1.141     foxr      909:     #  Install the new file:
                    910: 
1.412     foxr      911:     &logthis("Installing new $tablefile contents:\n$contents");
1.143     foxr      912:     if(!InstallFile($tablefile, $contents)) {
                    913: 	&logthis('<font color="red"> Pushfile: unable to install '
1.145     foxr      914: 	 .$tablefile." $! </font>");
1.143     foxr      915: 	return "error:$!";
1.224     foxr      916:     } else {
1.143     foxr      917: 	&logthis('<font color="green"> Installed new '.$tablefile
1.473     raeburn   918: 		 ." - transaction by: $clientname ($clientip)</font>");
1.472     raeburn   919:         my $adminmail = $perlvar{'lonAdmEMail'};
                    920:         my $admindom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                    921:         if ($admindom ne '') {
                    922:             my %domconfig =
                    923:                 &Apache::lonnet::get_dom('configuration',['contacts'],$admindom);
                    924:             if (ref($domconfig{'contacts'}) eq 'HASH') {
                    925:                 if ($domconfig{'contacts'}{'adminemail'} ne '') {
                    926:                     $adminmail = $domconfig{'contacts'}{'adminemail'};
                    927:                 }
                    928:             }
                    929:         }
                    930:         if ($adminmail =~ /^[^\@]+\@[^\@]+$/) {
                    931:             my $msg = new Mail::Send;
                    932:             $msg->to($adminmail);
                    933:             $msg->subject('LON-CAPA DNS update on '.$perlvar{'lonHostID'});
                    934:             $msg->add('Content-type','text/plain; charset=UTF-8');
                    935:             if (my $fh = $msg->open()) {
                    936:                 print $fh 'Update to '.$tablefile.' from Cluster Manager '.
1.473     raeburn   937:                           "$clientname ($clientip)\n";
1.472     raeburn   938:                 $fh->close;
                    939:             }
                    940:         }
1.143     foxr      941:     }
                    942: 
1.141     foxr      943:     #  Indicate success:
                    944:  
                    945:     return "ok";
                    946: 
                    947: }
1.145     foxr      948: 
                    949: #
                    950: #  Called to re-init either lonc or lond.
                    951: #
                    952: #  Parameters:
                    953: #    request   - The full request by the client.  This is of the form
                    954: #                reinit:<process>  
                    955: #                where <process> is allowed to be either of 
                    956: #                lonc or lond
                    957: #
                    958: #  Returns:
                    959: #     The string to be sent back to the client either:
                    960: #   ok         - Everything worked just fine.
                    961: #   error:why  - There was a failure and why describes the reason.
                    962: #
                    963: #
                    964: sub ReinitProcess {
                    965:     my $request = shift;
                    966: 
1.146     foxr      967: 
                    968:     # separate the request (reinit) from the process identifier and
                    969:     # validate it producing the name of the .pid file for the process.
                    970:     #
                    971:     #
                    972:     my ($junk, $process) = split(":", $request);
1.147     foxr      973:     my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
1.146     foxr      974:     if($process eq 'lonc') {
                    975: 	$processpidfile = $processpidfile."lonc.pid";
1.147     foxr      976: 	if (!open(PIDFILE, "< $processpidfile")) {
                    977: 	    return "error:Open failed for $processpidfile";
                    978: 	}
                    979: 	my $loncpid = <PIDFILE>;
                    980: 	close(PIDFILE);
                    981: 	logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
                    982: 		."</font>");
                    983: 	kill("USR2", $loncpid);
1.146     foxr      984:     } elsif ($process eq 'lond') {
1.147     foxr      985: 	logthis('<font color="red"> Reinitializing self (lond) </font>');
                    986: 	&UpdateHosts;			# Lond is us!!
1.146     foxr      987:     } else {
                    988: 	&logthis('<font color="yellow" Invalid reinit request for '.$process
                    989: 		 ."</font>");
                    990: 	return "error:Invalid process identifier $process";
                    991:     }
1.145     foxr      992:     return 'ok';
                    993: }
1.168     foxr      994: #   Validate a line in a configuration file edit script:
                    995: #   Validation includes:
                    996: #     - Ensuring the command is valid.
                    997: #     - Ensuring the command has sufficient parameters
                    998: #   Parameters:
                    999: #     scriptline - A line to validate (\n has been stripped for what it's worth).
1.167     foxr     1000: #
1.168     foxr     1001: #   Return:
                   1002: #      0     - Invalid scriptline.
                   1003: #      1     - Valid scriptline
                   1004: #  NOTE:
                   1005: #     Only the command syntax is checked, not the executability of the
                   1006: #     command.
                   1007: #
                   1008: sub isValidEditCommand {
                   1009:     my $scriptline = shift;
                   1010: 
                   1011:     #   Line elements are pipe separated:
                   1012: 
                   1013:     my ($command, $key, $newline)  = split(/\|/, $scriptline);
                   1014:     &logthis('<font color="green"> isValideditCommand checking: '.
                   1015: 	     "Command = '$command', Key = '$key', Newline = '$newline' </font>\n");
                   1016:     
                   1017:     if ($command eq "delete") {
                   1018: 	#
                   1019: 	#   key with no newline.
                   1020: 	#
                   1021: 	if( ($key eq "") || ($newline ne "")) {
                   1022: 	    return 0;		# Must have key but no newline.
                   1023: 	} else {
                   1024: 	    return 1;		# Valid syntax.
                   1025: 	}
1.169     foxr     1026:     } elsif ($command eq "replace") {
1.168     foxr     1027: 	#
                   1028: 	#   key and newline:
                   1029: 	#
                   1030: 	if (($key eq "") || ($newline eq "")) {
                   1031: 	    return 0;
                   1032: 	} else {
                   1033: 	    return 1;
                   1034: 	}
1.169     foxr     1035:     } elsif ($command eq "append") {
                   1036: 	if (($key ne "") && ($newline eq "")) {
                   1037: 	    return 1;
                   1038: 	} else {
                   1039: 	    return 0;
                   1040: 	}
1.168     foxr     1041:     } else {
                   1042: 	return 0;		# Invalid command.
                   1043:     }
                   1044:     return 0;			# Should not get here!!!
                   1045: }
1.169     foxr     1046: #
                   1047: #   ApplyEdit - Applies an edit command to a line in a configuration 
                   1048: #               file.  It is the caller's responsiblity to validate the
                   1049: #               edit line.
                   1050: #   Parameters:
                   1051: #      $directive - A single edit directive to apply.  
                   1052: #                   Edit directives are of the form:
                   1053: #                  append|newline      - Appends a new line to the file.
                   1054: #                  replace|key|newline - Replaces the line with key value 'key'
                   1055: #                  delete|key          - Deletes the line with key value 'key'.
                   1056: #      $editor   - A config file editor object that contains the
                   1057: #                  file being edited.
                   1058: #
                   1059: sub ApplyEdit {
1.192     foxr     1060: 
                   1061:     my ($directive, $editor) = @_;
1.169     foxr     1062: 
                   1063:     # Break the directive down into its command and its parameters
                   1064:     # (at most two at this point.  The meaning of the parameters, if in fact
                   1065:     #  they exist depends on the command).
                   1066: 
                   1067:     my ($command, $p1, $p2) = split(/\|/, $directive);
                   1068: 
                   1069:     if($command eq "append") {
                   1070: 	$editor->Append($p1);	          # p1 - key p2 null.
                   1071:     } elsif ($command eq "replace") {
                   1072: 	$editor->ReplaceLine($p1, $p2);   # p1 - key p2 = newline.
                   1073:     } elsif ($command eq "delete") {
                   1074: 	$editor->DeleteLine($p1);         # p1 - key p2 null.
                   1075:     } else {			          # Should not get here!!!
                   1076: 	die "Invalid command given to ApplyEdit $command"
                   1077:     }
                   1078: }
                   1079: #
                   1080: # AdjustOurHost:
                   1081: #           Adjusts a host file stored in a configuration file editor object
                   1082: #           for the true IP address of this host. This is necessary for hosts
                   1083: #           that live behind a firewall.
                   1084: #           Those hosts have a publicly distributed IP of the firewall, but
                   1085: #           internally must use their actual IP.  We assume that a given
                   1086: #           host only has a single IP interface for now.
                   1087: # Formal Parameters:
                   1088: #     editor   - The configuration file editor to adjust.  This
                   1089: #                editor is assumed to contain a hosts.tab file.
                   1090: # Strategy:
                   1091: #    - Figure out our hostname.
                   1092: #    - Lookup the entry for this host.
                   1093: #    - Modify the line to contain our IP
                   1094: #    - Do a replace for this host.
                   1095: sub AdjustOurHost {
                   1096:     my $editor        = shift;
                   1097: 
                   1098:     # figure out who I am.
                   1099: 
                   1100:     my $myHostName    = $perlvar{'lonHostID'}; # LonCAPA hostname.
                   1101: 
                   1102:     #  Get my host file entry.
                   1103: 
                   1104:     my $ConfigLine    = $editor->Find($myHostName);
                   1105:     if(! (defined $ConfigLine)) {
                   1106: 	die "AdjustOurHost - no entry for me in hosts file $myHostName";
                   1107:     }
                   1108:     # figure out my IP:
                   1109:     #   Use the config line to get my hostname.
                   1110:     #   Use gethostbyname to translate that into an IP address.
                   1111:     #
1.338     albertel 1112:     my ($id,$domain,$role,$name,$maxcon,$idleto,$mincon) = split(/:/,$ConfigLine);
1.169     foxr     1113:     #
                   1114:     #  Reassemble the config line from the elements in the list.
                   1115:     #  Note that if the loncnew items were not present before, they will
                   1116:     #  be now even if they would be empty
                   1117:     #
                   1118:     my $newConfigLine = $id;
1.338     albertel 1119:     foreach my $item ($domain, $role, $name, $maxcon, $idleto, $mincon) {
1.169     foxr     1120: 	$newConfigLine .= ":".$item;
                   1121:     }
                   1122:     #  Replace the line:
                   1123: 
                   1124:     $editor->ReplaceLine($id, $newConfigLine);
                   1125:     
                   1126: }
                   1127: #
                   1128: #   ReplaceConfigFile:
                   1129: #              Replaces a configuration file with the contents of a
                   1130: #              configuration file editor object.
                   1131: #              This is done by:
                   1132: #              - Copying the target file to <filename>.old
                   1133: #              - Writing the new file to <filename>.tmp
                   1134: #              - Moving <filename.tmp>  -> <filename>
                   1135: #              This laborious process ensures that the system is never without
                   1136: #              a configuration file that's at least valid (even if the contents
                   1137: #              may be dated).
                   1138: #   Parameters:
                   1139: #        filename   - Name of the file to modify... this is a full path.
                   1140: #        editor     - Editor containing the file.
                   1141: #
                   1142: sub ReplaceConfigFile {
1.192     foxr     1143:     
                   1144:     my ($filename, $editor) = @_;
1.168     foxr     1145: 
1.169     foxr     1146:     CopyFile ($filename, $filename.".old");
                   1147: 
                   1148:     my $contents  = $editor->Get(); # Get the contents of the file.
                   1149: 
                   1150:     InstallFile($filename, $contents);
                   1151: }
1.168     foxr     1152: #   
                   1153: #
                   1154: #   Called to edit a configuration table  file
1.167     foxr     1155: #   Parameters:
                   1156: #      request           - The entire command/request sent by lonc or lonManage
                   1157: #   Return:
                   1158: #      The reply to send to the client.
1.168     foxr     1159: #
1.167     foxr     1160: sub EditFile {
                   1161:     my $request = shift;
                   1162: 
                   1163:     #  Split the command into it's pieces:  edit:filetype:script
                   1164: 
1.339     albertel 1165:     my ($cmd, $filetype, $script) = split(/:/, $request,3);	# : in script
1.167     foxr     1166: 
                   1167:     #  Check the pre-coditions for success:
                   1168: 
1.339     albertel 1169:     if($cmd != "edit") {	# Something is amiss afoot alack.
1.167     foxr     1170: 	return "error:edit request detected, but request != 'edit'\n";
                   1171:     }
                   1172:     if( ($filetype ne "hosts")  &&
                   1173: 	($filetype ne "domain")) {
                   1174: 	return "error:edit requested with invalid file specifier: $filetype \n";
                   1175:     }
                   1176: 
                   1177:     #   Split the edit script and check it's validity.
1.168     foxr     1178: 
                   1179:     my @scriptlines = split(/\n/, $script);  # one line per element.
                   1180:     my $linecount   = scalar(@scriptlines);
                   1181:     for(my $i = 0; $i < $linecount; $i++) {
                   1182: 	chomp($scriptlines[$i]);
                   1183: 	if(!isValidEditCommand($scriptlines[$i])) {
                   1184: 	    return "error:edit with bad script line: '$scriptlines[$i]' \n";
                   1185: 	}
                   1186:     }
1.145     foxr     1187: 
1.167     foxr     1188:     #   Execute the edit operation.
1.169     foxr     1189:     #   - Create a config file editor for the appropriate file and 
                   1190:     #   - execute each command in the script:
                   1191:     #
                   1192:     my $configfile = ConfigFileFromSelector($filetype);
                   1193:     if (!(defined $configfile)) {
                   1194: 	return "refused\n";
                   1195:     }
                   1196:     my $editor = ConfigFileEdit->new($configfile);
1.167     foxr     1197: 
1.169     foxr     1198:     for (my $i = 0; $i < $linecount; $i++) {
                   1199: 	ApplyEdit($scriptlines[$i], $editor);
                   1200:     }
                   1201:     # If the file is the host file, ensure that our host is
                   1202:     # adjusted to have our ip:
                   1203:     #
                   1204:     if($filetype eq "host") {
                   1205: 	AdjustOurHost($editor);
                   1206:     }
                   1207:     #  Finally replace the current file with our file.
                   1208:     #
                   1209:     ReplaceConfigFile($configfile, $editor);
1.167     foxr     1210: 
                   1211:     return "ok\n";
                   1212: }
1.207     foxr     1213: 
1.255     foxr     1214: #   read_profile
                   1215: #
                   1216: #   Returns a set of specific entries from a user's profile file.
                   1217: #   this is a utility function that is used by both get_profile_entry and
                   1218: #   get_profile_entry_encrypted.
                   1219: #
                   1220: # Parameters:
                   1221: #    udom       - Domain in which the user exists.
                   1222: #    uname      - User's account name (loncapa account)
                   1223: #    namespace  - The profile namespace to open.
                   1224: #    what       - A set of & separated queries.
                   1225: # Returns:
                   1226: #    If all ok: - The string that needs to be shipped back to the user.
                   1227: #    If failure - A string that starts with error: followed by the failure
                   1228: #                 reason.. note that this probabyl gets shipped back to the
                   1229: #                 user as well.
                   1230: #
                   1231: sub read_profile {
                   1232:     my ($udom, $uname, $namespace, $what) = @_;
                   1233:     
                   1234:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   1235: 				 &GDBM_READER());
                   1236:     if ($hashref) {
                   1237:         my @queries=split(/\&/,$what);
1.440     raeburn  1238:         if ($namespace eq 'roles') {
                   1239:             @queries = map { &unescape($_); } @queries; 
                   1240:         }
1.255     foxr     1241:         my $qresult='';
                   1242: 	
                   1243: 	for (my $i=0;$i<=$#queries;$i++) {
                   1244: 	    $qresult.="$hashref->{$queries[$i]}&";    # Presumably failure gives empty string.
                   1245: 	}
                   1246: 	$qresult=~s/\&$//;              # Remove trailing & from last lookup.
1.311     albertel 1247: 	if (&untie_user_hash($hashref)) {
1.255     foxr     1248: 	    return $qresult;
                   1249: 	} else {
                   1250: 	    return "error: ".($!+0)." untie (GDBM) Failed";
                   1251: 	}
                   1252:     } else {
                   1253: 	if ($!+0 == 2) {
                   1254: 	    return "error:No such file or GDBM reported bad block error";
                   1255: 	} else {
                   1256: 	    return "error: ".($!+0)." tie (GDBM) Failed";
                   1257: 	}
                   1258:     }
                   1259: 
                   1260: }
1.214     foxr     1261: #--------------------- Request Handlers --------------------------------------------
                   1262: #
1.215     foxr     1263: #   By convention each request handler registers itself prior to the sub 
                   1264: #   declaration:
1.214     foxr     1265: #
                   1266: 
1.216     foxr     1267: #++
                   1268: #
1.214     foxr     1269: #  Handles ping requests.
                   1270: #  Parameters:
                   1271: #      $cmd    - the actual keyword that invoked us.
                   1272: #      $tail   - the tail of the request that invoked us.
                   1273: #      $replyfd- File descriptor connected to the client
                   1274: #  Implicit Inputs:
                   1275: #      $currenthostid - Global variable that carries the name of the host we are
                   1276: #                       known as.
                   1277: #  Returns:
                   1278: #      1       - Ok to continue processing.
                   1279: #      0       - Program should exit.
                   1280: #  Side effects:
                   1281: #      Reply information is sent to the client.
                   1282: sub ping_handler {
                   1283:     my ($cmd, $tail, $client) = @_;
                   1284:     Debug("$cmd $tail $client .. $currenthostid:");
                   1285:    
1.387     albertel 1286:     Reply( $client,\$currenthostid,"$cmd:$tail");
1.214     foxr     1287:    
                   1288:     return 1;
                   1289: }
                   1290: &register_handler("ping", \&ping_handler, 0, 1, 1);       # Ping unencoded, client or manager.
                   1291: 
1.216     foxr     1292: #++
1.215     foxr     1293: #
                   1294: # Handles pong requests.  Pong replies with our current host id, and
                   1295: #                         the results of a ping sent to us via our lonc.
                   1296: #
                   1297: # Parameters:
                   1298: #      $cmd    - the actual keyword that invoked us.
                   1299: #      $tail   - the tail of the request that invoked us.
                   1300: #      $replyfd- File descriptor connected to the client
                   1301: #  Implicit Inputs:
                   1302: #      $currenthostid - Global variable that carries the name of the host we are
                   1303: #                       connected to.
                   1304: #  Returns:
                   1305: #      1       - Ok to continue processing.
                   1306: #      0       - Program should exit.
                   1307: #  Side effects:
                   1308: #      Reply information is sent to the client.
                   1309: sub pong_handler {
                   1310:     my ($cmd, $tail, $replyfd) = @_;
                   1311: 
1.365     albertel 1312:     my $reply=&Apache::lonnet::reply("ping",$clientname);
1.215     foxr     1313:     &Reply( $replyfd, "$currenthostid:$reply\n", "$cmd:$tail"); 
                   1314:     return 1;
                   1315: }
                   1316: &register_handler("pong", \&pong_handler, 0, 1, 1);       # Pong unencoded, client or manager
                   1317: 
1.216     foxr     1318: #++
                   1319: #      Called to establish an encrypted session key with the remote client.
                   1320: #      Note that with secure lond, in most cases this function is never
                   1321: #      invoked.  Instead, the secure session key is established either
                   1322: #      via a local file that's locked down tight and only lives for a short
                   1323: #      time, or via an ssl tunnel...and is generated from a bunch-o-random
                   1324: #      bits from /dev/urandom, rather than the predictable pattern used by
                   1325: #      by this sub.  This sub is only used in the old-style insecure
                   1326: #      key negotiation.
                   1327: # Parameters:
                   1328: #      $cmd    - the actual keyword that invoked us.
                   1329: #      $tail   - the tail of the request that invoked us.
                   1330: #      $replyfd- File descriptor connected to the client
                   1331: #  Implicit Inputs:
                   1332: #      $currenthostid - Global variable that carries the name of the host
                   1333: #                       known as.
1.448     raeburn  1334: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.216     foxr     1335: #  Returns:
                   1336: #      1       - Ok to continue processing.
                   1337: #      0       - Program should exit.
                   1338: #  Implicit Outputs:
                   1339: #      Reply information is sent to the client.
                   1340: #      $cipher is set with a reference to a new IDEA encryption object.
                   1341: #
                   1342: sub establish_key_handler {
                   1343:     my ($cmd, $tail, $replyfd) = @_;
                   1344: 
                   1345:     my $buildkey=time.$$.int(rand 100000);
                   1346:     $buildkey=~tr/1-6/A-F/;
                   1347:     $buildkey=int(rand 100000).$buildkey.int(rand 100000);
                   1348:     my $key=$currenthostid.$clientname;
                   1349:     $key=~tr/a-z/A-Z/;
                   1350:     $key=~tr/G-P/0-9/;
                   1351:     $key=~tr/Q-Z/0-9/;
                   1352:     $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
                   1353:     $key=substr($key,0,32);
                   1354:     my $cipherkey=pack("H32",$key);
                   1355:     $cipher=new IDEA $cipherkey;
1.387     albertel 1356:     &Reply($replyfd, \$buildkey, "$cmd:$tail"); 
1.216     foxr     1357:    
                   1358:     return 1;
                   1359: 
                   1360: }
                   1361: &register_handler("ekey", \&establish_key_handler, 0, 1,1);
                   1362: 
1.217     foxr     1363: #     Handler for the load command.  Returns the current system load average
                   1364: #     to the requestor.
                   1365: #
                   1366: # Parameters:
                   1367: #      $cmd    - the actual keyword that invoked us.
                   1368: #      $tail   - the tail of the request that invoked us.
                   1369: #      $replyfd- File descriptor connected to the client
                   1370: #  Implicit Inputs:
                   1371: #      $currenthostid - Global variable that carries the name of the host
                   1372: #                       known as.
1.448     raeburn  1373: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.217     foxr     1374: #  Returns:
                   1375: #      1       - Ok to continue processing.
                   1376: #      0       - Program should exit.
                   1377: #  Side effects:
                   1378: #      Reply information is sent to the client.
                   1379: sub load_handler {
                   1380:     my ($cmd, $tail, $replyfd) = @_;
                   1381: 
1.463     foxr     1382: 
                   1383: 
1.217     foxr     1384:    # Get the load average from /proc/loadavg and calculate it as a percentage of
                   1385:    # the allowed load limit as set by the perl global variable lonLoadLim
                   1386: 
                   1387:     my $loadavg;
                   1388:     my $loadfile=IO::File->new('/proc/loadavg');
                   1389:    
                   1390:     $loadavg=<$loadfile>;
                   1391:     $loadavg =~ s/\s.*//g;                      # Extract the first field only.
                   1392:    
                   1393:     my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
                   1394: 
1.387     albertel 1395:     &Reply( $replyfd, \$loadpercent, "$cmd:$tail");
1.217     foxr     1396:    
                   1397:     return 1;
                   1398: }
1.263     albertel 1399: &register_handler("load", \&load_handler, 0, 1, 0);
1.217     foxr     1400: 
                   1401: #
                   1402: #   Process the userload request.  This sub returns to the client the current
                   1403: #  user load average.  It can be invoked either by clients or managers.
                   1404: #
                   1405: # Parameters:
                   1406: #      $cmd    - the actual keyword that invoked us.
                   1407: #      $tail   - the tail of the request that invoked us.
                   1408: #      $replyfd- File descriptor connected to the client
                   1409: #  Implicit Inputs:
                   1410: #      $currenthostid - Global variable that carries the name of the host
                   1411: #                       known as.
1.448     raeburn  1412: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.217     foxr     1413: #  Returns:
                   1414: #      1       - Ok to continue processing.
                   1415: #      0       - Program should exit
                   1416: # Implicit inputs:
                   1417: #     whatever the userload() function requires.
                   1418: #  Implicit outputs:
                   1419: #     the reply is written to the client.
                   1420: #
                   1421: sub user_load_handler {
                   1422:     my ($cmd, $tail, $replyfd) = @_;
                   1423: 
1.365     albertel 1424:     my $userloadpercent=&Apache::lonnet::userload();
1.387     albertel 1425:     &Reply($replyfd, \$userloadpercent, "$cmd:$tail");
1.217     foxr     1426:     
                   1427:     return 1;
                   1428: }
1.263     albertel 1429: &register_handler("userload", \&user_load_handler, 0, 1, 0);
1.217     foxr     1430: 
1.218     foxr     1431: #   Process a request for the authorization type of a user:
                   1432: #   (userauth).
                   1433: #
                   1434: # Parameters:
                   1435: #      $cmd    - the actual keyword that invoked us.
                   1436: #      $tail   - the tail of the request that invoked us.
                   1437: #      $replyfd- File descriptor connected to the client
                   1438: #  Returns:
                   1439: #      1       - Ok to continue processing.
                   1440: #      0       - Program should exit
                   1441: # Implicit outputs:
                   1442: #    The user authorization type is written to the client.
                   1443: #
                   1444: sub user_authorization_type {
                   1445:     my ($cmd, $tail, $replyfd) = @_;
                   1446:    
                   1447:     my $userinput = "$cmd:$tail";
                   1448:    
                   1449:     #  Pull the domain and username out of the command tail.
1.222     foxr     1450:     # and call get_auth_type to determine the authentication type.
1.218     foxr     1451:    
                   1452:     my ($udom,$uname)=split(/:/,$tail);
1.222     foxr     1453:     my $result = &get_auth_type($udom, $uname);
1.218     foxr     1454:     if($result eq "nouser") {
                   1455: 	&Failure( $replyfd, "unknown_user\n", $userinput);
                   1456:     } else {
                   1457: 	#
1.222     foxr     1458: 	# We only want to pass the second field from get_auth_type
1.218     foxr     1459: 	# for ^krb.. otherwise we'll be handing out the encrypted
                   1460: 	# password for internals e.g.
                   1461: 	#
                   1462: 	my ($type,$otherinfo) = split(/:/,$result);
                   1463: 	if($type =~ /^krb/) {
                   1464: 	    $type = $result;
1.269     raeburn  1465: 	} else {
                   1466:             $type .= ':';
                   1467:         }
1.387     albertel 1468: 	&Reply( $replyfd, \$type, $userinput);
1.218     foxr     1469:     }
                   1470:   
                   1471:     return 1;
                   1472: }
                   1473: &register_handler("currentauth", \&user_authorization_type, 1, 1, 0);
                   1474: 
                   1475: #   Process a request by a manager to push a hosts or domain table 
                   1476: #   to us.  We pick apart the command and pass it on to the subs
                   1477: #   that already exist to do this.
                   1478: #
                   1479: # Parameters:
                   1480: #      $cmd    - the actual keyword that invoked us.
                   1481: #      $tail   - the tail of the request that invoked us.
                   1482: #      $client - File descriptor connected to the client
                   1483: #  Returns:
                   1484: #      1       - Ok to continue processing.
                   1485: #      0       - Program should exit
                   1486: # Implicit Output:
                   1487: #    a reply is written to the client.
                   1488: sub push_file_handler {
                   1489:     my ($cmd, $tail, $client) = @_;
1.412     foxr     1490:     &Debug("In push file handler");
1.218     foxr     1491:     my $userinput = "$cmd:$tail";
                   1492: 
                   1493:     # At this time we only know that the IP of our partner is a valid manager
                   1494:     # the code below is a hook to do further authentication (e.g. to resolve
                   1495:     # spoofing).
                   1496: 
                   1497:     my $cert = &GetCertificate($userinput);
1.412     foxr     1498:     if(&ValidManager($cert)) {
                   1499: 	&Debug("Valid manager: $client");
1.218     foxr     1500: 
                   1501: 	# Now presumably we have the bona fides of both the peer host and the
                   1502: 	# process making the request.
                   1503:       
                   1504: 	my $reply = &PushFile($userinput);
1.387     albertel 1505: 	&Reply($client, \$reply, $userinput);
1.218     foxr     1506: 
                   1507:     } else {
1.412     foxr     1508: 	&logthis("push_file_handler $client is not valid");
1.218     foxr     1509: 	&Failure( $client, "refused\n", $userinput);
                   1510:     } 
1.219     foxr     1511:     return 1;
1.218     foxr     1512: }
                   1513: &register_handler("pushfile", \&push_file_handler, 1, 0, 1);
                   1514: 
1.399     raeburn  1515: # The du_handler routine should be considered obsolete and is retained
                   1516: # for communication with legacy servers.  Please see the du2_handler.
1.243     banghart 1517: #
1.399     raeburn  1518: #   du  - list the disk usage of a directory recursively. 
1.243     banghart 1519: #    
                   1520: #   note: stolen code from the ls file handler
                   1521: #   under construction by Rick Banghart 
                   1522: #    .
                   1523: # Parameters:
                   1524: #    $cmd        - The command that dispatched us (du).
                   1525: #    $ududir     - The directory path to list... I'm not sure what this
                   1526: #                  is relative as things like ls:. return e.g.
                   1527: #                  no_such_dir.
                   1528: #    $client     - Socket open on the client.
                   1529: # Returns:
                   1530: #     1 - indicating that the daemon should not disconnect.
                   1531: # Side Effects:
                   1532: #   The reply is written to  $client.
                   1533: #
                   1534: sub du_handler {
                   1535:     my ($cmd, $ududir, $client) = @_;
1.339     albertel 1536:     ($ududir) = split(/:/,$ududir); # Make 'telnet' testing easier.
1.251     foxr     1537:     my $userinput = "$cmd:$ududir";
                   1538: 
1.245     albertel 1539:     if ($ududir=~/\.\./ || $ududir!~m|^/home/httpd/|) {
                   1540: 	&Failure($client,"refused\n","$cmd:$ududir");
                   1541: 	return 1;
                   1542:     }
1.249     foxr     1543:     #  Since $ududir could have some nasties in it,
                   1544:     #  we will require that ududir is a valid
                   1545:     #  directory.  Just in case someone tries to
                   1546:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
                   1547:     #  etc.
                   1548:     #
                   1549:     if (-d $ududir) {
1.292     albertel 1550: 	my $total_size=0;
                   1551: 	my $code=sub { 
                   1552: 	    if ($_=~/\.\d+\./) { return;} 
                   1553: 	    if ($_=~/\.meta$/) { return;}
1.362     albertel 1554: 	    if (-d $_)         { return;}
1.292     albertel 1555: 	    $total_size+=(stat($_))[7];
                   1556: 	};
1.295     raeburn  1557: 	chdir($ududir);
1.292     albertel 1558: 	find($code,$ududir);
                   1559: 	$total_size=int($total_size/1024);
1.387     albertel 1560: 	&Reply($client,\$total_size,"$cmd:$ududir");
1.249     foxr     1561:     } else {
1.251     foxr     1562: 	&Failure($client, "bad_directory:$ududir\n","$cmd:$ududir"); 
1.249     foxr     1563:     }
1.243     banghart 1564:     return 1;
                   1565: }
                   1566: &register_handler("du", \&du_handler, 0, 1, 0);
1.218     foxr     1567: 
1.399     raeburn  1568: # Please also see the du_handler, which is obsoleted by du2. 
                   1569: # du2_handler differs from du_handler in that required path to directory
                   1570: # provided by &propath() is prepended in the handler instead of on the 
                   1571: # client side.
1.239     foxr     1572: #
1.399     raeburn  1573: #   du2  - list the disk usage of a directory recursively.
                   1574: #
                   1575: # Parameters:
                   1576: #    $cmd        - The command that dispatched us (du).
                   1577: #    $tail       - The tail of the request that invoked us.
                   1578: #                  $tail is a : separated list of the following:
                   1579: #                   - $ududir - directory path to list (before prepending)
                   1580: #                   - $getpropath = 1 if &propath() should prepend
                   1581: #                   - $uname - username to use for &propath or user dir
                   1582: #                   - $udom - domain to use for &propath or user dir
                   1583: #                   All are escaped.
                   1584: #    $client     - Socket open on the client.
                   1585: # Returns:
                   1586: #     1 - indicating that the daemon should not disconnect.
                   1587: # Side Effects:
                   1588: #   The reply is written to $client.
                   1589: #
                   1590: 
                   1591: sub du2_handler {
                   1592:     my ($cmd, $tail, $client) = @_;
                   1593:     my ($ududir,$getpropath,$uname,$udom) = map { &unescape($_) } (split(/:/, $tail));
                   1594:     my $userinput = "$cmd:$tail";
                   1595:     if (($ududir=~/\.\./) || (($ududir!~m|^/home/httpd/|) && (!$getpropath))) {
                   1596:         &Failure($client,"refused\n","$cmd:$tail");
                   1597:         return 1;
                   1598:     }
                   1599:     if ($getpropath) {
                   1600:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
                   1601:             $ududir = &propath($udom,$uname).'/'.$ududir;
                   1602:         } else {
                   1603:             &Failure($client,"refused\n","$cmd:$tail");
                   1604:             return 1;
                   1605:         }
                   1606:     }
                   1607:     #  Since $ududir could have some nasties in it,
                   1608:     #  we will require that ududir is a valid
                   1609:     #  directory.  Just in case someone tries to
                   1610:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
                   1611:     #  etc.
                   1612:     #
                   1613:     if (-d $ududir) {
                   1614:         my $total_size=0;
                   1615:         my $code=sub {
                   1616:             if ($_=~/\.\d+\./) { return;}
                   1617:             if ($_=~/\.meta$/) { return;}
                   1618:             if (-d $_)         { return;}
                   1619:             $total_size+=(stat($_))[7];
                   1620:         };
                   1621:         chdir($ududir);
                   1622:         find($code,$ududir);
                   1623:         $total_size=int($total_size/1024);
                   1624:         &Reply($client,\$total_size,"$cmd:$ududir");
                   1625:     } else {
                   1626:         &Failure($client, "bad_directory:$ududir\n","$cmd:$tail");
                   1627:     }
                   1628:     return 1;
                   1629: }
                   1630: &register_handler("du2", \&du2_handler, 0, 1, 0);
                   1631: 
                   1632: #
                   1633: # The ls_handler routine should be considered obsolete and is retained
                   1634: # for communication with legacy servers.  Please see the ls3_handler.
1.280     matthew  1635: #
1.239     foxr     1636: #   ls  - list the contents of a directory.  For each file in the
                   1637: #    selected directory the filename followed by the full output of
                   1638: #    the stat function is returned.  The returned info for each
                   1639: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1640: #
                   1641: #    If the requested path contains /../ or is:
                   1642: #
                   1643: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1644: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1645: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1646: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
                   1647: #    or is:
                   1648: #
1.538     raeburn  1649: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1650: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1651: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1652: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
1.529     raeburn  1653: #
                   1654: #    the response will be "refused".
                   1655: #
1.239     foxr     1656: # Parameters:
                   1657: #    $cmd        - The command that dispatched us (ls).
                   1658: #    $ulsdir     - The directory path to list... I'm not sure what this
                   1659: #                  is relative as things like ls:. return e.g.
                   1660: #                  no_such_dir.
                   1661: #    $client     - Socket open on the client.
                   1662: # Returns:
                   1663: #     1 - indicating that the daemon should not disconnect.
                   1664: # Side Effects:
                   1665: #   The reply is written to  $client.
                   1666: #
                   1667: sub ls_handler {
1.280     matthew  1668:     # obsoleted by ls2_handler
1.239     foxr     1669:     my ($cmd, $ulsdir, $client) = @_;
                   1670: 
                   1671:     my $userinput = "$cmd:$ulsdir";
                   1672: 
                   1673:     my $obs;
                   1674:     my $rights;
                   1675:     my $ulsout='';
                   1676:     my $ulsfn;
1.529     raeburn  1677:     if ($ulsdir =~m{/\.\./}) {
                   1678:         &Failure($client,"refused\n",$userinput);
                   1679:         return 1;
                   1680:     }
1.239     foxr     1681:     if (-e $ulsdir) {
                   1682: 	if(-d $ulsdir) {
1.539     raeburn  1683:             unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1684:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
1.529     raeburn  1685:                 &Failure($client,"refused\n",$userinput);
                   1686:                 return 1;
                   1687:             }
1.239     foxr     1688: 	    if (opendir(LSDIR,$ulsdir)) {
                   1689: 		while ($ulsfn=readdir(LSDIR)) {
1.291     albertel 1690: 		    undef($obs);
                   1691: 		    undef($rights); 
1.239     foxr     1692: 		    my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1693: 		    #We do some obsolete checking here
                   1694: 		    if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   1695: 			open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1696: 			my @obsolete=<FILE>;
                   1697: 			foreach my $obsolete (@obsolete) {
1.301     www      1698: 			    if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
1.239     foxr     1699: 			    if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
                   1700: 			}
                   1701: 		    }
                   1702: 		    $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
                   1703: 		    if($obs eq '1') { $ulsout.="&1"; }
                   1704: 		    else { $ulsout.="&0"; }
                   1705: 		    if($rights eq '1') { $ulsout.="&1:"; }
                   1706: 		    else { $ulsout.="&0:"; }
                   1707: 		}
                   1708: 		closedir(LSDIR);
                   1709: 	    }
                   1710: 	} else {
1.539     raeburn  1711:             unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1712:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
1.529     raeburn  1713:                 &Failure($client,"refused\n",$userinput);
                   1714:                 return 1;
                   1715:             }
1.239     foxr     1716: 	    my @ulsstats=stat($ulsdir);
                   1717: 	    $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1718: 	}
                   1719:     } else {
                   1720: 	$ulsout='no_such_dir';
                   1721:     }
                   1722:     if ($ulsout eq '') { $ulsout='empty'; }
1.387     albertel 1723:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1.239     foxr     1724:     
                   1725:     return 1;
                   1726: 
                   1727: }
                   1728: &register_handler("ls", \&ls_handler, 0, 1, 0);
                   1729: 
1.399     raeburn  1730: # The ls2_handler routine should be considered obsolete and is retained
                   1731: # for communication with legacy servers.  Please see the ls3_handler.
                   1732: # Please also see the ls_handler, which was itself obsoleted by ls2.
1.280     matthew  1733: # ls2_handler differs from ls_handler in that it escapes its return 
                   1734: # values before concatenating them together with ':'s.
                   1735: #
                   1736: #   ls2  - list the contents of a directory.  For each file in the
                   1737: #    selected directory the filename followed by the full output of
                   1738: #    the stat function is returned.  The returned info for each
                   1739: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1740: #
                   1741: #    If the requested path contains /../ or is:
                   1742: #
                   1743: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1744: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1745: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1746: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
                   1747: #    or is:
                   1748: #
1.538     raeburn  1749: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1750: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1751: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1752: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
1.529     raeburn  1753: #
                   1754: #    the response will be "refused".
                   1755: #
1.280     matthew  1756: # Parameters:
                   1757: #    $cmd        - The command that dispatched us (ls).
                   1758: #    $ulsdir     - The directory path to list... I'm not sure what this
                   1759: #                  is relative as things like ls:. return e.g.
                   1760: #                  no_such_dir.
                   1761: #    $client     - Socket open on the client.
                   1762: # Returns:
                   1763: #     1 - indicating that the daemon should not disconnect.
                   1764: # Side Effects:
                   1765: #   The reply is written to  $client.
                   1766: #
                   1767: sub ls2_handler {
                   1768:     my ($cmd, $ulsdir, $client) = @_;
                   1769: 
                   1770:     my $userinput = "$cmd:$ulsdir";
                   1771: 
                   1772:     my $obs;
                   1773:     my $rights;
                   1774:     my $ulsout='';
                   1775:     my $ulsfn;
1.529     raeburn  1776:     if ($ulsdir =~m{/\.\./}) {
                   1777:         &Failure($client,"refused\n",$userinput);
                   1778:         return 1;
                   1779:     }
1.280     matthew  1780:     if (-e $ulsdir) {
                   1781:         if(-d $ulsdir) {
1.539     raeburn  1782:             unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1783:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
1.529     raeburn  1784:                 &Failure($client,"refused\n","$userinput");
                   1785:                 return 1;
                   1786:             }
1.280     matthew  1787:             if (opendir(LSDIR,$ulsdir)) {
                   1788:                 while ($ulsfn=readdir(LSDIR)) {
1.291     albertel 1789:                     undef($obs);
                   1790: 		    undef($rights); 
1.280     matthew  1791:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1792:                     #We do some obsolete checking here
                   1793:                     if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   1794:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1795:                         my @obsolete=<FILE>;
                   1796:                         foreach my $obsolete (@obsolete) {
1.301     www      1797:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
1.280     matthew  1798:                             if($obsolete =~ m|(<copyright>)(default)|) {
                   1799:                                 $rights = 1;
                   1800:                             }
                   1801:                         }
                   1802:                     }
                   1803:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
                   1804:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1805:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1806:                     $ulsout.= &escape($tmp).':';
                   1807:                 }
                   1808:                 closedir(LSDIR);
                   1809:             }
                   1810:         } else {
1.539     raeburn  1811:             unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1812:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
1.529     raeburn  1813:                 &Failure($client,"refused\n",$userinput);
                   1814:                 return 1;
                   1815:             }
1.280     matthew  1816:             my @ulsstats=stat($ulsdir);
                   1817:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1818:         }
                   1819:     } else {
                   1820:         $ulsout='no_such_dir';
                   1821:    }
                   1822:    if ($ulsout eq '') { $ulsout='empty'; }
1.387     albertel 1823:    &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1.280     matthew  1824:    return 1;
                   1825: }
                   1826: &register_handler("ls2", \&ls2_handler, 0, 1, 0);
1.399     raeburn  1827: #
                   1828: #   ls3  - list the contents of a directory.  For each file in the
                   1829: #    selected directory the filename followed by the full output of
                   1830: #    the stat function is returned.  The returned info for each
                   1831: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1832: #
                   1833: #    If the requested path (after prepending) contains /../ or is:
                   1834: #
                   1835: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1836: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1837: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1838: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
1.539     raeburn  1839: #        (d) /home/httpd/html/priv/<domain> and client is the homeserver
1.529     raeburn  1840: #
1.530     raeburn  1841: #    or is:
1.529     raeburn  1842: #
1.538     raeburn  1843: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1844: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1845: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1846: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
                   1847: #        (d) /home/httpd/html/priv/<domain>/<username>/ and client is the homeserver
1.529     raeburn  1848: #
                   1849: #    the response will be "refused".
                   1850: #
1.399     raeburn  1851: # Parameters:
                   1852: #    $cmd        - The command that dispatched us (ls).
                   1853: #    $tail       - The tail of the request that invoked us.
                   1854: #                  $tail is a : separated list of the following:
                   1855: #                   - $ulsdir - directory path to list (before prepending)
                   1856: #                   - $getpropath = 1 if &propath() should prepend
                   1857: #                   - $getuserdir = 1 if path to user dir in lonUsers should
                   1858: #                                     prepend
                   1859: #                   - $alternate_root - path to prepend
                   1860: #                   - $uname - username to use for &propath or user dir
                   1861: #                   - $udom - domain to use for &propath or user dir
                   1862: #            All of these except $getpropath and &getuserdir are escaped.    
                   1863: #                  no_such_dir.
                   1864: #    $client     - Socket open on the client.
                   1865: # Returns:
                   1866: #     1 - indicating that the daemon should not disconnect.
                   1867: # Side Effects:
                   1868: #   The reply is written to $client.
                   1869: #
                   1870: 
                   1871: sub ls3_handler {
                   1872:     my ($cmd, $tail, $client) = @_;
                   1873:     my $userinput = "$cmd:$tail";
                   1874:     my ($ulsdir,$getpropath,$getuserdir,$alternate_root,$uname,$udom) =
                   1875:         split(/:/,$tail);
                   1876:     if (defined($ulsdir)) {
                   1877:         $ulsdir = &unescape($ulsdir);
                   1878:     }
                   1879:     if (defined($alternate_root)) {
                   1880:         $alternate_root = &unescape($alternate_root);
                   1881:     }
                   1882:     if (defined($uname)) {
                   1883:         $uname = &unescape($uname);
                   1884:     }
                   1885:     if (defined($udom)) {
                   1886:         $udom = &unescape($udom);
                   1887:     }
                   1888: 
                   1889:     my $dir_root = $perlvar{'lonDocRoot'};
1.529     raeburn  1890:     if (($getpropath) || ($getuserdir)) {
1.399     raeburn  1891:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
                   1892:             $dir_root = &propath($udom,$uname);
                   1893:             $dir_root =~ s/\/$//;
                   1894:         } else {
1.529     raeburn  1895:             &Failure($client,"refused\n",$userinput);
1.399     raeburn  1896:             return 1;
                   1897:         }
1.400     raeburn  1898:     } elsif ($alternate_root ne '') {
1.399     raeburn  1899:         $dir_root = $alternate_root;
                   1900:     }
1.408     raeburn  1901:     if (($dir_root ne '') && ($dir_root ne '/')) {
1.400     raeburn  1902:         if ($ulsdir =~ /^\//) {
                   1903:             $ulsdir = $dir_root.$ulsdir;
                   1904:         } else {
                   1905:             $ulsdir = $dir_root.'/'.$ulsdir;
                   1906:         }
1.399     raeburn  1907:     }
1.529     raeburn  1908:     if ($ulsdir =~m{/\.\./}) {
                   1909:         &Failure($client,"refused\n",$userinput);
                   1910:         return 1;
                   1911:     }
                   1912:     my $islocal;
                   1913:     my @machine_ids = &Apache::lonnet::current_machine_ids();
                   1914:     if (grep(/^\Q$clientname\E$/,@machine_ids)) {
                   1915:         $islocal = 1;
                   1916:     }
1.399     raeburn  1917:     my $obs;
                   1918:     my $rights;
                   1919:     my $ulsout='';
                   1920:     my $ulsfn;
1.547     raeburn  1921: 
                   1922:     my ($crscheck,$toplevel,$currdom,$currnum,$skip);
                   1923:     unless ($islocal) {
                   1924:         my ($major,$minor) = split(/\./,$clientversion);
                   1925:         if (($major < 2) || ($major == 2 && $minor < 12)) {
                   1926:             $crscheck = 1;
                   1927:         }
                   1928:     }
1.399     raeburn  1929:     if (-e $ulsdir) {
                   1930:         if(-d $ulsdir) {
1.529     raeburn  1931:             unless (($getpropath) || ($getuserdir) ||
1.539     raeburn  1932:                     ($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1933:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles}) ||
                   1934:                     (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain}) && ($islocal))) {
1.529     raeburn  1935:                 &Failure($client,"refused\n",$userinput);
                   1936:                 return 1;
                   1937:             }
1.547     raeburn  1938:             if (($crscheck) &&
                   1939:                 ($ulsdir =~ m{^/home/httpd/html/res/($LONCAPA::match_domain)(/?$|/$LONCAPA::match_courseid)})) {
                   1940:                 ($currdom,my $posscnum) = ($1,$2);
                   1941:                 if (($posscnum eq '') || ($posscnum eq '/')) {
                   1942:                     $toplevel = 1;
                   1943:                 } else {
                   1944:                     $posscnum =~ s{^/+}{};
                   1945:                     if (&LONCAPA::Lond::is_course($currdom,$posscnum)) {
                   1946:                         $skip = 1;
                   1947:                     }
                   1948:                 }
                   1949:             }
                   1950:             if ((!$skip) && (opendir(LSDIR,$ulsdir))) {
1.399     raeburn  1951:                 while ($ulsfn=readdir(LSDIR)) {
1.547     raeburn  1952:                     if (($crscheck) && ($toplevel) && ($currdom ne '') &&
                   1953:                         ($ulsfn =~ /^$LONCAPA::match_courseid$/) && (-d "$ulsdir/$ulsfn")) {
                   1954:                         if (&LONCAPA::Lond::is_course($currdom,$ulsfn)) {
                   1955:                             next;
                   1956:                         }
                   1957:                     }
1.399     raeburn  1958:                     undef($obs);
                   1959:                     undef($rights);
                   1960:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1961:                     #We do some obsolete checking here
                   1962:                     if(-e $ulsdir.'/'.$ulsfn.".meta") {
                   1963:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1964:                         my @obsolete=<FILE>;
                   1965:                         foreach my $obsolete (@obsolete) {
                   1966:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; }
                   1967:                             if($obsolete =~ m|(<copyright>)(default)|) {
                   1968:                                 $rights = 1;
                   1969:                             }
                   1970:                         }
                   1971:                     }
                   1972:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
                   1973:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1974:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1975:                     $ulsout.= &escape($tmp).':';
                   1976:                 }
                   1977:                 closedir(LSDIR);
                   1978:             }
                   1979:         } else {
1.529     raeburn  1980:             unless (($getpropath) || ($getuserdir) ||
1.539     raeburn  1981:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1982:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/}) ||
                   1983:                     (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain/$LONCAPA::match_name/}) && ($islocal))) {
1.529     raeburn  1984:                 &Failure($client,"refused\n",$userinput);
                   1985:                 return 1;
                   1986:             }
1.399     raeburn  1987:             my @ulsstats=stat($ulsdir);
                   1988:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1989:         }
                   1990:     } else {
                   1991:         $ulsout='no_such_dir';
1.400     raeburn  1992:     }
                   1993:     if ($ulsout eq '') { $ulsout='empty'; }
                   1994:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
                   1995:     return 1;
1.399     raeburn  1996: }
                   1997: &register_handler("ls3", \&ls3_handler, 0, 1, 0);
1.280     matthew  1998: 
1.477     raeburn  1999: sub read_lonnet_global {
                   2000:     my ($cmd,$tail,$client) = @_;
                   2001:     my $userinput = "$cmd:$tail";
                   2002:     my $requested = &Apache::lonnet::thaw_unescape($tail);
                   2003:     my $result;
1.480     raeburn  2004:     my %packagevars = (
                   2005:                         spareid => \%Apache::lonnet::spareid,
                   2006:                         perlvar => \%Apache::lonnet::perlvar,
                   2007:                       );
                   2008:     my %limit_to = (
                   2009:                     perlvar => {
1.531     raeburn  2010:                                  lonOtherAuthen  => 1,
                   2011:                                  lonBalancer     => 1,
                   2012:                                  lonVersion      => 1,
                   2013:                                  lonAdmEMail     => 1,
                   2014:                                  lonSupportEMail => 1,  
                   2015:                                  lonSysEMail     => 1,
                   2016:                                  lonHostID       => 1,
                   2017:                                  lonRole         => 1,
                   2018:                                  lonDefDomain    => 1,
                   2019:                                  lonLoadLim      => 1,
                   2020:                                  lonUserLoadLim  => 1,
1.480     raeburn  2021:                                }
                   2022:                   );
1.477     raeburn  2023:     if (ref($requested) eq 'HASH') {
                   2024:         foreach my $what (keys(%{$requested})) {
                   2025:             my $response;
1.480     raeburn  2026:             my $items = {};
                   2027:             if (exists($packagevars{$what})) {
                   2028:                 if (ref($limit_to{$what}) eq 'HASH') {
                   2029:                     foreach my $varname (keys(%{$packagevars{$what}})) {
                   2030:                         if ($limit_to{$what}{$varname}) {
                   2031:                             $items->{$varname} = $packagevars{$what}{$varname};
                   2032:                         }
                   2033:                     }
                   2034:                 } else {
                   2035:                     $items = $packagevars{$what};
1.477     raeburn  2036:                 }
1.480     raeburn  2037:                 if ($what eq 'perlvar') {
                   2038:                     if (!exists($packagevars{$what}{'lonBalancer'})) {
1.559     raeburn  2039:                         if ($dist =~ /^(centos|rhes|fedora|scientific|oracle)/) {
1.480     raeburn  2040:                             my $othervarref=LONCAPA::Configuration::read_conf('httpd.conf');
                   2041:                             if (ref($othervarref) eq 'HASH') {
                   2042:                                 $items->{'lonBalancer'} = $othervarref->{'lonBalancer'};
                   2043:                             }
                   2044:                         }
                   2045:                     }
1.477     raeburn  2046:                 }
1.480     raeburn  2047:                 $response = &Apache::lonnet::freeze_escape($items);
1.477     raeburn  2048:             }
1.478     raeburn  2049:             $result .= &escape($what).'='.$response.'&';
1.477     raeburn  2050:         }
                   2051:     }
                   2052:     $result =~ s/\&$//;
                   2053:     &Reply($client,\$result,$userinput);
                   2054:     return 1;
                   2055: }
                   2056: &register_handler("readlonnetglobal", \&read_lonnet_global, 0, 1, 0);
                   2057: 
1.479     raeburn  2058: sub server_devalidatecache_handler {
                   2059:     my ($cmd,$tail,$client) = @_;
                   2060:     my $userinput = "$cmd:$tail";
1.503     raeburn  2061:     my $items = &unescape($tail);
                   2062:     my @cached = split(/\&/,$items);
                   2063:     foreach my $key (@cached) {
                   2064:         if ($key =~ /:/) {
                   2065:             my ($name,$id) = map { &unescape($_); } split(/:/,$key);
                   2066:             &Apache::lonnet::devalidate_cache_new($name,$id);
                   2067:         }
                   2068:     }
1.479     raeburn  2069:     my $result = 'ok';
                   2070:     &Reply($client,\$result,$userinput);
                   2071:     return 1;
                   2072: }
1.481     raeburn  2073: &register_handler("devalidatecache", \&server_devalidatecache_handler, 0, 1, 0);
1.479     raeburn  2074: 
1.410     raeburn  2075: sub server_timezone_handler {
                   2076:     my ($cmd,$tail,$client) = @_;
                   2077:     my $userinput = "$cmd:$tail";
                   2078:     my $timezone;
                   2079:     my $clockfile = '/etc/sysconfig/clock'; # Fedora/CentOS/SuSE
                   2080:     my $tzfile = '/etc/timezone'; # Debian/Ubuntu
                   2081:     if (-e $clockfile) {
                   2082:         if (open(my $fh,"<$clockfile")) {
                   2083:             while (<$fh>) {
                   2084:                 next if (/^[\#\s]/);
                   2085:                 if (/^(?:TIME)?ZONE\s*=\s*['"]?\s*([\w\/]+)/) {
                   2086:                     $timezone = $1;
                   2087:                     last;
                   2088:                 }
                   2089:             }
                   2090:             close($fh);
                   2091:         }
                   2092:     } elsif (-e $tzfile) {
                   2093:         if (open(my $fh,"<$tzfile")) {
                   2094:             $timezone = <$fh>;
                   2095:             close($fh);
                   2096:             chomp($timezone);
                   2097:             if ($timezone =~ m{^Etc/(\w+)$}) {
                   2098:                 $timezone = $1;
                   2099:             }
                   2100:         }
                   2101:     }
                   2102:     &Reply($client,\$timezone,$userinput); # This supports debug logging.
                   2103:     return 1;
                   2104: }
                   2105: &register_handler("servertimezone", \&server_timezone_handler, 0, 1, 0);
                   2106: 
1.413     raeburn  2107: sub server_loncaparev_handler {
                   2108:     my ($cmd,$tail,$client) = @_;
                   2109:     my $userinput = "$cmd:$tail";
                   2110:     &Reply($client,\$perlvar{'lonVersion'},$userinput);
                   2111:     return 1;
                   2112: }
                   2113: &register_handler("serverloncaparev", \&server_loncaparev_handler, 0, 1, 0);
                   2114: 
1.448     raeburn  2115: sub server_homeID_handler {
                   2116:     my ($cmd,$tail,$client) = @_;
                   2117:     my $userinput = "$cmd:$tail";
                   2118:     &Reply($client,\$perlvar{'lonHostID'},$userinput);
                   2119:     return 1;
                   2120: }
                   2121: &register_handler("serverhomeID", \&server_homeID_handler, 0, 1, 0);
                   2122: 
1.471     raeburn  2123: sub server_distarch_handler {
                   2124:     my ($cmd,$tail,$client) = @_;
                   2125:     my $userinput = "$cmd:$tail";
                   2126:     my $reply = &distro_and_arch();
                   2127:     &Reply($client,\$reply,$userinput);
                   2128:     return 1;
                   2129: }
                   2130: &register_handler("serverdistarch", \&server_distarch_handler, 0, 1, 0);
                   2131: 
1.523     raeburn  2132: sub server_certs_handler {
                   2133:     my ($cmd,$tail,$client) = @_;
                   2134:     my $userinput = "$cmd:$tail";
1.548     raeburn  2135:     my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
                   2136:     my $result = &LONCAPA::Lond::server_certs(\%perlvar,$perlvar{'lonHostID'},$hostname);
1.523     raeburn  2137:     &Reply($client,\$result,$userinput);
                   2138:     return;
                   2139: }
                   2140: &register_handler("servercerts", \&server_certs_handler, 0, 1, 0);
                   2141: 
1.218     foxr     2142: #   Process a reinit request.  Reinit requests that either
                   2143: #   lonc or lond be reinitialized so that an updated 
                   2144: #   host.tab or domain.tab can be processed.
                   2145: #
                   2146: # Parameters:
                   2147: #      $cmd    - the actual keyword that invoked us.
                   2148: #      $tail   - the tail of the request that invoked us.
                   2149: #      $client - File descriptor connected to the client
                   2150: #  Returns:
                   2151: #      1       - Ok to continue processing.
                   2152: #      0       - Program should exit
                   2153: #  Implicit output:
                   2154: #     a reply is sent to the client.
                   2155: #
                   2156: sub reinit_process_handler {
                   2157:     my ($cmd, $tail, $client) = @_;
                   2158:    
                   2159:     my $userinput = "$cmd:$tail";
                   2160:    
                   2161:     my $cert = &GetCertificate($userinput);
                   2162:     if(&ValidManager($cert)) {
                   2163: 	chomp($userinput);
                   2164: 	my $reply = &ReinitProcess($userinput);
1.387     albertel 2165: 	&Reply( $client,  \$reply, $userinput);
1.218     foxr     2166:     } else {
                   2167: 	&Failure( $client, "refused\n", $userinput);
                   2168:     }
                   2169:     return 1;
                   2170: }
                   2171: &register_handler("reinit", \&reinit_process_handler, 1, 0, 1);
                   2172: 
                   2173: #  Process the editing script for a table edit operation.
                   2174: #  the editing operation must be encrypted and requested by
                   2175: #  a manager host.
                   2176: #
                   2177: # Parameters:
                   2178: #      $cmd    - the actual keyword that invoked us.
                   2179: #      $tail   - the tail of the request that invoked us.
                   2180: #      $client - File descriptor connected to the client
                   2181: #  Returns:
                   2182: #      1       - Ok to continue processing.
                   2183: #      0       - Program should exit
                   2184: #  Implicit output:
                   2185: #     a reply is sent to the client.
                   2186: #
                   2187: sub edit_table_handler {
                   2188:     my ($command, $tail, $client) = @_;
                   2189:    
                   2190:     my $userinput = "$command:$tail";
                   2191: 
                   2192:     my $cert = &GetCertificate($userinput);
                   2193:     if(&ValidManager($cert)) {
                   2194: 	my($filetype, $script) = split(/:/, $tail);
                   2195: 	if (($filetype eq "hosts") || 
                   2196: 	    ($filetype eq "domain")) {
                   2197: 	    if($script ne "") {
                   2198: 		&Reply($client,              # BUGBUG - EditFile
                   2199: 		      &EditFile($userinput), #   could fail.
                   2200: 		      $userinput);
                   2201: 	    } else {
                   2202: 		&Failure($client,"refused\n",$userinput);
                   2203: 	    }
                   2204: 	} else {
                   2205: 	    &Failure($client,"refused\n",$userinput);
                   2206: 	}
                   2207:     } else {
                   2208: 	&Failure($client,"refused\n",$userinput);
                   2209:     }
                   2210:     return 1;
                   2211: }
1.263     albertel 2212: &register_handler("edit", \&edit_table_handler, 1, 0, 1);
1.218     foxr     2213: 
1.220     foxr     2214: #
                   2215: #   Authenticate a user against the LonCAPA authentication
                   2216: #   database.  Note that there are several authentication
                   2217: #   possibilities:
                   2218: #   - unix     - The user can be authenticated against the unix
                   2219: #                password file.
                   2220: #   - internal - The user can be authenticated against a purely 
                   2221: #                internal per user password file.
                   2222: #   - kerberos - The user can be authenticated against either a kerb4 or kerb5
                   2223: #                ticket granting authority.
                   2224: #   - user     - The person tailoring LonCAPA can supply a user authentication
                   2225: #                mechanism that is per system.
                   2226: #
                   2227: # Parameters:
                   2228: #    $cmd      - The command that got us here.
                   2229: #    $tail     - Tail of the command (remaining parameters).
                   2230: #    $client   - File descriptor connected to client.
                   2231: # Returns
                   2232: #     0        - Requested to exit, caller should shut down.
                   2233: #     1        - Continue processing.
                   2234: # Implicit inputs:
                   2235: #    The authentication systems describe above have their own forms of implicit
                   2236: #    input into the authentication process that are described above.
                   2237: #
                   2238: sub authenticate_handler {
                   2239:     my ($cmd, $tail, $client) = @_;
                   2240: 
                   2241:     
                   2242:     #  Regenerate the full input line 
                   2243:     
                   2244:     my $userinput  = $cmd.":".$tail;
                   2245:     
                   2246:     #  udom    - User's domain.
                   2247:     #  uname   - Username.
                   2248:     #  upass   - User's password.
1.396     raeburn  2249:     #  checkdefauth - Pass to validate_user() to try authentication
                   2250:     #                 with default auth type(s) if no user account.
1.447     raeburn  2251:     #  clientcancheckhost - Passed by clients with functionality in lonauth.pm
                   2252:     #                       to check if session can be hosted.
1.220     foxr     2253:     
1.447     raeburn  2254:     my ($udom, $uname, $upass, $checkdefauth, $clientcancheckhost)=split(/:/,$tail);
1.399     raeburn  2255:     &Debug(" Authenticate domain = $udom, user = $uname, password = $upass,  checkdefauth = $checkdefauth");
1.220     foxr     2256:     chomp($upass);
                   2257:     $upass=&unescape($upass);
                   2258: 
1.396     raeburn  2259:     my $pwdcorrect = &validate_user($udom,$uname,$upass,$checkdefauth);
1.220     foxr     2260:     if($pwdcorrect) {
1.447     raeburn  2261:         my $canhost = 1;
                   2262:         unless ($clientcancheckhost) {
1.448     raeburn  2263:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   2264:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.452     raeburn  2265:             my @intdoms;
                   2266:             my $internet_names = &Apache::lonnet::get_internet_names($clientname);
                   2267:             if (ref($internet_names) eq 'ARRAY') {
                   2268:                 @intdoms = @{$internet_names};
                   2269:             }
1.448     raeburn  2270:             unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
1.447     raeburn  2271:                 my ($remote,$hosted);
                   2272:                 my $remotesession = &get_usersession_config($udom,'remotesession');
                   2273:                 if (ref($remotesession) eq 'HASH') {
1.525     raeburn  2274:                     $remote = $remotesession->{'remote'};
1.447     raeburn  2275:                 }
1.448     raeburn  2276:                 my $hostedsession = &get_usersession_config($clienthomedom,'hostedsession');
1.447     raeburn  2277:                 if (ref($hostedsession) eq 'HASH') {
                   2278:                     $hosted = $hostedsession->{'hosted'};
                   2279:                 }
1.448     raeburn  2280:                 $canhost = &Apache::lonnet::can_host_session($udom,$clientname,
1.492     droeschl 2281:                                                              $clientversion,
1.447     raeburn  2282:                                                              $remote,$hosted);
                   2283:             }
                   2284:         }
                   2285:         if ($canhost) {               
                   2286:             &Reply( $client, "authorized\n", $userinput);
                   2287:         } else {
                   2288:             &Reply( $client, "not_allowed_to_host\n", $userinput);
                   2289:         }
1.220     foxr     2290: 	#
                   2291: 	#  Bad credentials: Failed to authorize
                   2292: 	#
                   2293:     } else {
                   2294: 	&Failure( $client, "non_authorized\n", $userinput);
                   2295:     }
                   2296: 
                   2297:     return 1;
                   2298: }
1.263     albertel 2299: &register_handler("auth", \&authenticate_handler, 1, 1, 0);
1.214     foxr     2300: 
1.222     foxr     2301: #
                   2302: #   Change a user's password.  Note that this function is complicated by
                   2303: #   the fact that a user may be authenticated in more than one way:
                   2304: #   At present, we are not able to change the password for all types of
                   2305: #   authentication methods.  Only for:
                   2306: #      unix    - unix password or shadow passoword style authentication.
                   2307: #      local   - Locally written authentication mechanism.
                   2308: #   For now, kerb4 and kerb5 password changes are not supported and result
                   2309: #   in an error.
                   2310: # FUTURE WORK:
                   2311: #    Support kerberos passwd changes?
                   2312: # Parameters:
                   2313: #    $cmd      - The command that got us here.
                   2314: #    $tail     - Tail of the command (remaining parameters).
                   2315: #    $client   - File descriptor connected to client.
                   2316: # Returns
                   2317: #     0        - Requested to exit, caller should shut down.
                   2318: #     1        - Continue processing.
                   2319: # Implicit inputs:
                   2320: #    The authentication systems describe above have their own forms of implicit
                   2321: #    input into the authentication process that are described above.
                   2322: sub change_password_handler {
                   2323:     my ($cmd, $tail, $client) = @_;
                   2324: 
                   2325:     my $userinput = $cmd.":".$tail;           # Reconstruct client's string.
                   2326: 
                   2327:     #
                   2328:     #  udom  - user's domain.
                   2329:     #  uname - Username.
                   2330:     #  upass - Current password.
                   2331:     #  npass - New password.
1.346     raeburn  2332:     #  context - Context in which this was called 
                   2333:     #            (preferences or reset_by_email).
1.428     raeburn  2334:     #  lonhost - HostID of server where request originated 
1.222     foxr     2335:    
1.428     raeburn  2336:     my ($udom,$uname,$upass,$npass,$context,$lonhost)=split(/:/,$tail);
1.222     foxr     2337: 
                   2338:     $upass=&unescape($upass);
                   2339:     $npass=&unescape($npass);
                   2340:     &Debug("Trying to change password for $uname");
                   2341: 
                   2342:     # First require that the user can be authenticated with their
1.346     raeburn  2343:     # old password unless context was 'reset_by_email':
                   2344:     
1.428     raeburn  2345:     my ($validated,$failure);
1.346     raeburn  2346:     if ($context eq 'reset_by_email') {
1.428     raeburn  2347:         if ($lonhost eq '') {
                   2348:             $failure = 'invalid_client';
                   2349:         } else {
                   2350:             $validated = 1;
                   2351:         }
1.346     raeburn  2352:     } else {
                   2353:         $validated = &validate_user($udom, $uname, $upass);
                   2354:     }
1.222     foxr     2355:     if($validated) {
                   2356: 	my $realpasswd  = &get_auth_type($udom, $uname); # Defined since authd.
                   2357: 	my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
1.558     raeburn  2358:         my $notunique;
1.222     foxr     2359: 	if ($howpwd eq 'internal') {
                   2360: 	    &Debug("internal auth");
1.518     raeburn  2361:             my $ncpass = &hash_passwd($udom,$npass);
1.558     raeburn  2362:             my (undef,$method,@rest) = split(/!/,$contentpwd);
                   2363:             if ($method eq 'bcrypt') {
                   2364:                 my %passwdconf = &Apache::lonnet::get_passwdconf($udom);
                   2365:                 if (($passwdconf{'numsaved'}) && ($passwdconf{'numsaved'} =~ /^\d+$/)) {
                   2366:                     my @oldpasswds;
                   2367:                     my $userpath = &propath($udom,$uname);
                   2368:                     my $fullpath = $userpath.'/oldpasswds';
                   2369:                     if (-d $userpath) {
                   2370:                         my @oldfiles;
                   2371:                         if (-e $fullpath) {
                   2372:                             if (opendir(my $dir,$fullpath)) {
                   2373:                                 (@oldfiles) = grep(/^\d+$/,readdir($dir));
                   2374:                                 closedir($dir);
                   2375:                             }
                   2376:                             if (@oldfiles) {
                   2377:                                 @oldfiles = sort { $b <=> $a } (@oldfiles);
                   2378:                                 my $numremoved = 0;
                   2379:                                 for (my $i=0; $i<@oldfiles; $i++) {
                   2380:                                     if ($i>=$passwdconf{'numsaved'}) {
                   2381:                                         if (-f "$fullpath/$oldfiles[$i]") {
                   2382:                                             if (unlink("$fullpath/$oldfiles[$i]")) {
                   2383:                                                 $numremoved ++;
                   2384:                                             }
                   2385:                                         }
                   2386:                                     } elsif (open(my $fh,'<',"$fullpath/$oldfiles[$i]")) {
                   2387:                                         while (my $line = <$fh>) {
                   2388:                                             push(@oldpasswds,$line);
                   2389:                                         }
                   2390:                                         close($fh);
                   2391:                                     }
                   2392:                                 }
                   2393:                                 if ($numremoved) {
                   2394:                                     &logthis("unlinked $numremoved old password files for $uname:$udom");
                   2395:                                 }
                   2396:                             }
                   2397:                         }
                   2398:                         push(@oldpasswds,$contentpwd);
                   2399:                         foreach my $item (@oldpasswds) {
                   2400:                             my (undef,$method,@rest) = split(/!/,$item);
                   2401:                             if ($method eq 'bcrypt') {
                   2402:                                 my $result = &hash_passwd($udom,$npass,@rest);
                   2403:                                 if ($result eq $item) {
                   2404:                                     $notunique = 1;
                   2405:                                     last;
                   2406:                                 }
                   2407:                             }
                   2408:                         }
                   2409:                         unless ($notunique) {
                   2410:                             unless (-e $fullpath) {
                   2411:                                 if (&mkpath("$fullpath/")) {
                   2412:                                     chmod(0700,$fullpath);
                   2413:                                 }
                   2414:                             }
                   2415:                             if (-d $fullpath) {
                   2416:                                 my $now = time;
                   2417:                                 if (open(my $fh,'>',"$fullpath/$now")) {
                   2418:                                     print $fh $contentpwd;
                   2419:                                     close($fh);
                   2420:                                     chmod(0400,"$fullpath/$now");
                   2421:                                 }
                   2422:                             }
                   2423:                         }
                   2424:                     }
                   2425:                 }
                   2426:             }
                   2427:             if ($notunique) {
                   2428:                 my $msg="Result of password change for $uname:$udom - password matches one used before";
                   2429:                 if ($lonhost) {
                   2430:                     $msg .= " - request originated from: $lonhost";
                   2431:                 }
                   2432:                 &logthis($msg);
                   2433:                 &Reply($client, "prioruse\n", $userinput);
                   2434: 	    } elsif (&rewrite_password_file($udom, $uname, "internal:$ncpass")) {
1.428     raeburn  2435: 		my $msg="Result of password change for $uname: pwchange_success";
                   2436:                 if ($lonhost) {
                   2437:                     $msg .= " - request originated from: $lonhost";
                   2438:                 }
                   2439:                 &logthis($msg);
1.518     raeburn  2440:                 &update_passwd_history($uname,$udom,$howpwd,$context);
1.222     foxr     2441: 		&Reply($client, "ok\n", $userinput);
                   2442: 	    } else {
                   2443: 		&logthis("Unable to open $uname passwd "               
                   2444: 			 ."to change password");
                   2445: 		&Failure( $client, "non_authorized\n",$userinput);
                   2446: 	    }
1.346     raeburn  2447: 	} elsif ($howpwd eq 'unix' && $context ne 'reset_by_email') {
1.287     foxr     2448: 	    my $result = &change_unix_password($uname, $npass);
1.518     raeburn  2449:             if ($result eq 'ok') {
                   2450:                 &update_passwd_history($uname,$udom,$howpwd,$context);
1.561     raeburn  2451:             }
1.222     foxr     2452: 	    &logthis("Result of password change for $uname: ".
1.287     foxr     2453: 		     $result);
1.387     albertel 2454: 	    &Reply($client, \$result, $userinput);
1.222     foxr     2455: 	} else {
                   2456: 	    # this just means that the current password mode is not
                   2457: 	    # one we know how to change (e.g the kerberos auth modes or
                   2458: 	    # locally written auth handler).
                   2459: 	    #
                   2460: 	    &Failure( $client, "auth_mode_error\n", $userinput);
                   2461: 	}  
1.224     foxr     2462:     } else {
1.428     raeburn  2463: 	if ($failure eq '') {
                   2464: 	    $failure = 'non_authorized';
                   2465: 	}
                   2466: 	&Failure( $client, "$failure\n", $userinput);
1.222     foxr     2467:     }
                   2468: 
                   2469:     return 1;
                   2470: }
1.263     albertel 2471: &register_handler("passwd", \&change_password_handler, 1, 1, 0);
1.222     foxr     2472: 
1.518     raeburn  2473: sub hash_passwd {
                   2474:     my ($domain,$plainpass,@rest) = @_;
                   2475:     my ($salt,$cost);
                   2476:     if (@rest) {
                   2477:         $cost = $rest[0];
                   2478:         # salt is first 22 characters, base-64 encoded by bcrypt
                   2479:         my $plainsalt = substr($rest[1],0,22);
                   2480:         $salt = Crypt::Eksblowfish::Bcrypt::de_base64($plainsalt);
                   2481:     } else {
1.533     raeburn  2482:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   2483:         my $defaultcost = $domdefaults{'intauth_cost'};
1.518     raeburn  2484:         if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
                   2485:             $cost = 10;
                   2486:         } else {
                   2487:             $cost = $defaultcost;
                   2488:         }
                   2489:         # Generate random 16-octet base64 salt
                   2490:         $salt = "";
                   2491:         $salt .= pack("C", int rand(256)) for 1..16;
                   2492:     }
                   2493:     my $hash = &Crypt::Eksblowfish::Bcrypt::bcrypt_hash({
                   2494:         key_nul => 1,
                   2495:         cost    => $cost,
                   2496:         salt    => $salt,
                   2497:     }, Digest::SHA::sha512(Encode::encode('UTF-8',$plainpass)));
                   2498: 
                   2499:     my $result = join("!", "", "bcrypt", sprintf("%02d",$cost),
                   2500:                 &Crypt::Eksblowfish::Bcrypt::en_base64($salt).
                   2501:                 &Crypt::Eksblowfish::Bcrypt::en_base64($hash));
                   2502:     return $result;
                   2503: }
                   2504: 
1.225     foxr     2505: #
                   2506: #   Create a new user.  User in this case means a lon-capa user.
                   2507: #   The user must either already exist in some authentication realm
                   2508: #   like kerberos or the /etc/passwd.  If not, a user completely local to
                   2509: #   this loncapa system is created.
                   2510: #
                   2511: # Parameters:
                   2512: #    $cmd      - The command that got us here.
                   2513: #    $tail     - Tail of the command (remaining parameters).
                   2514: #    $client   - File descriptor connected to client.
                   2515: # Returns
                   2516: #     0        - Requested to exit, caller should shut down.
                   2517: #     1        - Continue processing.
                   2518: # Implicit inputs:
                   2519: #    The authentication systems describe above have their own forms of implicit
                   2520: #    input into the authentication process that are described above.
                   2521: sub add_user_handler {
                   2522: 
                   2523:     my ($cmd, $tail, $client) = @_;
                   2524: 
                   2525: 
                   2526:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   2527:     my $userinput = $cmd.":".$tail; # Reconstruct the full request line.
                   2528: 
                   2529:     &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
                   2530: 
                   2531: 
                   2532:     if($udom eq $currentdomainid) { # Reject new users for other domains...
                   2533: 	
                   2534: 	my $oldumask=umask(0077);
                   2535: 	chomp($npass);
                   2536: 	$npass=&unescape($npass);
                   2537: 	my $passfilename  = &password_path($udom, $uname);
                   2538: 	&Debug("Password file created will be:".$passfilename);
                   2539: 	if (-e $passfilename) {
                   2540: 	    &Failure( $client, "already_exists\n", $userinput);
                   2541: 	} else {
                   2542: 	    my $fperror='';
1.264     albertel 2543: 	    if (!&mkpath($passfilename)) {
                   2544: 		$fperror="error: ".($!+0)." mkdir failed while attempting "
                   2545: 		    ."makeuser";
1.225     foxr     2546: 	    }
                   2547: 	    unless ($fperror) {
1.518     raeburn  2548: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
                   2549:                                              $passfilename,'makeuser');
1.390     raeburn  2550: 		&Reply($client,\$result, $userinput);     #BUGBUG - could be fail
1.225     foxr     2551: 	    } else {
1.387     albertel 2552: 		&Failure($client, \$fperror, $userinput);
1.225     foxr     2553: 	    }
                   2554: 	}
                   2555: 	umask($oldumask);
                   2556:     }  else {
                   2557: 	&Failure($client, "not_right_domain\n",
                   2558: 		$userinput);	# Even if we are multihomed.
                   2559:     
                   2560:     }
                   2561:     return 1;
                   2562: 
                   2563: }
                   2564: &register_handler("makeuser", \&add_user_handler, 1, 1, 0);
                   2565: 
                   2566: #
                   2567: #   Change the authentication method of a user.  Note that this may
                   2568: #   also implicitly change the user's password if, for example, the user is
                   2569: #   joining an existing authentication realm.  Known authentication realms at
                   2570: #   this time are:
                   2571: #    internal   - Purely internal password file (only loncapa knows this user)
                   2572: #    local      - Institutionally written authentication module.
                   2573: #    unix       - Unix user (/etc/passwd with or without /etc/shadow).
                   2574: #    kerb4      - kerberos version 4
                   2575: #    kerb5      - kerberos version 5
                   2576: #
                   2577: # Parameters:
                   2578: #    $cmd      - The command that got us here.
                   2579: #    $tail     - Tail of the command (remaining parameters).
                   2580: #    $client   - File descriptor connected to client.
                   2581: # Returns
                   2582: #     0        - Requested to exit, caller should shut down.
                   2583: #     1        - Continue processing.
                   2584: # Implicit inputs:
                   2585: #    The authentication systems describe above have their own forms of implicit
                   2586: #    input into the authentication process that are described above.
1.287     foxr     2587: # NOTE:
                   2588: #   This is also used to change the authentication credential values (e.g. passwd).
                   2589: #   
1.225     foxr     2590: #
                   2591: sub change_authentication_handler {
                   2592: 
                   2593:     my ($cmd, $tail, $client) = @_;
                   2594:    
                   2595:     my $userinput  = "$cmd:$tail";              # Reconstruct user input.
                   2596: 
                   2597:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   2598:     &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
                   2599:     if ($udom ne $currentdomainid) {
                   2600: 	&Failure( $client, "not_right_domain\n", $client);
                   2601:     } else {
                   2602: 	
                   2603: 	chomp($npass);
                   2604: 	
                   2605: 	$npass=&unescape($npass);
1.261     foxr     2606: 	my $oldauth = &get_auth_type($udom, $uname); # Get old auth info.
1.225     foxr     2607: 	my $passfilename = &password_path($udom, $uname);
                   2608: 	if ($passfilename) {	# Not allowed to create a new user!!
1.287     foxr     2609: 	    # If just changing the unix passwd. need to arrange to run
1.502     raeburn  2610: 	    # passwd since otherwise make_passwd_file will fail as 
                   2611: 	    # creation of unix authenticated users is no longer supported
                   2612:             # except from the command line, when running make_domain_coordinator.pl
1.287     foxr     2613: 
                   2614: 	    if(($oldauth =~/^unix/) && ($umode eq "unix")) {
                   2615: 		my $result = &change_unix_password($uname, $npass);
                   2616: 		&logthis("Result of password change for $uname: ".$result);
                   2617: 		if ($result eq "ok") {
1.518     raeburn  2618:                     &update_passwd_history($uname,$udom,$umode,'changeuserauth'); 
1.390     raeburn  2619: 		    &Reply($client, \$result);
1.288     albertel 2620: 		} else {
1.387     albertel 2621: 		    &Failure($client, \$result);
1.287     foxr     2622: 		}
1.288     albertel 2623: 	    } else {
1.518     raeburn  2624: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
                   2625:                                              $passfilename,'changeuserauth');
1.287     foxr     2626: 		#
                   2627: 		#  If the current auth mode is internal, and the old auth mode was
                   2628: 		#  unix, or krb*,  and the user is an author for this domain,
                   2629: 		#  re-run manage_permissions for that role in order to be able
                   2630: 		#  to take ownership of the construction space back to www:www
                   2631: 		#
1.502     raeburn  2632: 
                   2633: 
1.387     albertel 2634: 		&Reply($client, \$result, $userinput);
1.261     foxr     2635: 	    }
                   2636: 	       
                   2637: 
1.225     foxr     2638: 	} else {	       
1.251     foxr     2639: 	    &Failure($client, "non_authorized\n", $userinput); # Fail the user now.
1.225     foxr     2640: 	}
                   2641:     }
                   2642:     return 1;
                   2643: }
                   2644: &register_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
                   2645: 
1.518     raeburn  2646: sub update_passwd_history {
                   2647:     my ($uname,$udom,$umode,$context) = @_;
                   2648:     my $proname=&propath($udom,$uname);
                   2649:     my $now = time;
                   2650:     if (open(my $fh,">>$proname/passwd.log")) {
                   2651:         print $fh "$now:$umode:$context\n";
                   2652:         close($fh);
                   2653:     }
                   2654:     return;
                   2655: }
                   2656: 
1.225     foxr     2657: #
                   2658: #   Determines if this is the home server for a user.  The home server
                   2659: #   for a user will have his/her lon-capa passwd file.  Therefore all we need
                   2660: #   to do is determine if this file exists.
                   2661: #
                   2662: # Parameters:
                   2663: #    $cmd      - The command that got us here.
                   2664: #    $tail     - Tail of the command (remaining parameters).
                   2665: #    $client   - File descriptor connected to client.
                   2666: # Returns
                   2667: #     0        - Requested to exit, caller should shut down.
                   2668: #     1        - Continue processing.
                   2669: # Implicit inputs:
                   2670: #    The authentication systems describe above have their own forms of implicit
                   2671: #    input into the authentication process that are described above.
                   2672: #
                   2673: sub is_home_handler {
                   2674:     my ($cmd, $tail, $client) = @_;
                   2675:    
                   2676:     my $userinput  = "$cmd:$tail";
                   2677:    
                   2678:     my ($udom,$uname)=split(/:/,$tail);
                   2679:     chomp($uname);
                   2680:     my $passfile = &password_filename($udom, $uname);
                   2681:     if($passfile) {
                   2682: 	&Reply( $client, "found\n", $userinput);
                   2683:     } else {
                   2684: 	&Failure($client, "not_found\n", $userinput);
                   2685:     }
                   2686:     return 1;
                   2687: }
                   2688: &register_handler("home", \&is_home_handler, 0,1,0);
                   2689: 
                   2690: #
1.434     www      2691: #   Process an update request for a resource.
                   2692: #   A resource has been modified that we hold a subscription to.
1.225     foxr     2693: #   If the resource is not local, then we must update, or at least invalidate our
                   2694: #   cached copy of the resource. 
                   2695: # Parameters:
                   2696: #    $cmd      - The command that got us here.
                   2697: #    $tail     - Tail of the command (remaining parameters).
                   2698: #    $client   - File descriptor connected to client.
                   2699: # Returns
                   2700: #     0        - Requested to exit, caller should shut down.
                   2701: #     1        - Continue processing.
                   2702: # Implicit inputs:
                   2703: #    The authentication systems describe above have their own forms of implicit
                   2704: #    input into the authentication process that are described above.
                   2705: #
                   2706: sub update_resource_handler {
                   2707: 
                   2708:     my ($cmd, $tail, $client) = @_;
                   2709:    
                   2710:     my $userinput = "$cmd:$tail";
                   2711:    
                   2712:     my $fname= $tail;		# This allows interactive testing
                   2713: 
                   2714: 
                   2715:     my $ownership=ishome($fname);
                   2716:     if ($ownership eq 'not_owner') {
                   2717: 	if (-e $fname) {
1.434     www      2718:             # Delete preview file, if exists
                   2719:             unlink("$fname.tmp");
                   2720:             # Get usage stats
1.225     foxr     2721: 	    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
                   2722: 		$atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
                   2723: 	    my $now=time;
                   2724: 	    my $since=$now-$atime;
1.434     www      2725:             # If the file has not been used within lonExpire seconds,
                   2726:             # unsubscribe from it and delete local copy
1.225     foxr     2727: 	    if ($since>$perlvar{'lonExpire'}) {
1.365     albertel 2728: 		my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
1.308     albertel 2729: 		&devalidate_meta_cache($fname);
1.225     foxr     2730: 		unlink("$fname");
1.334     albertel 2731: 		unlink("$fname.meta");
1.225     foxr     2732: 	    } else {
1.434     www      2733:             # Yes, this is in active use. Get a fresh copy. Since it might be in
                   2734:             # very active use and huge (like a movie), copy it to "in.transfer" filename first.
1.225     foxr     2735: 		my $transname="$fname.in.transfer";
1.365     albertel 2736: 		my $remoteurl=&Apache::lonnet::reply("sub:$fname","$clientname");
1.225     foxr     2737: 		my $response;
1.537     raeburn  2738: # FIXME: cannot replicate files that take more than two minutes to transfer -- needs checking now 1200s timeout used
                   2739: # for LWP request.
                   2740: 		my $request=new HTTP::Request('GET',"$remoteurl");
                   2741:                 $response=&LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,0,1);
1.225     foxr     2742: 		if ($response->is_error()) {
1.541     raeburn  2743:                     my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
                   2744:                     &devalidate_meta_cache($fname);
                   2745:                     if (-e $transname) {
                   2746:                         unlink($transname);
                   2747:                     }
                   2748:                     unlink($fname);
1.225     foxr     2749: 		    my $message=$response->status_line;
                   2750: 		    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   2751: 		} else {
                   2752: 		    if ($remoteurl!~/\.meta$/) {
1.537     raeburn  2753: 			my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2754:                         my $mresponse = &LONCAPA::LWPReq::makerequest($clientname,$mrequest,$fname.'.meta',\%perlvar,120,0,1);
                   2755: 			if ($mresponse->is_error()) {
                   2756: 			    unlink($fname.'.meta');
1.225     foxr     2757: 			}
                   2758: 		    }
1.434     www      2759:                     # we successfully transfered, copy file over to real name
1.225     foxr     2760: 		    rename($transname,$fname);
1.308     albertel 2761: 		    &devalidate_meta_cache($fname);
1.225     foxr     2762: 		}
                   2763: 	    }
                   2764: 	    &Reply( $client, "ok\n", $userinput);
                   2765: 	} else {
                   2766: 	    &Failure($client, "not_found\n", $userinput);
                   2767: 	}
                   2768:     } else {
                   2769: 	&Failure($client, "rejected\n", $userinput);
                   2770:     }
                   2771:     return 1;
                   2772: }
                   2773: &register_handler("update", \&update_resource_handler, 0 ,1, 0);
                   2774: 
1.308     albertel 2775: sub devalidate_meta_cache {
                   2776:     my ($url) = @_;
                   2777:     use Cache::Memcached;
                   2778:     my $memcache = new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.365     albertel 2779:     $url = &Apache::lonnet::declutter($url);
1.308     albertel 2780:     $url =~ s-\.meta$--;
                   2781:     my $id = &escape('meta:'.$url);
                   2782:     $memcache->delete($id);
                   2783: }
                   2784: 
1.225     foxr     2785: #
1.226     foxr     2786: #   Fetch a user file from a remote server to the user's home directory
                   2787: #   userfiles subdir.
1.225     foxr     2788: # Parameters:
                   2789: #    $cmd      - The command that got us here.
                   2790: #    $tail     - Tail of the command (remaining parameters).
                   2791: #    $client   - File descriptor connected to client.
                   2792: # Returns
                   2793: #     0        - Requested to exit, caller should shut down.
                   2794: #     1        - Continue processing.
                   2795: #
                   2796: sub fetch_user_file_handler {
                   2797: 
                   2798:     my ($cmd, $tail, $client) = @_;
                   2799: 
                   2800:     my $userinput = "$cmd:$tail";
                   2801:     my $fname           = $tail;
1.232     foxr     2802:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
1.225     foxr     2803:     my $udir=&propath($udom,$uname).'/userfiles';
                   2804:     unless (-e $udir) {
                   2805: 	mkdir($udir,0770); 
                   2806:     }
1.232     foxr     2807:     Debug("fetch user file for $fname");
1.225     foxr     2808:     if (-e $udir) {
                   2809: 	$ufile=~s/^[\.\~]+//;
1.232     foxr     2810: 
                   2811: 	# IF necessary, create the path right down to the file.
                   2812: 	# Note that any regular files in the way of this path are
                   2813: 	# wiped out to deal with some earlier folly of mine.
                   2814: 
1.267     raeburn  2815: 	if (!&mkpath($udir.'/'.$ufile)) {
1.264     albertel 2816: 	    &Failure($client, "unable_to_create\n", $userinput);	    
1.232     foxr     2817: 	}
                   2818: 
1.225     foxr     2819: 	my $destname=$udir.'/'.$ufile;
                   2820: 	my $transname=$udir.'/'.$ufile.'.in.transit';
1.476     raeburn  2821:         my $clientprotocol=$Apache::lonnet::protocol{$clientname};
                   2822:         $clientprotocol = 'http' if ($clientprotocol ne 'https');
1.486     raeburn  2823: 	my $clienthost = &Apache::lonnet::hostname($clientname);
                   2824: 	my $remoteurl=$clientprotocol.'://'.$clienthost.'/userfiles/'.$fname;
1.225     foxr     2825: 	my $response;
1.232     foxr     2826: 	Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
1.537     raeburn  2827: 	my $request=new HTTP::Request('GET',"$remoteurl");
                   2828:         my $verifycert = 1;
                   2829:         my @machine_ids = &Apache::lonnet::current_machine_ids();
                   2830:         if (grep(/^\Q$clientname\E$/,@machine_ids)) {
                   2831:             $verifycert = 0;
                   2832:         }
                   2833:         $response = &LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,$verifycert);
1.225     foxr     2834: 	if ($response->is_error()) {
                   2835: 	    unlink($transname);
                   2836: 	    my $message=$response->status_line;
                   2837: 	    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   2838: 	    &Failure($client, "failed\n", $userinput);
                   2839: 	} else {
1.232     foxr     2840: 	    Debug("Renaming $transname to $destname");
1.225     foxr     2841: 	    if (!rename($transname,$destname)) {
                   2842: 		&logthis("Unable to move $transname to $destname");
                   2843: 		unlink($transname);
                   2844: 		&Failure($client, "failed\n", $userinput);
                   2845: 	    } else {
1.495     raeburn  2846:                 if ($fname =~ /^default.+\.(page|sequence)$/) {
                   2847:                     my ($major,$minor) = split(/\./,$clientversion);
                   2848:                     if (($major < 2) || ($major == 2 && $minor < 11)) {
                   2849:                         my $now = time;
                   2850:                         &Apache::lonnet::do_cache_new('crschange',$udom.'_'.$uname,$now,600);
                   2851:                         my $key = &escape('internal.contentchange');
                   2852:                         my $what = "$key=$now";
                   2853:                         my $hashref = &tie_user_hash($udom,$uname,'environment',
                   2854:                                                      &GDBM_WRCREAT(),"P",$what);
                   2855:                         if ($hashref) {
                   2856:                             $hashref->{$key}=$now;
                   2857:                             if (!&untie_user_hash($hashref)) {
                   2858:                                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
                   2859:                                          "when updating internal.contentchange");
                   2860:                             }
                   2861:                         }
                   2862:                     }
                   2863:                 }
1.225     foxr     2864: 		&Reply($client, "ok\n", $userinput);
                   2865: 	    }
                   2866: 	}   
                   2867:     } else {
                   2868: 	&Failure($client, "not_home\n", $userinput);
                   2869:     }
                   2870:     return 1;
                   2871: }
                   2872: &register_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
                   2873: 
1.226     foxr     2874: #
                   2875: #   Remove a file from a user's home directory userfiles subdirectory.
                   2876: # Parameters:
                   2877: #    cmd   - the Lond request keyword that got us here.
                   2878: #    tail  - the part of the command past the keyword.
                   2879: #    client- File descriptor connected with the client.
                   2880: #
                   2881: # Returns:
                   2882: #    1    - Continue processing.
                   2883: sub remove_user_file_handler {
                   2884:     my ($cmd, $tail, $client) = @_;
                   2885: 
                   2886:     my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2887: 
                   2888:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2889:     if ($ufile =~m|/\.\./|) {
                   2890: 	# any files paths with /../ in them refuse 
                   2891: 	# to deal with
                   2892: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2893:     } else {
                   2894: 	my $udir = &propath($udom,$uname);
                   2895: 	if (-e $udir) {
                   2896: 	    my $file=$udir.'/userfiles/'.$ufile;
                   2897: 	    if (-e $file) {
1.253     foxr     2898: 		#
                   2899: 		#   If the file is a regular file unlink is fine...
1.520     raeburn  2900: 		#   However it's possible the client wants a dir 
                   2901: 		#   removed, in which case rmdir is more appropriate.
                   2902: 		#   Note: rmdir will only remove an empty directory.
1.253     foxr     2903: 		#
1.240     banghart 2904: 	        if (-f $file){
1.241     albertel 2905: 		    unlink($file);
1.520     raeburn  2906:                     # for html files remove the associated .bak file 
                   2907:                     # which may have been created by the editor.
                   2908:                     if ($ufile =~ m{^((docs|supplemental)/(?:\d+|default)/\d+(?:|/.+)/)[^/]+\.x?html?$}i) {
                   2909:                         my $path = $1;
                   2910:                         if (-e $file.'.bak') {
                   2911:                             unlink($file.'.bak');
                   2912:                         }
                   2913:                     }
1.241     albertel 2914: 		} elsif(-d $file) {
                   2915: 		    rmdir($file);
1.240     banghart 2916: 		}
1.226     foxr     2917: 		if (-e $file) {
1.253     foxr     2918: 		    #  File is still there after we deleted it ?!?
                   2919: 
1.226     foxr     2920: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2921: 		} else {
                   2922: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2923: 		}
                   2924: 	    } else {
                   2925: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2926: 	    }
                   2927: 	} else {
                   2928: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2929: 	}
                   2930:     }
                   2931:     return 1;
                   2932: }
                   2933: &register_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
                   2934: 
1.236     albertel 2935: #
                   2936: #   make a directory in a user's home directory userfiles subdirectory.
                   2937: # Parameters:
                   2938: #    cmd   - the Lond request keyword that got us here.
                   2939: #    tail  - the part of the command past the keyword.
                   2940: #    client- File descriptor connected with the client.
                   2941: #
                   2942: # Returns:
                   2943: #    1    - Continue processing.
                   2944: sub mkdir_user_file_handler {
                   2945:     my ($cmd, $tail, $client) = @_;
                   2946: 
                   2947:     my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2948:     $dir=&unescape($dir);
                   2949:     my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2950:     if ($ufile =~m|/\.\./|) {
                   2951: 	# any files paths with /../ in them refuse 
                   2952: 	# to deal with
                   2953: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2954:     } else {
                   2955: 	my $udir = &propath($udom,$uname);
                   2956: 	if (-e $udir) {
1.264     albertel 2957: 	    my $newdir=$udir.'/userfiles/'.$ufile.'/';
                   2958: 	    if (!&mkpath($newdir)) {
                   2959: 		&Failure($client, "failed\n", "$cmd:$tail");
1.236     albertel 2960: 	    }
1.264     albertel 2961: 	    &Reply($client, "ok\n", "$cmd:$tail");
1.236     albertel 2962: 	} else {
                   2963: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2964: 	}
                   2965:     }
                   2966:     return 1;
                   2967: }
                   2968: &register_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
                   2969: 
1.237     albertel 2970: #
                   2971: #   rename a file in a user's home directory userfiles subdirectory.
                   2972: # Parameters:
                   2973: #    cmd   - the Lond request keyword that got us here.
                   2974: #    tail  - the part of the command past the keyword.
                   2975: #    client- File descriptor connected with the client.
                   2976: #
                   2977: # Returns:
                   2978: #    1    - Continue processing.
                   2979: sub rename_user_file_handler {
                   2980:     my ($cmd, $tail, $client) = @_;
                   2981: 
                   2982:     my ($udom,$uname,$old,$new) = split(/:/, $tail);
                   2983:     $old=&unescape($old);
                   2984:     $new=&unescape($new);
                   2985:     if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
                   2986: 	# any files paths with /../ in them refuse to deal with
                   2987: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2988:     } else {
                   2989: 	my $udir = &propath($udom,$uname);
                   2990: 	if (-e $udir) {
                   2991: 	    my $oldfile=$udir.'/userfiles/'.$old;
                   2992: 	    my $newfile=$udir.'/userfiles/'.$new;
                   2993: 	    if (-e $newfile) {
                   2994: 		&Failure($client, "exists\n", "$cmd:$tail");
                   2995: 	    } elsif (! -e $oldfile) {
                   2996: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2997: 	    } else {
                   2998: 		if (!rename($oldfile,$newfile)) {
                   2999: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   3000: 		} else {
                   3001: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   3002: 		}
                   3003: 	    }
                   3004: 	} else {
                   3005: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   3006: 	}
                   3007:     }
                   3008:     return 1;
                   3009: }
                   3010: &register_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
                   3011: 
1.227     foxr     3012: #
1.382     albertel 3013: #  Checks if the specified user has an active session on the server
                   3014: #  return ok if so, not_found if not
                   3015: #
                   3016: # Parameters:
                   3017: #   cmd      - The request keyword that dispatched to tus.
                   3018: #   tail     - The tail of the request (colon separated parameters).
                   3019: #   client   - Filehandle open on the client.
                   3020: # Return:
                   3021: #    1.
                   3022: sub user_has_session_handler {
                   3023:     my ($cmd, $tail, $client) = @_;
                   3024: 
                   3025:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
                   3026:     
                   3027:     opendir(DIR,$perlvar{'lonIDsDir'});
                   3028:     my $filename;
                   3029:     while ($filename=readdir(DIR)) {
                   3030: 	last if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/);
                   3031:     }
                   3032:     if ($filename) {
                   3033: 	&Reply($client, "ok\n", "$cmd:$tail");
                   3034:     } else {
                   3035: 	&Failure($client, "not_found\n", "$cmd:$tail");
                   3036:     }
                   3037:     return 1;
                   3038: 
                   3039: }
                   3040: &register_handler("userhassession", \&user_has_session_handler, 0,1,0);
                   3041: 
1.560     raeburn  3042: sub del_usersession_handler {
                   3043:     my ($cmd, $tail, $client) = @_;
                   3044: 
                   3045:     my $result;
                   3046:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
                   3047:     if (($udom =~ /^$LONCAPA::match_domain$/) && ($uname =~ /^$LONCAPA::match_username$/)) {
                   3048:         my $lonidsdir = $perlvar{'lonIDsDir'};
                   3049:         if (-d $lonidsdir) {
                   3050:             if (opendir(DIR,$lonidsdir)) {
                   3051:                 my $filename;
                   3052:                 while ($filename=readdir(DIR)) {
                   3053:                     if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/) {
                   3054:                         if (tie(my %oldenv,'GDBM_File',"$lonidsdir/$filename",
                   3055:                                 &GDBM_READER(),0640)) {
                   3056:                             my $linkedfile;
                   3057:                             if (exists($oldenv{'user.linkedenv'})) {
                   3058:                                 $linkedfile = $oldenv{'user.linkedenv'};
                   3059:                             }
                   3060:                             untie(%oldenv);
                   3061:                             $result = unlink("$lonidsdir/$filename");
                   3062:                             if ($result) {
                   3063:                                 if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   3064:                                     if (-l "$lonidsdir/$linkedfile.id") {
                   3065:                                         unlink("$lonidsdir/$linkedfile.id");
                   3066:                                     }
                   3067:                                 }
                   3068:                             }
                   3069:                         } else {
                   3070:                             $result = unlink("$lonidsdir/$filename");
                   3071:                         }
                   3072:                         last;
                   3073:                     }
                   3074:                 }
                   3075:             }
                   3076:         }
                   3077:         if ($result == 1) {
                   3078:             &Reply($client, "$result\n", "$cmd:$tail");
                   3079:         } else {
                   3080:             &Reply($client, "not_found\n", "$cmd:$tail");
                   3081:         }
                   3082:     } else {
                   3083:         &Failure($client, "invalid_user\n", "$cmd:$tail");
                   3084:     }
                   3085:     return 1;
                   3086: }
                   3087: 
                   3088: &register_handler("delusersession", \&del_usersession_handler, 0,1,0);
                   3089: 
1.382     albertel 3090: #
1.263     albertel 3091: #  Authenticate access to a user file by checking that the token the user's 
                   3092: #  passed also exists in their session file
1.227     foxr     3093: #
                   3094: # Parameters:
                   3095: #   cmd      - The request keyword that dispatched to tus.
                   3096: #   tail     - The tail of the request (colon separated parameters).
                   3097: #   client   - Filehandle open on the client.
                   3098: # Return:
                   3099: #    1.
                   3100: sub token_auth_user_file_handler {
                   3101:     my ($cmd, $tail, $client) = @_;
                   3102: 
                   3103:     my ($fname, $session) = split(/:/, $tail);
                   3104:     
                   3105:     chomp($session);
1.393     raeburn  3106:     my $reply="non_auth";
1.343     albertel 3107:     my $file = $perlvar{'lonIDsDir'}.'/'.$session.'.id';
                   3108:     if (open(ENVIN,"$file")) {
1.332     albertel 3109: 	flock(ENVIN,LOCK_SH);
1.343     albertel 3110: 	tie(my %disk_env,'GDBM_File',"$file",&GDBM_READER(),0640);
                   3111: 	if (exists($disk_env{"userfile.$fname"})) {
1.393     raeburn  3112: 	    $reply="ok";
1.343     albertel 3113: 	} else {
                   3114: 	    foreach my $envname (keys(%disk_env)) {
                   3115: 		if ($envname=~ m|^userfile\.\Q$fname\E|) {
1.393     raeburn  3116: 		    $reply="ok";
1.343     albertel 3117: 		    last;
                   3118: 		}
                   3119: 	    }
1.227     foxr     3120: 	}
1.343     albertel 3121: 	untie(%disk_env);
1.227     foxr     3122: 	close(ENVIN);
1.387     albertel 3123: 	&Reply($client, \$reply, "$cmd:$tail");
1.227     foxr     3124:     } else {
                   3125: 	&Failure($client, "invalid_token\n", "$cmd:$tail");
                   3126:     }
                   3127:     return 1;
                   3128: 
                   3129: }
                   3130: &register_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
1.229     foxr     3131: 
                   3132: #
                   3133: #   Unsubscribe from a resource.
                   3134: #
                   3135: # Parameters:
                   3136: #    $cmd      - The command that got us here.
                   3137: #    $tail     - Tail of the command (remaining parameters).
                   3138: #    $client   - File descriptor connected to client.
                   3139: # Returns
                   3140: #     0        - Requested to exit, caller should shut down.
                   3141: #     1        - Continue processing.
                   3142: #
                   3143: sub unsubscribe_handler {
                   3144:     my ($cmd, $tail, $client) = @_;
                   3145: 
                   3146:     my $userinput= "$cmd:$tail";
                   3147:     
                   3148:     my ($fname) = split(/:/,$tail); # Split in case there's extrs.
                   3149: 
                   3150:     &Debug("Unsubscribing $fname");
                   3151:     if (-e $fname) {
                   3152: 	&Debug("Exists");
                   3153: 	&Reply($client, &unsub($fname,$clientip), $userinput);
                   3154:     } else {
                   3155: 	&Failure($client, "not_found\n", $userinput);
                   3156:     }
                   3157:     return 1;
                   3158: }
                   3159: &register_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
1.263     albertel 3160: 
1.230     foxr     3161: #   Subscribe to a resource
                   3162: #
                   3163: # Parameters:
                   3164: #    $cmd      - The command that got us here.
                   3165: #    $tail     - Tail of the command (remaining parameters).
                   3166: #    $client   - File descriptor connected to client.
                   3167: # Returns
                   3168: #     0        - Requested to exit, caller should shut down.
                   3169: #     1        - Continue processing.
                   3170: #
                   3171: sub subscribe_handler {
                   3172:     my ($cmd, $tail, $client)= @_;
                   3173: 
                   3174:     my $userinput  = "$cmd:$tail";
                   3175: 
                   3176:     &Reply( $client, &subscribe($userinput,$clientip), $userinput);
                   3177: 
                   3178:     return 1;
                   3179: }
                   3180: &register_handler("sub", \&subscribe_handler, 0, 1, 0);
                   3181: 
                   3182: #
1.379     albertel 3183: #   Determine the latest version of a resource (it looks for the highest
                   3184: #   past version and then returns that +1)
1.230     foxr     3185: #
                   3186: # Parameters:
                   3187: #    $cmd      - The command that got us here.
                   3188: #    $tail     - Tail of the command (remaining parameters).
1.379     albertel 3189: #                 (Should consist of an absolute path to a file)
1.230     foxr     3190: #    $client   - File descriptor connected to client.
                   3191: # Returns
                   3192: #     0        - Requested to exit, caller should shut down.
                   3193: #     1        - Continue processing.
                   3194: #
                   3195: sub current_version_handler {
                   3196:     my ($cmd, $tail, $client) = @_;
                   3197: 
                   3198:     my $userinput= "$cmd:$tail";
                   3199:    
                   3200:     my $fname   = $tail;
                   3201:     &Reply( $client, &currentversion($fname)."\n", $userinput);
                   3202:     return 1;
                   3203: 
                   3204: }
                   3205: &register_handler("currentversion", \&current_version_handler, 0, 1, 0);
                   3206: 
                   3207: #  Make an entry in a user's activity log.
                   3208: #
                   3209: # Parameters:
                   3210: #    $cmd      - The command that got us here.
                   3211: #    $tail     - Tail of the command (remaining parameters).
                   3212: #    $client   - File descriptor connected to client.
                   3213: # Returns
                   3214: #     0        - Requested to exit, caller should shut down.
                   3215: #     1        - Continue processing.
                   3216: #
                   3217: sub activity_log_handler {
                   3218:     my ($cmd, $tail, $client) = @_;
                   3219: 
                   3220: 
                   3221:     my $userinput= "$cmd:$tail";
                   3222: 
                   3223:     my ($udom,$uname,$what)=split(/:/,$tail);
                   3224:     chomp($what);
                   3225:     my $proname=&propath($udom,$uname);
                   3226:     my $now=time;
                   3227:     my $hfh;
                   3228:     if ($hfh=IO::File->new(">>$proname/activity.log")) { 
                   3229: 	print $hfh "$now:$clientname:$what\n";
                   3230: 	&Reply( $client, "ok\n", $userinput); 
                   3231:     } else {
                   3232: 	&Failure($client, "error: ".($!+0)." IO::File->new Failed "
                   3233: 		 ."while attempting log\n", 
                   3234: 		 $userinput);
                   3235:     }
                   3236: 
                   3237:     return 1;
                   3238: }
1.263     albertel 3239: &register_handler("log", \&activity_log_handler, 0, 1, 0);
1.230     foxr     3240: 
                   3241: #
                   3242: #   Put a namespace entry in a user profile hash.
                   3243: #   My druthers would be for this to be an encrypted interaction too.
                   3244: #   anything that might be an inadvertent covert channel about either
                   3245: #   user authentication or user personal information....
                   3246: #
                   3247: # Parameters:
                   3248: #    $cmd      - The command that got us here.
                   3249: #    $tail     - Tail of the command (remaining parameters).
                   3250: #    $client   - File descriptor connected to client.
                   3251: # Returns
                   3252: #     0        - Requested to exit, caller should shut down.
                   3253: #     1        - Continue processing.
                   3254: #
                   3255: sub put_user_profile_entry {
                   3256:     my ($cmd, $tail, $client)  = @_;
1.229     foxr     3257: 
1.230     foxr     3258:     my $userinput = "$cmd:$tail";
                   3259:     
1.242     raeburn  3260:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
1.230     foxr     3261:     if ($namespace ne 'roles') {
                   3262: 	chomp($what);
                   3263: 	my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3264: 				  &GDBM_WRCREAT(),"P",$what);
                   3265: 	if($hashref) {
                   3266: 	    my @pairs=split(/\&/,$what);
                   3267: 	    foreach my $pair (@pairs) {
                   3268: 		my ($key,$value)=split(/=/,$pair);
                   3269: 		$hashref->{$key}=$value;
                   3270: 	    }
1.311     albertel 3271: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     3272: 		&Reply( $client, "ok\n", $userinput);
                   3273: 	    } else {
                   3274: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3275: 			"while attempting put\n", 
                   3276: 			$userinput);
                   3277: 	    }
                   3278: 	} else {
1.316     albertel 3279: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.230     foxr     3280: 		     "while attempting put\n", $userinput);
                   3281: 	}
                   3282:     } else {
                   3283:         &Failure( $client, "refused\n", $userinput);
                   3284:     }
                   3285:     
                   3286:     return 1;
                   3287: }
                   3288: &register_handler("put", \&put_user_profile_entry, 0, 1, 0);
                   3289: 
1.283     albertel 3290: #   Put a piece of new data in hash, returns error if entry already exists
                   3291: # Parameters:
                   3292: #    $cmd      - The command that got us here.
                   3293: #    $tail     - Tail of the command (remaining parameters).
                   3294: #    $client   - File descriptor connected to client.
                   3295: # Returns
                   3296: #     0        - Requested to exit, caller should shut down.
                   3297: #     1        - Continue processing.
                   3298: #
                   3299: sub newput_user_profile_entry {
                   3300:     my ($cmd, $tail, $client)  = @_;
                   3301: 
                   3302:     my $userinput = "$cmd:$tail";
                   3303: 
                   3304:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
                   3305:     if ($namespace eq 'roles') {
                   3306:         &Failure( $client, "refused\n", $userinput);
                   3307: 	return 1;
                   3308:     }
                   3309: 
                   3310:     chomp($what);
                   3311: 
                   3312:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3313: 				 &GDBM_WRCREAT(),"N",$what);
                   3314:     if(!$hashref) {
1.316     albertel 3315: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.283     albertel 3316: 		  "while attempting put\n", $userinput);
                   3317: 	return 1;
                   3318:     }
                   3319: 
                   3320:     my @pairs=split(/\&/,$what);
                   3321:     foreach my $pair (@pairs) {
                   3322: 	my ($key,$value)=split(/=/,$pair);
                   3323: 	if (exists($hashref->{$key})) {
1.513     raeburn  3324:             if (!&untie_user_hash($hashref)) {
                   3325:                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
                   3326:                          "while attempting newput - early out as key exists");
                   3327:             }
                   3328:             &Failure($client, "key_exists: ".$key."\n",$userinput);
                   3329:             return 1;
1.283     albertel 3330: 	}
                   3331:     }
                   3332: 
                   3333:     foreach my $pair (@pairs) {
                   3334: 	my ($key,$value)=split(/=/,$pair);
                   3335: 	$hashref->{$key}=$value;
                   3336:     }
                   3337: 
1.311     albertel 3338:     if (&untie_user_hash($hashref)) {
1.283     albertel 3339: 	&Reply( $client, "ok\n", $userinput);
                   3340:     } else {
                   3341: 	&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3342: 		 "while attempting put\n", 
                   3343: 		 $userinput);
                   3344:     }
                   3345:     return 1;
                   3346: }
                   3347: &register_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
                   3348: 
1.230     foxr     3349: # 
                   3350: #   Increment a profile entry in the user history file.
                   3351: #   The history contains keyword value pairs.  In this case,
                   3352: #   The value itself is a pair of numbers.  The first, the current value
                   3353: #   the second an increment that this function applies to the current
                   3354: #   value.
                   3355: #
                   3356: # Parameters:
                   3357: #    $cmd      - The command that got us here.
                   3358: #    $tail     - Tail of the command (remaining parameters).
                   3359: #    $client   - File descriptor connected to client.
                   3360: # Returns
                   3361: #     0        - Requested to exit, caller should shut down.
                   3362: #     1        - Continue processing.
                   3363: #
                   3364: sub increment_user_value_handler {
                   3365:     my ($cmd, $tail, $client) = @_;
                   3366:     
                   3367:     my $userinput   = "$cmd:$tail";
                   3368:     
                   3369:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
                   3370:     if ($namespace ne 'roles') {
                   3371:         chomp($what);
                   3372: 	my $hashref = &tie_user_hash($udom, $uname,
                   3373: 				     $namespace, &GDBM_WRCREAT(),
                   3374: 				     "P",$what);
                   3375: 	if ($hashref) {
                   3376: 	    my @pairs=split(/\&/,$what);
                   3377: 	    foreach my $pair (@pairs) {
                   3378: 		my ($key,$value)=split(/=/,$pair);
1.284     raeburn  3379:                 $value = &unescape($value);
1.230     foxr     3380: 		# We could check that we have a number...
                   3381: 		if (! defined($value) || $value eq '') {
                   3382: 		    $value = 1;
                   3383: 		}
                   3384: 		$hashref->{$key}+=$value;
1.284     raeburn  3385:                 if ($namespace eq 'nohist_resourcetracker') {
                   3386:                     if ($hashref->{$key} < 0) {
                   3387:                         $hashref->{$key} = 0;
                   3388:                     }
                   3389:                 }
1.230     foxr     3390: 	    }
1.311     albertel 3391: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     3392: 		&Reply( $client, "ok\n", $userinput);
                   3393: 	    } else {
                   3394: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3395: 			 "while attempting inc\n", $userinput);
                   3396: 	    }
                   3397: 	} else {
                   3398: 	    &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3399: 		     "while attempting inc\n", $userinput);
                   3400: 	}
                   3401:     } else {
                   3402: 	&Failure($client, "refused\n", $userinput);
                   3403:     }
                   3404:     
                   3405:     return 1;
                   3406: }
                   3407: &register_handler("inc", \&increment_user_value_handler, 0, 1, 0);
                   3408: 
                   3409: #
                   3410: #   Put a new role for a user.  Roles are LonCAPA's packaging of permissions.
                   3411: #   Each 'role' a user has implies a set of permissions.  Adding a new role
                   3412: #   for a person grants the permissions packaged with that role
                   3413: #   to that user when the role is selected.
                   3414: #
                   3415: # Parameters:
                   3416: #    $cmd       - The command string (rolesput).
                   3417: #    $tail      - The remainder of the request line.  For rolesput this
                   3418: #                 consists of a colon separated list that contains:
                   3419: #                 The domain and user that is granting the role (logged).
                   3420: #                 The domain and user that is getting the role.
                   3421: #                 The roles being granted as a set of & separated pairs.
                   3422: #                 each pair a key value pair.
                   3423: #    $client    - File descriptor connected to the client.
                   3424: # Returns:
                   3425: #     0         - If the daemon should exit
                   3426: #     1         - To continue processing.
                   3427: #
                   3428: #
                   3429: sub roles_put_handler {
                   3430:     my ($cmd, $tail, $client) = @_;
                   3431: 
                   3432:     my $userinput  = "$cmd:$tail";
                   3433: 
                   3434:     my ( $exedom, $exeuser, $udom, $uname,  $what) = split(/:/,$tail);
                   3435:     
                   3436: 
                   3437:     my $namespace='roles';
                   3438:     chomp($what);
                   3439:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3440: 				 &GDBM_WRCREAT(), "P",
                   3441: 				 "$exedom:$exeuser:$what");
                   3442:     #
                   3443:     #  Log the attempt to set a role.  The {}'s here ensure that the file 
                   3444:     #  handle is open for the minimal amount of time.  Since the flush
                   3445:     #  is done on close this improves the chances the log will be an un-
                   3446:     #  corrupted ordered thing.
                   3447:     if ($hashref) {
1.261     foxr     3448: 	my $pass_entry = &get_auth_type($udom, $uname);
                   3449: 	my ($auth_type,$pwd)  = split(/:/, $pass_entry);
                   3450: 	$auth_type = $auth_type.":";
1.230     foxr     3451: 	my @pairs=split(/\&/,$what);
                   3452: 	foreach my $pair (@pairs) {
                   3453: 	    my ($key,$value)=split(/=/,$pair);
                   3454: 	    &manage_permissions($key, $udom, $uname,
1.260     foxr     3455: 			       $auth_type);
1.230     foxr     3456: 	    $hashref->{$key}=$value;
                   3457: 	}
1.311     albertel 3458: 	if (&untie_user_hash($hashref)) {
1.230     foxr     3459: 	    &Reply($client, "ok\n", $userinput);
                   3460: 	} else {
                   3461: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3462: 		     "while attempting rolesput\n", $userinput);
                   3463: 	}
                   3464:     } else {
                   3465: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3466: 		 "while attempting rolesput\n", $userinput);
                   3467:     }
                   3468:     return 1;
                   3469: }
                   3470: &register_handler("rolesput", \&roles_put_handler, 1,1,0);  # Encoded client only.
                   3471: 
                   3472: #
1.231     foxr     3473: #   Deletes (removes) a role for a user.   This is equivalent to removing
                   3474: #  a permissions package associated with the role from the user's profile.
                   3475: #
                   3476: # Parameters:
                   3477: #     $cmd                 - The command (rolesdel)
                   3478: #     $tail                - The remainder of the request line. This consists
                   3479: #                             of:
                   3480: #                             The domain and user requesting the change (logged)
                   3481: #                             The domain and user being changed.
                   3482: #                             The roles being revoked.  These are shipped to us
                   3483: #                             as a bunch of & separated role name keywords.
                   3484: #     $client              - The file handle open on the client.
                   3485: # Returns:
                   3486: #     1                    - Continue processing
                   3487: #     0                    - Exit.
                   3488: #
                   3489: sub roles_delete_handler {
                   3490:     my ($cmd, $tail, $client)  = @_;
                   3491: 
                   3492:     my $userinput    = "$cmd:$tail";
                   3493:    
                   3494:     my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
                   3495:     &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
                   3496: 	   "what = ".$what);
                   3497:     my $namespace='roles';
                   3498:     chomp($what);
                   3499:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3500: 				 &GDBM_WRCREAT(), "D",
                   3501: 				 "$exedom:$exeuser:$what");
                   3502:     
                   3503:     if ($hashref) {
                   3504: 	my @rolekeys=split(/\&/,$what);
                   3505: 	
                   3506: 	foreach my $key (@rolekeys) {
                   3507: 	    delete $hashref->{$key};
                   3508: 	}
1.315     albertel 3509: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3510: 	    &Reply($client, "ok\n", $userinput);
                   3511: 	} else {
                   3512: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3513: 		     "while attempting rolesdel\n", $userinput);
                   3514: 	}
                   3515:     } else {
                   3516:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3517: 		 "while attempting rolesdel\n", $userinput);
                   3518:     }
                   3519:     
                   3520:     return 1;
                   3521: }
                   3522: &register_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
                   3523: 
                   3524: # Unencrypted get from a user's profile database.  See 
                   3525: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
                   3526: # This function retrieves a keyed item from a specific named database in the
                   3527: # user's directory.
                   3528: #
                   3529: # Parameters:
                   3530: #   $cmd             - Command request keyword (get).
                   3531: #   $tail            - Tail of the command.  This is a colon separated list
                   3532: #                      consisting of the domain and username that uniquely
                   3533: #                      identifies the profile,
                   3534: #                      The 'namespace' which selects the gdbm file to 
                   3535: #                      do the lookup in, 
                   3536: #                      & separated list of keys to lookup.  Note that
                   3537: #                      the values are returned as an & separated list too.
                   3538: #   $client          - File descriptor open on the client.
                   3539: # Returns:
                   3540: #   1       - Continue processing.
                   3541: #   0       - Exit.
                   3542: #
                   3543: sub get_profile_entry {
                   3544:     my ($cmd, $tail, $client) = @_;
                   3545: 
                   3546:     my $userinput= "$cmd:$tail";
                   3547:    
                   3548:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   3549:     chomp($what);
1.255     foxr     3550: 
1.390     raeburn  3551: 
1.255     foxr     3552:     my $replystring = read_profile($udom, $uname, $namespace, $what);
                   3553:     my ($first) = split(/:/,$replystring);
                   3554:     if($first ne "error") {
1.387     albertel 3555: 	&Reply($client, \$replystring, $userinput);
1.231     foxr     3556:     } else {
1.255     foxr     3557: 	&Failure($client, $replystring." while attempting get\n", $userinput);
1.231     foxr     3558:     }
                   3559:     return 1;
1.255     foxr     3560: 
                   3561: 
1.231     foxr     3562: }
                   3563: &register_handler("get", \&get_profile_entry, 0,1,0);
                   3564: 
                   3565: #
                   3566: #  Process the encrypted get request.  Note that the request is sent
                   3567: #  in clear, but the reply is encrypted.  This is a small covert channel:
                   3568: #  information about the sensitive keys is given to the snooper.  Just not
                   3569: #  information about the values of the sensitive key.  Hmm if I wanted to
                   3570: #  know these I'd snoop for the egets. Get the profile item names from them
                   3571: #  and then issue a get for them since there's no enforcement of the
                   3572: #  requirement of an encrypted get for particular profile items.  If I
                   3573: #  were re-doing this, I'd force the request to be encrypted as well as the
                   3574: #  reply.  I'd also just enforce encrypted transactions for all gets since
                   3575: #  that would prevent any covert channel snooping.
                   3576: #
                   3577: #  Parameters:
                   3578: #     $cmd               - Command keyword of request (eget).
1.536     raeburn  3579: #     $tail              - Tail of the command.  See GetProfileEntry
                   3580: #                          for more information about this.
1.231     foxr     3581: #     $client            - File open on the client.
                   3582: #  Returns:
                   3583: #     1      - Continue processing
                   3584: #     0      - server should exit.
                   3585: sub get_profile_entry_encrypted {
                   3586:     my ($cmd, $tail, $client) = @_;
                   3587: 
                   3588:     my $userinput = "$cmd:$tail";
                   3589:    
1.339     albertel 3590:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
1.231     foxr     3591:     chomp($what);
1.255     foxr     3592:     my $qresult = read_profile($udom, $uname, $namespace, $what);
                   3593:     my ($first) = split(/:/, $qresult);
                   3594:     if($first ne "error") {
                   3595: 	
                   3596: 	if ($cipher) {
                   3597: 	    my $cmdlength=length($qresult);
                   3598: 	    $qresult.="         ";
                   3599: 	    my $encqresult='';
                   3600: 	    for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   3601: 		$encqresult.= unpack("H16", 
                   3602: 				     $cipher->encrypt(substr($qresult,
                   3603: 							     $encidx,
                   3604: 							     8)));
                   3605: 	    }
                   3606: 	    &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
                   3607: 	} else {
1.231     foxr     3608: 		&Failure( $client, "error:no_key\n", $userinput);
                   3609: 	    }
                   3610:     } else {
1.255     foxr     3611: 	&Failure($client, "$qresult while attempting eget\n", $userinput);
                   3612: 
1.231     foxr     3613:     }
                   3614:     
                   3615:     return 1;
                   3616: }
1.255     foxr     3617: &register_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
1.263     albertel 3618: 
1.231     foxr     3619: #
                   3620: #   Deletes a key in a user profile database.
                   3621: #   
                   3622: #   Parameters:
                   3623: #       $cmd                  - Command keyword (del).
                   3624: #       $tail                 - Command tail.  IN this case a colon
                   3625: #                               separated list containing:
                   3626: #                               The domain and user that identifies uniquely
                   3627: #                               the identity of the user.
                   3628: #                               The profile namespace (name of the profile
                   3629: #                               database file).
                   3630: #                               & separated list of keywords to delete.
                   3631: #       $client              - File open on client socket.
                   3632: # Returns:
                   3633: #     1   - Continue processing
                   3634: #     0   - Exit server.
                   3635: #
                   3636: #
                   3637: sub delete_profile_entry {
                   3638:     my ($cmd, $tail, $client) = @_;
                   3639: 
                   3640:     my $userinput = "cmd:$tail";
                   3641: 
                   3642:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   3643:     chomp($what);
                   3644:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3645: 				 &GDBM_WRCREAT(),
                   3646: 				 "D",$what);
                   3647:     if ($hashref) {
                   3648:         my @keys=split(/\&/,$what);
                   3649: 	foreach my $key (@keys) {
                   3650: 	    delete($hashref->{$key});
                   3651: 	}
1.315     albertel 3652: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3653: 	    &Reply($client, "ok\n", $userinput);
                   3654: 	} else {
                   3655: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3656: 		    "while attempting del\n", $userinput);
                   3657: 	}
                   3658:     } else {
                   3659: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3660: 		 "while attempting del\n", $userinput);
                   3661:     }
                   3662:     return 1;
                   3663: }
                   3664: &register_handler("del", \&delete_profile_entry, 0, 1, 0);
1.263     albertel 3665: 
1.231     foxr     3666: #
                   3667: #  List the set of keys that are defined in a profile database file.
                   3668: #  A successful reply from this will contain an & separated list of
                   3669: #  the keys. 
                   3670: # Parameters:
                   3671: #     $cmd              - Command request (keys).
                   3672: #     $tail             - Remainder of the request, a colon separated
                   3673: #                         list containing domain/user that identifies the
                   3674: #                         user being queried, and the database namespace
                   3675: #                         (database filename essentially).
                   3676: #     $client           - File open on the client.
                   3677: #  Returns:
                   3678: #    1    - Continue processing.
                   3679: #    0    - Exit the server.
                   3680: #
                   3681: sub get_profile_keys {
                   3682:     my ($cmd, $tail, $client) = @_;
                   3683: 
                   3684:     my $userinput = "$cmd:$tail";
                   3685: 
                   3686:     my ($udom,$uname,$namespace)=split(/:/,$tail);
                   3687:     my $qresult='';
                   3688:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3689: 				  &GDBM_READER());
                   3690:     if ($hashref) {
                   3691: 	foreach my $key (keys %$hashref) {
                   3692: 	    $qresult.="$key&";
                   3693: 	}
1.315     albertel 3694: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3695: 	    $qresult=~s/\&$//;
1.387     albertel 3696: 	    &Reply($client, \$qresult, $userinput);
1.231     foxr     3697: 	} else {
                   3698: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3699: 		    "while attempting keys\n", $userinput);
                   3700: 	}
                   3701:     } else {
                   3702: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3703: 		 "while attempting keys\n", $userinput);
                   3704:     }
                   3705:    
                   3706:     return 1;
                   3707: }
                   3708: &register_handler("keys", \&get_profile_keys, 0, 1, 0);
                   3709: 
                   3710: #
                   3711: #   Dump the contents of a user profile database.
                   3712: #   Note that this constitutes a very large covert channel too since
                   3713: #   the dump will return sensitive information that is not encrypted.
                   3714: #   The naive security assumption is that the session negotiation ensures
                   3715: #   our client is trusted and I don't believe that's assured at present.
                   3716: #   Sure want badly to go to ssl or tls.  Of course if my peer isn't really
                   3717: #   a LonCAPA node they could have negotiated an encryption key too so >sigh<.
                   3718: # 
                   3719: #  Parameters:
                   3720: #     $cmd           - The command request keyword (currentdump).
                   3721: #     $tail          - Remainder of the request, consisting of a colon
                   3722: #                      separated list that has the domain/username and
                   3723: #                      the namespace to dump (database file).
                   3724: #     $client        - file open on the remote client.
                   3725: # Returns:
                   3726: #     1    - Continue processing.
                   3727: #     0    - Exit the server.
                   3728: #
                   3729: sub dump_profile_database {
                   3730:     my ($cmd, $tail, $client) = @_;
                   3731: 
1.494     droeschl 3732:     my $res = LONCAPA::Lond::dump_profile_database($tail);
                   3733: 
                   3734:     if ($res =~ /^error:/) {
                   3735:         Failure($client, \$res, "$cmd:$tail");
                   3736:     } else {
                   3737:         Reply($client, \$res, "$cmd:$tail");
                   3738:     }
                   3739: 
                   3740:     return 1;  
                   3741: 
                   3742:     #TODO remove 
1.231     foxr     3743:     my $userinput = "$cmd:$tail";
                   3744:    
                   3745:     my ($udom,$uname,$namespace) = split(/:/,$tail);
                   3746:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3747: 				 &GDBM_READER());
                   3748:     if ($hashref) {
                   3749: 	# Structure of %data:
                   3750: 	# $data{$symb}->{$parameter}=$value;
                   3751: 	# $data{$symb}->{'v.'.$parameter}=$version;
                   3752: 	# since $parameter will be unescaped, we do not
                   3753:  	# have to worry about silly parameter names...
                   3754: 	
                   3755:         my $qresult='';
                   3756: 	my %data = ();                     # A hash of anonymous hashes..
                   3757: 	while (my ($key,$value) = each(%$hashref)) {
                   3758: 	    my ($v,$symb,$param) = split(/:/,$key);
                   3759: 	    next if ($v eq 'version' || $symb eq 'keys');
                   3760: 	    next if (exists($data{$symb}) && 
                   3761: 		     exists($data{$symb}->{$param}) &&
                   3762: 		     $data{$symb}->{'v.'.$param} > $v);
                   3763: 	    $data{$symb}->{$param}=$value;
                   3764: 	    $data{$symb}->{'v.'.$param}=$v;
                   3765: 	}
1.311     albertel 3766: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3767: 	    while (my ($symb,$param_hash) = each(%data)) {
                   3768: 		while(my ($param,$value) = each (%$param_hash)){
                   3769: 		    next if ($param =~ /^v\./);       # Ignore versions...
                   3770: 		    #
                   3771: 		    #   Just dump the symb=value pairs separated by &
                   3772: 		    #
                   3773: 		    $qresult.=$symb.':'.$param.'='.$value.'&';
                   3774: 		}
                   3775: 	    }
                   3776: 	    chop($qresult);
1.387     albertel 3777: 	    &Reply($client , \$qresult, $userinput);
1.231     foxr     3778: 	} else {
                   3779: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3780: 		     "while attempting currentdump\n", $userinput);
                   3781: 	}
                   3782:     } else {
                   3783: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3784: 		"while attempting currentdump\n", $userinput);
                   3785:     }
                   3786: 
                   3787:     return 1;
                   3788: }
                   3789: &register_handler("currentdump", \&dump_profile_database, 0, 1, 0);
                   3790: 
                   3791: #
                   3792: #   Dump a profile database with an optional regular expression
                   3793: #   to match against the keys.  In this dump, no effort is made
                   3794: #   to separate symb from version information. Presumably the
                   3795: #   databases that are dumped by this command are of a different
                   3796: #   structure.  Need to look at this and improve the documentation of
                   3797: #   both this and the currentdump handler.
                   3798: # Parameters:
                   3799: #    $cmd                     - The command keyword.
                   3800: #    $tail                    - All of the characters after the $cmd:
                   3801: #                               These are expected to be a colon
                   3802: #                               separated list containing:
                   3803: #                               domain/user - identifying the user.
                   3804: #                               namespace   - identifying the database.
                   3805: #                               regexp      - optional regular expression
                   3806: #                                             that is matched against
                   3807: #                                             database keywords to do
                   3808: #                                             selective dumps.
1.488     raeburn  3809: #                               range       - optional range of entries
                   3810: #                                             e.g., 10-20 would return the
                   3811: #                                             10th to 19th items, etc.  
1.231     foxr     3812: #   $client                   - Channel open on the client.
                   3813: # Returns:
                   3814: #    1    - Continue processing.
                   3815: # Side effects:
                   3816: #    response is written to $client.
                   3817: #
                   3818: sub dump_with_regexp {
                   3819:     my ($cmd, $tail, $client) = @_;
                   3820: 
1.494     droeschl 3821:     my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
1.490     droeschl 3822:     
                   3823:     if ($res =~ /^error:/) {
                   3824:         Failure($client, \$res, "$cmd:$tail");
                   3825:     } else {
                   3826:         Reply($client, \$res, "$cmd:$tail");
                   3827:     }
1.231     foxr     3828: 
                   3829:     return 1;
                   3830: }
                   3831: &register_handler("dump", \&dump_with_regexp, 0, 1, 0);
                   3832: 
1.568   ! raeburn  3833: #
        !          3834: #  Process the encrypted dump request. Original call should
        !          3835: #  be from lonnet::dump() with seventh arg ($encrypt) set to
        !          3836: #  1, to ensure that both request and response are encrypted.
        !          3837: #
        !          3838: #  Parameters:
        !          3839: #     $cmd               - Command keyword of request (edump).
        !          3840: #     $tail              - Tail of the command.
        !          3841: #                          See &dump_with_regexp for more
        !          3842: #                          information about this.
        !          3843: #     $client            - File open on the client.
        !          3844: #  Returns:
        !          3845: #     1      - Continue processing
        !          3846: #     0      - server should exit.
        !          3847: #
        !          3848: 
        !          3849: sub encrypted_dump_with_regexp {
        !          3850:     my ($cmd, $tail, $client) = @_;
        !          3851:     my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
        !          3852: 
        !          3853:     if ($res =~ /^error:/) {
        !          3854:         Failure($client, \$res, "$cmd:$tail");
        !          3855:     } else {
        !          3856:         if ($cipher) {
        !          3857:             my $cmdlength=length($res);
        !          3858:             $res.="         ";
        !          3859:             my $encres='';
        !          3860:             for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
        !          3861:                 $encres.= unpack("H16",
        !          3862:                                  $cipher->encrypt(substr($res,
        !          3863:                                                          $encidx,
        !          3864:                                                          8)));
        !          3865:             }
        !          3866:             &Reply( $client,"enc:$cmdlength:$encres\n","$cmd:$tail");
        !          3867:         } else {
        !          3868:             &Failure( $client, "error:no_key\n","$cmd:$tail");
        !          3869:         }
        !          3870:     }
        !          3871: }
        !          3872: &register_handler("edump", \&encrypted_dump_with_regexp, 0, 1, 0);
        !          3873: 
1.231     foxr     3874: #  Store a set of key=value pairs associated with a versioned name.
                   3875: #
                   3876: #  Parameters:
                   3877: #    $cmd                - Request command keyword.
                   3878: #    $tail               - Tail of the request.  This is a colon
                   3879: #                          separated list containing:
                   3880: #                          domain/user - User and authentication domain.
                   3881: #                          namespace   - Name of the database being modified
                   3882: #                          rid         - Resource keyword to modify.
                   3883: #                          what        - new value associated with rid.
1.512     raeburn  3884: #                          laststore   - (optional) version=timestamp
                   3885: #                                        for most recent transaction for rid
                   3886: #                                        in namespace, when cstore was called
1.231     foxr     3887: #
                   3888: #    $client             - Socket open on the client.
                   3889: #
                   3890: #
                   3891: #  Returns:
                   3892: #      1 (keep on processing).
                   3893: #  Side-Effects:
                   3894: #    Writes to the client
1.512     raeburn  3895: #    Successful storage will cause either 'ok', or, if $laststore was included
                   3896: #    in the tail of the request, and the version number for the last transaction
                   3897: #    is larger than the version in $laststore, delay:$numtrans , where $numtrans
                   3898: #    is the number of store evevnts recorded for rid in namespace since
                   3899: #    lonnet::store() was called by the client.
                   3900: #
1.231     foxr     3901: sub store_handler {
                   3902:     my ($cmd, $tail, $client) = @_;
                   3903:  
                   3904:     my $userinput = "$cmd:$tail";
1.512     raeburn  3905:     chomp($tail);
                   3906:     my ($udom,$uname,$namespace,$rid,$what,$laststore) =split(/:/,$tail);
1.231     foxr     3907:     if ($namespace ne 'roles') {
                   3908: 
                   3909: 	my @pairs=split(/\&/,$what);
                   3910: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
1.268     albertel 3911: 				       &GDBM_WRCREAT(), "S",
1.231     foxr     3912: 				       "$rid:$what");
                   3913: 	if ($hashref) {
                   3914: 	    my $now = time;
1.512     raeburn  3915:             my $numtrans;
                   3916:             if ($laststore) {
                   3917:                 my ($previousversion,$previoustime) = split(/\=/,$laststore);
                   3918:                 my ($lastversion,$lasttime) = (0,0);
                   3919:                 $lastversion = $hashref->{"version:$rid"};
                   3920:                 if ($lastversion) {
                   3921:                     $lasttime = $hashref->{"$lastversion:$rid:timestamp"};
                   3922:                 }
                   3923:                 if (($previousversion) && ($previousversion !~ /\D/)) {
                   3924:                     if (($lastversion > $previousversion) && ($lasttime >= $previoustime)) {
                   3925:                         $numtrans = $lastversion - $previousversion;
                   3926:                     }
                   3927:                 } elsif ($lastversion) {
                   3928:                     $numtrans = $lastversion;
                   3929:                 }
                   3930:                 if ($numtrans) {
                   3931:                     $numtrans =~ s/D//g;
                   3932:                 }
                   3933:             }
1.231     foxr     3934: 	    $hashref->{"version:$rid"}++;
                   3935: 	    my $version=$hashref->{"version:$rid"};
                   3936: 	    my $allkeys=''; 
                   3937: 	    foreach my $pair (@pairs) {
                   3938: 		my ($key,$value)=split(/=/,$pair);
                   3939: 		$allkeys.=$key.':';
                   3940: 		$hashref->{"$version:$rid:$key"}=$value;
                   3941: 	    }
                   3942: 	    $hashref->{"$version:$rid:timestamp"}=$now;
                   3943: 	    $allkeys.='timestamp';
                   3944: 	    $hashref->{"$version:keys:$rid"}=$allkeys;
1.311     albertel 3945: 	    if (&untie_user_hash($hashref)) {
1.512     raeburn  3946:                 my $msg = 'ok';
                   3947:                 if ($numtrans) {
                   3948:                     $msg = 'delay:'.$numtrans;
                   3949:                 }
                   3950: 		&Reply($client, "$msg\n", $userinput);
1.231     foxr     3951: 	    } else {
                   3952: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3953: 			"while attempting store\n", $userinput);
                   3954: 	    }
                   3955: 	} else {
                   3956: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3957: 		     "while attempting store\n", $userinput);
                   3958: 	}
                   3959:     } else {
                   3960: 	&Failure($client, "refused\n", $userinput);
                   3961:     }
                   3962: 
                   3963:     return 1;
                   3964: }
                   3965: &register_handler("store", \&store_handler, 0, 1, 0);
1.263     albertel 3966: 
1.323     albertel 3967: #  Modify a set of key=value pairs associated with a versioned name.
                   3968: #
                   3969: #  Parameters:
                   3970: #    $cmd                - Request command keyword.
                   3971: #    $tail               - Tail of the request.  This is a colon
                   3972: #                          separated list containing:
                   3973: #                          domain/user - User and authentication domain.
                   3974: #                          namespace   - Name of the database being modified
                   3975: #                          rid         - Resource keyword to modify.
                   3976: #                          v           - Version item to modify
                   3977: #                          what        - new value associated with rid.
                   3978: #
                   3979: #    $client             - Socket open on the client.
                   3980: #
                   3981: #
                   3982: #  Returns:
                   3983: #      1 (keep on processing).
                   3984: #  Side-Effects:
                   3985: #    Writes to the client
                   3986: sub putstore_handler {
                   3987:     my ($cmd, $tail, $client) = @_;
                   3988:  
                   3989:     my $userinput = "$cmd:$tail";
                   3990: 
                   3991:     my ($udom,$uname,$namespace,$rid,$v,$what) =split(/:/,$tail);
                   3992:     if ($namespace ne 'roles') {
                   3993: 
                   3994: 	chomp($what);
                   3995: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
                   3996: 				       &GDBM_WRCREAT(), "M",
                   3997: 				       "$rid:$v:$what");
                   3998: 	if ($hashref) {
                   3999: 	    my $now = time;
                   4000: 	    my %data = &hash_extract($what);
                   4001: 	    my @allkeys;
                   4002: 	    while (my($key,$value) = each(%data)) {
                   4003: 		push(@allkeys,$key);
                   4004: 		$hashref->{"$v:$rid:$key"} = $value;
                   4005: 	    }
                   4006: 	    my $allkeys = join(':',@allkeys);
                   4007: 	    $hashref->{"$v:keys:$rid"}=$allkeys;
                   4008: 
                   4009: 	    if (&untie_user_hash($hashref)) {
                   4010: 		&Reply($client, "ok\n", $userinput);
                   4011: 	    } else {
                   4012: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4013: 			"while attempting store\n", $userinput);
                   4014: 	    }
                   4015: 	} else {
                   4016: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4017: 		     "while attempting store\n", $userinput);
                   4018: 	}
                   4019:     } else {
                   4020: 	&Failure($client, "refused\n", $userinput);
                   4021:     }
                   4022: 
                   4023:     return 1;
                   4024: }
                   4025: &register_handler("putstore", \&putstore_handler, 0, 1, 0);
                   4026: 
                   4027: sub hash_extract {
                   4028:     my ($str)=@_;
                   4029:     my %hash;
                   4030:     foreach my $pair (split(/\&/,$str)) {
                   4031: 	my ($key,$value)=split(/=/,$pair);
                   4032: 	$hash{$key}=$value;
                   4033:     }
                   4034:     return (%hash);
                   4035: }
                   4036: sub hash_to_str {
                   4037:     my ($hash_ref)=@_;
                   4038:     my $str;
                   4039:     foreach my $key (keys(%$hash_ref)) {
                   4040: 	$str.=$key.'='.$hash_ref->{$key}.'&';
                   4041:     }
                   4042:     $str=~s/\&$//;
                   4043:     return $str;
                   4044: }
                   4045: 
1.231     foxr     4046: #
                   4047: #  Dump out all versions of a resource that has key=value pairs associated
                   4048: # with it for each version.  These resources are built up via the store
                   4049: # command.
                   4050: #
                   4051: #  Parameters:
                   4052: #     $cmd               - Command keyword.
                   4053: #     $tail              - Remainder of the request which consists of:
                   4054: #                          domain/user   - User and auth. domain.
                   4055: #                          namespace     - name of resource database.
                   4056: #                          rid           - Resource id.
                   4057: #    $client             - socket open on the client.
                   4058: #
                   4059: # Returns:
                   4060: #      1  indicating the caller should not yet exit.
                   4061: # Side-effects:
                   4062: #   Writes a reply to the client.
                   4063: #   The reply is a string of the following shape:
                   4064: #   version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
                   4065: #    Where the 1 above represents version 1.
                   4066: #    this continues for all pairs of keys in all versions.
                   4067: #
                   4068: #
                   4069: #    
                   4070: #
                   4071: sub restore_handler {
                   4072:     my ($cmd, $tail, $client) = @_;
                   4073: 
                   4074:     my $userinput = "$cmd:$tail";	# Only used for logging purposes.
1.351     banghart 4075:     my ($udom,$uname,$namespace,$rid) = split(/:/,$tail);
1.352     albertel 4076:     $namespace=~s/\//\_/g;
1.350     albertel 4077:     $namespace = &LONCAPA::clean_username($namespace);
1.349     albertel 4078: 
1.231     foxr     4079:     chomp($rid);
                   4080:     my $qresult='';
1.309     albertel 4081:     my $hashref = &tie_user_hash($udom, $uname, $namespace, &GDBM_READER());
                   4082:     if ($hashref) {
                   4083: 	my $version=$hashref->{"version:$rid"};
1.231     foxr     4084: 	$qresult.="version=$version&";
                   4085: 	my $scope;
                   4086: 	for ($scope=1;$scope<=$version;$scope++) {
1.309     albertel 4087: 	    my $vkeys=$hashref->{"$scope:keys:$rid"};
1.231     foxr     4088: 	    my @keys=split(/:/,$vkeys);
                   4089: 	    my $key;
                   4090: 	    $qresult.="$scope:keys=$vkeys&";
                   4091: 	    foreach $key (@keys) {
1.309     albertel 4092: 		$qresult.="$scope:$key=".$hashref->{"$scope:$rid:$key"}."&";
1.231     foxr     4093: 	    }                                  
                   4094: 	}
1.311     albertel 4095: 	if (&untie_user_hash($hashref)) {
1.231     foxr     4096: 	    $qresult=~s/\&$//;
1.387     albertel 4097: 	    &Reply( $client, \$qresult, $userinput);
1.231     foxr     4098: 	} else {
                   4099: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4100: 		    "while attempting restore\n", $userinput);
                   4101: 	}
                   4102:     } else {
                   4103: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4104: 		"while attempting restore\n", $userinput);
                   4105:     }
                   4106:   
                   4107:     return 1;
                   4108: 
                   4109: 
                   4110: }
                   4111: &register_handler("restore", \&restore_handler, 0,1,0);
1.234     foxr     4112: 
                   4113: #
1.324     raeburn  4114: #   Add a chat message to a synchronous discussion board.
1.234     foxr     4115: #
                   4116: # Parameters:
                   4117: #    $cmd                - Request keyword.
                   4118: #    $tail               - Tail of the command. A colon separated list
                   4119: #                          containing:
                   4120: #                          cdom    - Domain on which the chat board lives
1.324     raeburn  4121: #                          cnum    - Course containing the chat board.
                   4122: #                          newpost - Body of the posting.
                   4123: #                          group   - Optional group, if chat board is only 
                   4124: #                                    accessible in a group within the course 
1.234     foxr     4125: #   $client              - Socket open on the client.
                   4126: # Returns:
                   4127: #   1    - Indicating caller should keep on processing.
                   4128: #
                   4129: # Side-effects:
                   4130: #   writes a reply to the client.
                   4131: #
                   4132: #
                   4133: sub send_chat_handler {
                   4134:     my ($cmd, $tail, $client) = @_;
                   4135: 
                   4136:     
                   4137:     my $userinput = "$cmd:$tail";
                   4138: 
1.324     raeburn  4139:     my ($cdom,$cnum,$newpost,$group)=split(/\:/,$tail);
                   4140:     &chat_add($cdom,$cnum,$newpost,$group);
1.234     foxr     4141:     &Reply($client, "ok\n", $userinput);
                   4142: 
                   4143:     return 1;
                   4144: }
                   4145: &register_handler("chatsend", \&send_chat_handler, 0, 1, 0);
1.263     albertel 4146: 
1.234     foxr     4147: #
1.324     raeburn  4148: #   Retrieve the set of chat messages from a discussion board.
1.234     foxr     4149: #
                   4150: #  Parameters:
                   4151: #    $cmd             - Command keyword that initiated the request.
                   4152: #    $tail            - Remainder of the request after the command
                   4153: #                       keyword.  In this case a colon separated list of
                   4154: #                       chat domain    - Which discussion board.
                   4155: #                       chat id        - Discussion thread(?)
                   4156: #                       domain/user    - Authentication domain and username
                   4157: #                                        of the requesting person.
1.324     raeburn  4158: #                       group          - Optional course group containing
                   4159: #                                        the board.      
1.234     foxr     4160: #   $client           - Socket open on the client program.
                   4161: # Returns:
                   4162: #    1     - continue processing
                   4163: # Side effects:
                   4164: #    Response is written to the client.
                   4165: #
                   4166: sub retrieve_chat_handler {
                   4167:     my ($cmd, $tail, $client) = @_;
                   4168: 
                   4169: 
                   4170:     my $userinput = "$cmd:$tail";
                   4171: 
1.324     raeburn  4172:     my ($cdom,$cnum,$udom,$uname,$group)=split(/\:/,$tail);
1.234     foxr     4173:     my $reply='';
1.324     raeburn  4174:     foreach (&get_chat($cdom,$cnum,$udom,$uname,$group)) {
1.234     foxr     4175: 	$reply.=&escape($_).':';
                   4176:     }
                   4177:     $reply=~s/\:$//;
1.387     albertel 4178:     &Reply($client, \$reply, $userinput);
1.234     foxr     4179: 
                   4180: 
                   4181:     return 1;
                   4182: }
                   4183: &register_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
                   4184: 
                   4185: #
                   4186: #  Initiate a query of an sql database.  SQL query repsonses get put in
                   4187: #  a file for later retrieval.  This prevents sql query results from
                   4188: #  bottlenecking the system.  Note that with loncnew, perhaps this is
                   4189: #  less of an issue since multiple outstanding requests can be concurrently
                   4190: #  serviced.
                   4191: #
                   4192: #  Parameters:
1.535     raeburn  4193: #     $cmd       - Command keyword that initiated the request.
1.234     foxr     4194: #     $tail      - Remainder of the command after the keyword.
                   4195: #                  For this function, this consists of a query and
                   4196: #                  3 arguments that are self-documentingly labelled
                   4197: #                  in the original arg1, arg2, arg3.
                   4198: #     $client    - Socket open on the client.
                   4199: # Return:
                   4200: #    1   - Indicating processing should continue.
                   4201: # Side-effects:
                   4202: #    a reply is written to $client.
                   4203: #
                   4204: sub send_query_handler {
                   4205:     my ($cmd, $tail, $client) = @_;
                   4206: 
                   4207:     my $userinput = "$cmd:$tail";
                   4208: 
                   4209:     my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
                   4210:     $query=~s/\n*$//g;
1.534     raeburn  4211:     if (($query eq 'usersearch') || ($query eq 'instdirsearch')) {
                   4212:         my $usersearchconf = &get_usersearch_config($currentdomainid,'directorysrch');
                   4213:         my $earlyout;
                   4214:         if (ref($usersearchconf) eq 'HASH') {
                   4215:             if ($currentdomainid eq $clienthomedom) {
                   4216:                 if ($query eq 'usersearch') {
                   4217:                     if ($usersearchconf->{'lcavailable'} eq '0') {
                   4218:                         $earlyout = 1;
                   4219:                     }
                   4220:                 } else {
                   4221:                     if ($usersearchconf->{'available'} eq '0') {
                   4222:                         $earlyout = 1;
                   4223:                     }
                   4224:                 }
                   4225:             } else {
                   4226:                 if ($query eq 'usersearch') {
                   4227:                     if ($usersearchconf->{'lclocalonly'}) {
                   4228:                         $earlyout = 1;
                   4229:                     }
                   4230:                 } else {
                   4231:                     if ($usersearchconf->{'localonly'}) {
                   4232:                         $earlyout = 1;
                   4233:                     }
                   4234:                 }
                   4235:             }
                   4236:         }
                   4237:         if ($earlyout) {
                   4238:             &Reply($client, "query_not_authorized\n");
                   4239:             return 1;
                   4240:         }
                   4241:     }
1.234     foxr     4242:     &Reply($client, "". &sql_reply("$clientname\&$query".
                   4243: 				"\&$arg1"."\&$arg2"."\&$arg3")."\n",
                   4244: 	  $userinput);
                   4245:     
                   4246:     return 1;
                   4247: }
                   4248: &register_handler("querysend", \&send_query_handler, 0, 1, 0);
                   4249: 
                   4250: #
                   4251: #   Add a reply to an sql query.  SQL queries are done asyncrhonously.
                   4252: #   The query is submitted via a "querysend" transaction.
                   4253: #   There it is passed on to the lonsql daemon, queued and issued to
                   4254: #   mysql.
                   4255: #     This transaction is invoked when the sql transaction is complete
                   4256: #   it stores the query results in flie and indicates query completion.
                   4257: #   presumably local software then fetches this response... I'm guessing
                   4258: #   the sequence is: lonc does a querysend, we ask lonsql to do it.
                   4259: #   lonsql on completion of the query interacts with the lond of our
                   4260: #   client to do a query reply storing two files:
                   4261: #    - id     - The results of the query.
                   4262: #    - id.end - Indicating the transaction completed. 
                   4263: #    NOTE: id is a unique id assigned to the query and querysend time.
                   4264: # Parameters:
                   4265: #    $cmd        - Command keyword that initiated this request.
                   4266: #    $tail       - Remainder of the tail.  In this case that's a colon
                   4267: #                  separated list containing the query Id and the 
                   4268: #                  results of the query.
                   4269: #    $client     - Socket open on the client.
                   4270: # Return:
                   4271: #    1           - Indicating that we should continue processing.
                   4272: # Side effects:
                   4273: #    ok written to the client.
                   4274: #
                   4275: sub reply_query_handler {
                   4276:     my ($cmd, $tail, $client) = @_;
                   4277: 
                   4278: 
                   4279:     my $userinput = "$cmd:$tail";
                   4280: 
1.339     albertel 4281:     my ($id,$reply)=split(/:/,$tail); 
1.234     foxr     4282:     my $store;
                   4283:     my $execdir=$perlvar{'lonDaemons'};
                   4284:     if ($store=IO::File->new(">$execdir/tmp/$id")) {
                   4285: 	$reply=~s/\&/\n/g;
                   4286: 	print $store $reply;
                   4287: 	close $store;
                   4288: 	my $store2=IO::File->new(">$execdir/tmp/$id.end");
                   4289: 	print $store2 "done\n";
                   4290: 	close $store2;
                   4291: 	&Reply($client, "ok\n", $userinput);
                   4292:     } else {
                   4293: 	&Failure($client, "error: ".($!+0)
                   4294: 		." IO::File->new Failed ".
                   4295: 		"while attempting queryreply\n", $userinput);
                   4296:     }
                   4297:  
                   4298: 
                   4299:     return 1;
                   4300: }
                   4301: &register_handler("queryreply", \&reply_query_handler, 0, 1, 0);
                   4302: 
                   4303: #
                   4304: #  Process the courseidput request.  Not quite sure what this means
                   4305: #  at the system level sense.  It appears a gdbm file in the 
                   4306: #  /home/httpd/lonUsers/$domain/nohist_courseids is tied and
                   4307: #  a set of entries made in that database.
                   4308: #
                   4309: # Parameters:
                   4310: #   $cmd      - The command keyword that initiated this request.
                   4311: #   $tail     - Tail of the command.  In this case consists of a colon
                   4312: #               separated list contaning the domain to apply this to and
                   4313: #               an ampersand separated list of keyword=value pairs.
1.272     raeburn  4314: #               Each value is a colon separated list that includes:  
                   4315: #               description, institutional code and course owner.
                   4316: #               For backward compatibility with versions included
                   4317: #               in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
                   4318: #               code and/or course owner are preserved from the existing 
                   4319: #               record when writing a new record in response to 1.1 or 
                   4320: #               1.2 implementations of lonnet::flushcourselogs().   
                   4321: #                      
1.234     foxr     4322: #   $client   - Socket open on the client.
                   4323: # Returns:
                   4324: #   1    - indicating that processing should continue
                   4325: #
                   4326: # Side effects:
                   4327: #   reply is written to the client.
                   4328: #
                   4329: sub put_course_id_handler {
                   4330:     my ($cmd, $tail, $client) = @_;
                   4331: 
                   4332: 
                   4333:     my $userinput = "$cmd:$tail";
                   4334: 
1.266     raeburn  4335:     my ($udom, $what) = split(/:/, $tail,2);
1.234     foxr     4336:     chomp($what);
                   4337:     my $now=time;
                   4338:     my @pairs=split(/\&/,$what);
                   4339: 
                   4340:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   4341:     if ($hashref) {
                   4342: 	foreach my $pair (@pairs) {
1.271     raeburn  4343:             my ($key,$courseinfo) = split(/=/,$pair,2);
                   4344:             $courseinfo =~ s/=/:/g;
1.384     raeburn  4345:             if (defined($hashref->{$key})) {
                   4346:                 my $value = &Apache::lonnet::thaw_unescape($hashref->{$key});
                   4347:                 if (ref($value) eq 'HASH') {
                   4348:                     my @items = ('description','inst_code','owner','type');
                   4349:                     my @new_items = split(/:/,$courseinfo,-1);
                   4350:                     my %storehash; 
                   4351:                     for (my $i=0; $i<@new_items; $i++) {
1.391     raeburn  4352:                         $storehash{$items[$i]} = &unescape($new_items[$i]);
1.384     raeburn  4353:                     }
                   4354:                     $hashref->{$key} = 
                   4355:                         &Apache::lonnet::freeze_escape(\%storehash);
                   4356:                     my $unesc_key = &unescape($key);
                   4357:                     $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
                   4358:                     next;
1.383     raeburn  4359:                 }
1.384     raeburn  4360:             }
                   4361:             my @current_items = split(/:/,$hashref->{$key},-1);
                   4362:             shift(@current_items); # remove description
                   4363:             pop(@current_items);   # remove last access
                   4364:             my $numcurrent = scalar(@current_items);
                   4365:             if ($numcurrent > 3) {
                   4366:                 $numcurrent = 3;
                   4367:             }
                   4368:             my @new_items = split(/:/,$courseinfo,-1);
                   4369:             my $numnew = scalar(@new_items);
                   4370:             if ($numcurrent > 0) {
                   4371:                 if ($numnew <= $numcurrent) { # flushcourselogs() from pre 2.2 
                   4372:                     for (my $j=$numcurrent-$numnew; $j>=0; $j--) {
                   4373:                         $courseinfo .= ':'.$current_items[$numcurrent-$j-1];
1.333     raeburn  4374:                     }
1.272     raeburn  4375:                 }
                   4376:             }
1.384     raeburn  4377:             $hashref->{$key}=$courseinfo.':'.$now;
1.234     foxr     4378: 	}
1.311     albertel 4379: 	if (&untie_domain_hash($hashref)) {
1.253     foxr     4380: 	    &Reply( $client, "ok\n", $userinput);
1.234     foxr     4381: 	} else {
1.253     foxr     4382: 	    &Failure($client, "error: ".($!+0)
1.234     foxr     4383: 		     ." untie(GDBM) Failed ".
                   4384: 		     "while attempting courseidput\n", $userinput);
                   4385: 	}
                   4386:     } else {
1.253     foxr     4387: 	&Failure($client, "error: ".($!+0)
1.234     foxr     4388: 		 ." tie(GDBM) Failed ".
                   4389: 		 "while attempting courseidput\n", $userinput);
                   4390:     }
                   4391: 
                   4392:     return 1;
                   4393: }
                   4394: &register_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
                   4395: 
1.383     raeburn  4396: sub put_course_id_hash_handler {
                   4397:     my ($cmd, $tail, $client) = @_;
                   4398:     my $userinput = "$cmd:$tail";
1.384     raeburn  4399:     my ($udom,$mode,$what) = split(/:/, $tail,3);
1.383     raeburn  4400:     chomp($what);
                   4401:     my $now=time;
                   4402:     my @pairs=split(/\&/,$what);
1.384     raeburn  4403:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
1.383     raeburn  4404:     if ($hashref) {
                   4405:         foreach my $pair (@pairs) {
                   4406:             my ($key,$value)=split(/=/,$pair);
1.384     raeburn  4407:             my $unesc_key = &unescape($key);
                   4408:             if ($mode ne 'timeonly') {
                   4409:                 if (!defined($hashref->{&escape('lasttime:'.$unesc_key)})) {
                   4410:                     my $curritems = &Apache::lonnet::thaw_unescape($key); 
                   4411:                     if (ref($curritems) ne 'HASH') {
                   4412:                         my @current_items = split(/:/,$hashref->{$key},-1);
                   4413:                         my $lasttime = pop(@current_items);
                   4414:                         $hashref->{&escape('lasttime:'.$unesc_key)} = $lasttime;
                   4415:                     } else {
                   4416:                         $hashref->{&escape('lasttime:'.$unesc_key)} = '';
                   4417:                     }
                   4418:                 } 
                   4419:                 $hashref->{$key} = $value;
                   4420:             }
                   4421:             if ($mode ne 'notime') {
                   4422:                 $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
                   4423:             }
1.383     raeburn  4424:         }
                   4425:         if (&untie_domain_hash($hashref)) {
                   4426:             &Reply($client, "ok\n", $userinput);
                   4427:         } else {
                   4428:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4429:                      "while attempting courseidputhash\n", $userinput);
                   4430:         }
                   4431:     } else {
                   4432:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4433:                   "while attempting courseidputhash\n", $userinput);
                   4434:     }
                   4435:     return 1;
                   4436: }
                   4437: &register_handler("courseidputhash", \&put_course_id_hash_handler, 0, 1, 0);
                   4438: 
1.234     foxr     4439: #  Retrieves the value of a course id resource keyword pattern
                   4440: #  defined since a starting date.  Both the starting date and the
                   4441: #  keyword pattern are optional.  If the starting date is not supplied it
                   4442: #  is treated as the beginning of time.  If the pattern is not found,
                   4443: #  it is treatred as "." matching everything.
                   4444: #
                   4445: #  Parameters:
                   4446: #     $cmd     - Command keyword that resulted in us being dispatched.
                   4447: #     $tail    - The remainder of the command that, in this case, consists
                   4448: #                of a colon separated list of:
                   4449: #                 domain   - The domain in which the course database is 
                   4450: #                            defined.
                   4451: #                 since    - Optional parameter describing the minimum
                   4452: #                            time of definition(?) of the resources that
                   4453: #                            will match the dump.
                   4454: #                 description - regular expression that is used to filter
                   4455: #                            the dump.  Only keywords matching this regexp
                   4456: #                            will be used.
1.272     raeburn  4457: #                 institutional code - optional supplied code to filter 
                   4458: #                            the dump. Only courses with an institutional code 
                   4459: #                            that match the supplied code will be returned.
1.336     raeburn  4460: #                 owner    - optional supplied username and domain of owner to
                   4461: #                            filter the dump.  Only courses for which the course
                   4462: #                            owner matches the supplied username and/or domain
                   4463: #                            will be returned. Pre-2.2.0 legacy entries from 
                   4464: #                            nohist_courseiddump will only contain usernames.
1.384     raeburn  4465: #                 type     - optional parameter for selection 
1.418     raeburn  4466: #                 regexp_ok - if 1 or -1 allow the supplied institutional code
                   4467: #                            filter to behave as a regular expression:
                   4468: #	                      1 will not exclude the course if the instcode matches the RE 
                   4469: #                            -1 will exclude the course if the instcode matches the RE
1.384     raeburn  4470: #                 rtn_as_hash - whether to return the information available for
                   4471: #                            each matched item as a frozen hash of all 
                   4472: #                            key, value pairs in the item's hash, or as a 
                   4473: #                            colon-separated list of (in order) description,
                   4474: #                            institutional code, and course owner.
1.404     raeburn  4475: #                 selfenrollonly - filter by courses allowing self-enrollment  
                   4476: #                                  now or in the future (selfenrollonly = 1).
                   4477: #                 catfilter - filter by course category, assigned to a course 
                   4478: #                             using manually defined categories (i.e., not
1.407     raeburn  4479: #                             self-cataloging based on on institutional code).   
1.404     raeburn  4480: #                 showhidden - include course in results even if course  
1.407     raeburn  4481: #                              was set to be excluded from course catalog (DC only).
1.404     raeburn  4482: #                 caller -  if set to 'coursecatalog', courses set to be hidden
                   4483: #                           from course catalog will be excluded from results (unless
                   4484: #                           overridden by "showhidden".
1.427     raeburn  4485: #                 cloner - escaped username:domain of course cloner (if picking course to
1.419     raeburn  4486: #                          clone).
                   4487: #                 cc_clone_list - escaped comma separated list of courses for which 
                   4488: #                                 course cloner has active CC role (and so can clone
                   4489: #                                 automatically).
1.427     raeburn  4490: #                 cloneonly - filter by courses for which cloner has rights to clone.
                   4491: #                 createdbefore - include courses for which creation date preceeded this date.
                   4492: #                 createdafter - include courses for which creation date followed this date.
                   4493: #                 creationcontext - include courses created in specified context 
1.404     raeburn  4494: #
1.445     raeburn  4495: #                 domcloner - flag to indicate if user can create CCs in course's domain.
1.505     raeburn  4496: #                             If so, ability to clone course is automatic.
                   4497: #                 hasuniquecode - filter by courses for which a six character unique code has 
                   4498: #                                 been set.
1.445     raeburn  4499: #
1.234     foxr     4500: #     $client  - The socket open on the client.
                   4501: # Returns:
                   4502: #    1     - Continue processing.
                   4503: # Side Effects:
                   4504: #   a reply is written to $client.
                   4505: sub dump_course_id_handler {
                   4506:     my ($cmd, $tail, $client) = @_;
1.494     droeschl 4507: 
                   4508:     my $res = LONCAPA::Lond::dump_course_id_handler($tail);
                   4509:     if ($res =~ /^error:/) {
                   4510:         Failure($client, \$res, "$cmd:$tail");
                   4511:     } else {
                   4512:         Reply($client, \$res, "$cmd:$tail");
                   4513:     }
                   4514: 
                   4515:     return 1;  
                   4516: 
                   4517:     #TODO remove
1.234     foxr     4518:     my $userinput = "$cmd:$tail";
                   4519: 
1.333     raeburn  4520:     my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter,
1.404     raeburn  4521:         $typefilter,$regexp_ok,$rtn_as_hash,$selfenrollonly,$catfilter,$showhidden,
1.427     raeburn  4522:         $caller,$cloner,$cc_clone_list,$cloneonly,$createdbefore,$createdafter,
1.505     raeburn  4523:         $creationcontext,$domcloner,$hasuniquecode) =split(/:/,$tail);
1.397     raeburn  4524:     my $now = time;
1.419     raeburn  4525:     my ($cloneruname,$clonerudom,%cc_clone);
1.234     foxr     4526:     if (defined($description)) {
                   4527: 	$description=&unescape($description);
                   4528:     } else {
                   4529: 	$description='.';
                   4530:     }
1.266     raeburn  4531:     if (defined($instcodefilter)) {
                   4532:         $instcodefilter=&unescape($instcodefilter);
                   4533:     } else {
                   4534:         $instcodefilter='.';
                   4535:     }
1.336     raeburn  4536:     my ($ownerunamefilter,$ownerdomfilter);
1.266     raeburn  4537:     if (defined($ownerfilter)) {
                   4538:         $ownerfilter=&unescape($ownerfilter);
1.336     raeburn  4539:         if ($ownerfilter ne '.' && defined($ownerfilter)) {
                   4540:             if ($ownerfilter =~ /^([^:]*):([^:]*)$/) {
                   4541:                  $ownerunamefilter = $1;
                   4542:                  $ownerdomfilter = $2;
                   4543:             } else {
                   4544:                 $ownerunamefilter = $ownerfilter;
                   4545:                 $ownerdomfilter = '';
                   4546:             }
                   4547:         }
1.266     raeburn  4548:     } else {
                   4549:         $ownerfilter='.';
                   4550:     }
1.336     raeburn  4551: 
1.282     raeburn  4552:     if (defined($coursefilter)) {
                   4553:         $coursefilter=&unescape($coursefilter);
                   4554:     } else {
                   4555:         $coursefilter='.';
                   4556:     }
1.333     raeburn  4557:     if (defined($typefilter)) {
                   4558:         $typefilter=&unescape($typefilter);
                   4559:     } else {
                   4560:         $typefilter='.';
                   4561:     }
1.344     raeburn  4562:     if (defined($regexp_ok)) {
                   4563:         $regexp_ok=&unescape($regexp_ok);
                   4564:     }
1.401     raeburn  4565:     if (defined($catfilter)) {
                   4566:         $catfilter=&unescape($catfilter);
                   4567:     }
1.419     raeburn  4568:     if (defined($cloner)) {
                   4569:         $cloner = &unescape($cloner);
                   4570:         ($cloneruname,$clonerudom) = ($cloner =~ /^($LONCAPA::match_username):($LONCAPA::match_domain)$/); 
                   4571:     }
                   4572:     if (defined($cc_clone_list)) {
                   4573:         $cc_clone_list = &unescape($cc_clone_list);
                   4574:         my @cc_cloners = split('&',$cc_clone_list);
                   4575:         foreach my $cid (@cc_cloners) {
                   4576:             my ($clonedom,$clonenum) = split(':',$cid);
                   4577:             next if ($clonedom ne $udom); 
                   4578:             $cc_clone{$clonedom.'_'.$clonenum} = 1;
                   4579:         } 
                   4580:     }
1.431     raeburn  4581:     if ($createdbefore ne '') {
1.427     raeburn  4582:         $createdbefore = &unescape($createdbefore);
                   4583:     } else {
                   4584:        $createdbefore = 0;
                   4585:     }
1.431     raeburn  4586:     if ($createdafter ne '') {
1.427     raeburn  4587:         $createdafter = &unescape($createdafter);
                   4588:     } else {
                   4589:         $createdafter = 0;
                   4590:     }
1.431     raeburn  4591:     if ($creationcontext ne '') {
1.427     raeburn  4592:         $creationcontext = &unescape($creationcontext);
                   4593:     } else {
                   4594:         $creationcontext = '.';
                   4595:     }
1.505     raeburn  4596:     unless ($hasuniquecode) {
                   4597:         $hasuniquecode = '.';
                   4598:     }
1.384     raeburn  4599:     my $unpack = 1;
1.485     raeburn  4600:     if ($description eq '.' && $instcodefilter eq '.' && $ownerfilter eq '.' && 
1.384     raeburn  4601:         $typefilter eq '.') {
                   4602:         $unpack = 0;
                   4603:     }
                   4604:     if (!defined($since)) { $since=0; }
1.234     foxr     4605:     my $qresult='';
                   4606:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   4607:     if ($hashref) {
1.384     raeburn  4608: 	while (my ($key,$value) = each(%$hashref)) {
1.397     raeburn  4609:             my ($unesc_key,$lasttime_key,$lasttime,$is_hash,%val,
1.427     raeburn  4610:                 %unesc_val,$selfenroll_end,$selfenroll_types,$created,
                   4611:                 $context);
1.384     raeburn  4612:             $unesc_key = &unescape($key);
                   4613:             if ($unesc_key =~ /^lasttime:/) {
                   4614:                 next;
                   4615:             } else {
                   4616:                 $lasttime_key = &escape('lasttime:'.$unesc_key);
                   4617:             }
                   4618:             if ($hashref->{$lasttime_key} ne '') {
                   4619:                 $lasttime = $hashref->{$lasttime_key};
                   4620:                 next if ($lasttime<$since);
                   4621:             }
1.419     raeburn  4622:             my ($canclone,$valchange);
1.384     raeburn  4623:             my $items = &Apache::lonnet::thaw_unescape($value);
                   4624:             if (ref($items) eq 'HASH') {
1.429     raeburn  4625:                 if ($hashref->{$lasttime_key} eq '') {
1.430     raeburn  4626:                     next if ($since > 1);
1.429     raeburn  4627:                 }
1.384     raeburn  4628:                 $is_hash =  1;
1.445     raeburn  4629:                 if ($domcloner) {
                   4630:                     $canclone = 1;
                   4631:                 } elsif (defined($clonerudom)) {
1.419     raeburn  4632:                     if ($items->{'cloners'}) {
                   4633:                         my @cloneable = split(',',$items->{'cloners'});
                   4634:                         if (@cloneable) {
                   4635:                             if (grep(/^\*$/,@cloneable))  {
                   4636:                                 $canclone = 1;
                   4637:                             } elsif (grep(/^\*:\Q$clonerudom\E$/,@cloneable)) {
                   4638:                                 $canclone = 1;
                   4639:                             } elsif (grep(/^\Q$cloneruname\E:\Q$clonerudom\E$/,@cloneable)) {
                   4640:                                 $canclone = 1;
                   4641:                             }
                   4642:                         }
                   4643:                         unless ($canclone) {
                   4644:                             if ($cloneruname ne '' && $clonerudom ne '') {
                   4645:                                 if ($cc_clone{$unesc_key}) {
                   4646:                                     $canclone = 1;
                   4647:                                     $items->{'cloners'} .= ','.$cloneruname.':'.
                   4648:                                                            $clonerudom;
                   4649:                                     $valchange = 1;
                   4650:                                 }
                   4651:                             }
                   4652:                         }
                   4653:                     } elsif (defined($cloneruname)) {
                   4654:                         if ($cc_clone{$unesc_key}) {
                   4655:                             $canclone = 1;
                   4656:                             $items->{'cloners'} = $cloneruname.':'.$clonerudom;
                   4657:                             $valchange = 1;
                   4658:                         }
1.437     raeburn  4659:                         unless ($canclone) {
                   4660:                             if ($items->{'owner'} =~ /:/) {
                   4661:                                 if ($items->{'owner'} eq $cloner) {
                   4662:                                     $canclone = 1;
                   4663:                                 }
1.444     raeburn  4664:                             } elsif ($cloner eq $items->{'owner'}.':'.$udom) {
1.437     raeburn  4665:                                 $canclone = 1;
                   4666:                             }
                   4667:                             if ($canclone) {
                   4668:                                 $items->{'cloners'} = $cloneruname.':'.$clonerudom;
                   4669:                                 $valchange = 1;
                   4670:                             }
                   4671:                         }
1.419     raeburn  4672:                     }
                   4673:                 }
1.384     raeburn  4674:                 if ($unpack || !$rtn_as_hash) {
                   4675:                     $unesc_val{'descr'} = $items->{'description'};
                   4676:                     $unesc_val{'inst_code'} = $items->{'inst_code'};
                   4677:                     $unesc_val{'owner'} = $items->{'owner'};
                   4678:                     $unesc_val{'type'} = $items->{'type'};
1.419     raeburn  4679:                     $unesc_val{'cloners'} = $items->{'cloners'};
1.427     raeburn  4680:                     $unesc_val{'created'} = $items->{'created'};
                   4681:                     $unesc_val{'context'} = $items->{'context'};
1.404     raeburn  4682:                 }
                   4683:                 $selfenroll_types = $items->{'selfenroll_types'};
                   4684:                 $selfenroll_end = $items->{'selfenroll_end_date'};
1.427     raeburn  4685:                 $created = $items->{'created'};
                   4686:                 $context = $items->{'context'};
1.505     raeburn  4687:                 if ($hasuniquecode ne '.') {
                   4688:                     next unless ($items->{'uniquecode'});
                   4689:                 }
1.404     raeburn  4690:                 if ($selfenrollonly) {
                   4691:                     next if (!$selfenroll_types);
                   4692:                     if (($selfenroll_end > 0) && ($selfenroll_end <= $now)) {
                   4693:                         next;
1.397     raeburn  4694:                     }
1.404     raeburn  4695:                 }
1.427     raeburn  4696:                 if ($creationcontext ne '.') {
                   4697:                     next if (($context ne '') && ($context ne $creationcontext));  
                   4698:                 }
                   4699:                 if ($createdbefore > 0) {
                   4700:                     next if (($created eq '') || ($created > $createdbefore));   
                   4701:                 }
                   4702:                 if ($createdafter > 0) {
                   4703:                     next if (($created eq '') || ($created <= $createdafter)); 
                   4704:                 }
1.404     raeburn  4705:                 if ($catfilter ne '') {
1.406     raeburn  4706:                     next if ($items->{'categories'} eq '');
                   4707:                     my @categories = split('&',$items->{'categories'}); 
1.407     raeburn  4708:                     next if (@categories == 0);
                   4709:                     my @subcats = split('&',$catfilter);
                   4710:                     my $matchcat = 0;
                   4711:                     foreach my $cat (@categories) {
                   4712:                         if (grep(/^\Q$cat\E$/,@subcats)) {
                   4713:                             $matchcat = 1;
                   4714:                             last;
                   4715:                         }
                   4716:                     }
                   4717:                     next if (!$matchcat);
1.404     raeburn  4718:                 }
                   4719:                 if ($caller eq 'coursecatalog') {
1.405     raeburn  4720:                     if ($items->{'hidefromcat'} eq 'yes') {
                   4721:                         next if !$showhidden;
1.401     raeburn  4722:                     }
1.384     raeburn  4723:                 }
1.383     raeburn  4724:             } else {
1.401     raeburn  4725:                 next if ($catfilter ne '');
1.419     raeburn  4726:                 next if ($selfenrollonly);
1.427     raeburn  4727:                 next if ($createdbefore || $createdafter);
                   4728:                 next if ($creationcontext ne '.');
1.419     raeburn  4729:                 if ((defined($clonerudom)) && (defined($cloneruname)))  {
                   4730:                     if ($cc_clone{$unesc_key}) {
                   4731:                         $canclone = 1;
                   4732:                         $val{'cloners'} = &escape($cloneruname.':'.$clonerudom);
                   4733:                     }
                   4734:                 }
1.384     raeburn  4735:                 $is_hash =  0;
1.388     raeburn  4736:                 my @courseitems = split(/:/,$value);
1.403     raeburn  4737:                 $lasttime = pop(@courseitems);
1.402     raeburn  4738:                 if ($hashref->{$lasttime_key} eq '') {
                   4739:                     next if ($lasttime<$since);
                   4740:                 }
1.384     raeburn  4741: 	        ($val{'descr'},$val{'inst_code'},$val{'owner'},$val{'type'}) = @courseitems;
1.383     raeburn  4742:             }
1.419     raeburn  4743:             if ($cloneonly) {
                   4744:                next unless ($canclone);
                   4745:             }
1.266     raeburn  4746:             my $match = 1;
1.384     raeburn  4747: 	    if ($description ne '.') {
                   4748:                 if (!$is_hash) {
                   4749:                     $unesc_val{'descr'} = &unescape($val{'descr'});
                   4750:                 }
                   4751:                 if (eval{$unesc_val{'descr'} !~ /\Q$description\E/i}) {
1.266     raeburn  4752:                     $match = 0;
1.384     raeburn  4753:                 }
1.266     raeburn  4754:             }
1.384     raeburn  4755:             if ($instcodefilter ne '.') {
                   4756:                 if (!$is_hash) {
                   4757:                     $unesc_val{'inst_code'} = &unescape($val{'inst_code'});
                   4758:                 }
1.418     raeburn  4759:                 if ($regexp_ok == 1) {
1.384     raeburn  4760:                     if (eval{$unesc_val{'inst_code'} !~ /$instcodefilter/}) {
1.344     raeburn  4761:                         $match = 0;
                   4762:                     }
1.418     raeburn  4763:                 } elsif ($regexp_ok == -1) {
                   4764:                     if (eval{$unesc_val{'inst_code'} =~ /$instcodefilter/}) {
                   4765:                         $match = 0;
                   4766:                     }
1.344     raeburn  4767:                 } else {
1.384     raeburn  4768:                     if (eval{$unesc_val{'inst_code'} !~ /\Q$instcodefilter\E/i}) {
1.344     raeburn  4769:                         $match = 0;
                   4770:                     }
1.266     raeburn  4771:                 }
1.234     foxr     4772: 	    }
1.384     raeburn  4773:             if ($ownerfilter ne '.') {
                   4774:                 if (!$is_hash) {
                   4775:                     $unesc_val{'owner'} = &unescape($val{'owner'});
                   4776:                 }
1.336     raeburn  4777:                 if (($ownerunamefilter ne '') && ($ownerdomfilter ne '')) {
1.384     raeburn  4778:                     if ($unesc_val{'owner'} =~ /:/) {
                   4779:                         if (eval{$unesc_val{'owner'} !~ 
                   4780:                              /\Q$ownerunamefilter\E:\Q$ownerdomfilter\E$/i}) {
1.336     raeburn  4781:                             $match = 0;
                   4782:                         } 
                   4783:                     } else {
1.384     raeburn  4784:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336     raeburn  4785:                             $match = 0;
                   4786:                         }
                   4787:                     }
                   4788:                 } elsif ($ownerunamefilter ne '') {
1.384     raeburn  4789:                     if ($unesc_val{'owner'} =~ /:/) {
                   4790:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E:[^:]+$/i}) {
1.336     raeburn  4791:                              $match = 0;
                   4792:                         }
                   4793:                     } else {
1.384     raeburn  4794:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336     raeburn  4795:                             $match = 0;
                   4796:                         }
                   4797:                     }
                   4798:                 } elsif ($ownerdomfilter ne '') {
1.384     raeburn  4799:                     if ($unesc_val{'owner'} =~ /:/) {
                   4800:                         if (eval{$unesc_val{'owner'} !~ /^[^:]+:\Q$ownerdomfilter\E/}) {
1.336     raeburn  4801:                              $match = 0;
                   4802:                         }
                   4803:                     } else {
                   4804:                         if ($ownerdomfilter ne $udom) {
                   4805:                             $match = 0;
                   4806:                         }
                   4807:                     }
1.266     raeburn  4808:                 }
                   4809:             }
1.384     raeburn  4810:             if ($coursefilter ne '.') {
                   4811:                 if (eval{$unesc_key !~ /^$udom(_)\Q$coursefilter\E$/}) {
1.282     raeburn  4812:                     $match = 0;
                   4813:                 }
                   4814:             }
1.384     raeburn  4815:             if ($typefilter ne '.') {
                   4816:                 if (!$is_hash) {
                   4817:                     $unesc_val{'type'} = &unescape($val{'type'});
                   4818:                 }
                   4819:                 if ($unesc_val{'type'} eq '') {
1.333     raeburn  4820:                     if ($typefilter ne 'Course') {
                   4821:                         $match = 0;
                   4822:                     }
1.383     raeburn  4823:                 } else {
1.384     raeburn  4824:                     if (eval{$unesc_val{'type'} !~ /^\Q$typefilter\E$/}) {
1.333     raeburn  4825:                         $match = 0;
                   4826:                     }
                   4827:                 }
                   4828:             }
1.266     raeburn  4829:             if ($match == 1) {
1.384     raeburn  4830:                 if ($rtn_as_hash) {
                   4831:                     if ($is_hash) {
1.419     raeburn  4832:                         if ($valchange) {
                   4833:                             my $newvalue = &Apache::lonnet::freeze_escape($items);
                   4834:                             $qresult.=$key.'='.$newvalue.'&';
                   4835:                         } else {
                   4836:                             $qresult.=$key.'='.$value.'&';
                   4837:                         }
1.384     raeburn  4838:                     } else {
1.388     raeburn  4839:                         my %rtnhash = ( 'description' => &unescape($val{'descr'}),
                   4840:                                         'inst_code' => &unescape($val{'inst_code'}),
                   4841:                                         'owner'     => &unescape($val{'owner'}),
                   4842:                                         'type'      => &unescape($val{'type'}),
1.419     raeburn  4843:                                         'cloners'   => &unescape($val{'cloners'}),
1.384     raeburn  4844:                                       );
                   4845:                         my $items = &Apache::lonnet::freeze_escape(\%rtnhash);
                   4846:                         $qresult.=$key.'='.$items.'&';
                   4847:                     }
1.383     raeburn  4848:                 } else {
1.384     raeburn  4849:                     if ($is_hash) {
                   4850:                         $qresult .= $key.'='.&escape($unesc_val{'descr'}).':'.
                   4851:                                     &escape($unesc_val{'inst_code'}).':'.
                   4852:                                     &escape($unesc_val{'owner'}).'&';
                   4853:                     } else {
                   4854:                         $qresult .= $key.'='.$val{'descr'}.':'.$val{'inst_code'}.
                   4855:                                     ':'.$val{'owner'}.'&';
                   4856:                     }
1.383     raeburn  4857:                 }
1.266     raeburn  4858:             }
1.234     foxr     4859: 	}
1.311     albertel 4860: 	if (&untie_domain_hash($hashref)) {
1.234     foxr     4861: 	    chop($qresult);
1.387     albertel 4862: 	    &Reply($client, \$qresult, $userinput);
1.234     foxr     4863: 	} else {
                   4864: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4865: 		    "while attempting courseiddump\n", $userinput);
                   4866: 	}
                   4867:     } else {
                   4868: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4869: 		"while attempting courseiddump\n", $userinput);
                   4870:     }
                   4871:     return 1;
                   4872: }
                   4873: &register_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
1.238     foxr     4874: 
1.438     raeburn  4875: sub course_lastaccess_handler {
                   4876:     my ($cmd, $tail, $client) = @_;
                   4877:     my $userinput = "$cmd:$tail";
                   4878:     my ($cdom,$cnum) = split(':',$tail); 
                   4879:     my (%lastaccess,$qresult);
                   4880:     my $hashref = &tie_domain_hash($cdom, "nohist_courseids", &GDBM_WRCREAT());
                   4881:     if ($hashref) {
                   4882:         while (my ($key,$value) = each(%$hashref)) {
                   4883:             my ($unesc_key,$lasttime);
                   4884:             $unesc_key = &unescape($key);
                   4885:             if ($cnum) {
                   4886:                 next unless ($unesc_key =~ /\Q$cdom\E_\Q$cnum\E$/);
                   4887:             }
                   4888:             if ($unesc_key =~ /^lasttime:($LONCAPA::match_domain\_$LONCAPA::match_courseid)/) {
                   4889:                 $lastaccess{$1} = $value;
                   4890:             } else {
                   4891:                 my $items = &Apache::lonnet::thaw_unescape($value);
                   4892:                 if (ref($items) eq 'HASH') {
                   4893:                     unless ($lastaccess{$unesc_key}) {
                   4894:                         $lastaccess{$unesc_key} = '';
                   4895:                     }
                   4896:                 } else {
                   4897:                     my @courseitems = split(':',$value);
                   4898:                     $lastaccess{$unesc_key} = pop(@courseitems);
                   4899:                 }
                   4900:             }
                   4901:         }
                   4902:         foreach my $cid (sort(keys(%lastaccess))) {
                   4903:             $qresult.=&escape($cid).'='.$lastaccess{$cid}.'&'; 
                   4904:         }
                   4905:         if (&untie_domain_hash($hashref)) {
                   4906:             if ($qresult) {
                   4907:                 chop($qresult);
                   4908:             }
                   4909:             &Reply($client, \$qresult, $userinput);
                   4910:         } else {
                   4911:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4912:                     "while attempting lastacourseaccess\n", $userinput);
                   4913:         }
                   4914:     } else {
                   4915:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4916:                 "while attempting lastcourseaccess\n", $userinput);
                   4917:     }
                   4918:     return 1;
                   4919: }
                   4920: &register_handler("courselastaccess",\&course_lastaccess_handler, 0, 1, 0);
                   4921: 
1.561     raeburn  4922: sub course_sessions_handler {
                   4923:     my ($cmd, $tail, $client) = @_;
                   4924:     my $userinput = "$cmd:$tail";
                   4925:     my ($cdom,$cnum,$lastactivity) = split(':',$tail);
                   4926:     my $dbsuffix = '_'.$cdom.'_'.$cnum.'.db';
                   4927:     my (%sessions,$qresult);
                   4928:     my $now=time;
                   4929:     if (opendir(DIR,$perlvar{'lonIDsDir'})) {
                   4930:         my $filename;
                   4931:         while ($filename=readdir(DIR)) {
                   4932:             next if ($filename=~/^\./);
                   4933:             next if ($filename=~/^publicuser_/);
                   4934:             next if ($filename=~/^[a-f0-9]+_(linked|lti_\d+)\.id$/);
1.562     raeburn  4935:             if ($filename =~ /^($LONCAPA::match_username)_\d+_($LONCAPA::match_domain)_/) {
1.561     raeburn  4936:                 my ($uname,$udom) = ($1,$2);
1.562     raeburn  4937:                 next unless (-e "$perlvar{'lonDaemons'}/tmp/$uname$dbsuffix");
1.561     raeburn  4938:                 my $mtime = (stat("$perlvar{'lonIDsDir'}/$filename"))[9];
                   4939:                 if ($lastactivity < 0) {
1.563     raeburn  4940:                     next if ($mtime-$now > $lastactivity);
1.561     raeburn  4941:                 } else {
1.563     raeburn  4942:                     next if ($now-$mtime > $lastactivity);
1.561     raeburn  4943:                 }
                   4944:                 $sessions{$uname.':'.$udom} = $mtime;
                   4945:             }
                   4946:         }
                   4947:         closedir(DIR); 
                   4948:     }
                   4949:     foreach my $user (keys(%sessions)) {
                   4950:         $qresult.=&escape($user).'='.$sessions{$user}.'&';
                   4951:     }
                   4952:     if ($qresult) {
                   4953:         chop($qresult);
                   4954:     }
                   4955:     &Reply($client, \$qresult, $userinput);
                   4956:     return 1;
                   4957: }
                   4958: &register_handler("coursesessions",\&course_sessions_handler, 0, 1, 0);
                   4959: 
1.238     foxr     4960: #
1.348     raeburn  4961: # Puts an unencrypted entry in a namespace db file at the domain level 
                   4962: #
                   4963: # Parameters:
                   4964: #    $cmd      - The command that got us here.
                   4965: #    $tail     - Tail of the command (remaining parameters).
                   4966: #    $client   - File descriptor connected to client.
                   4967: # Returns
                   4968: #     0        - Requested to exit, caller should shut down.
                   4969: #     1        - Continue processing.
                   4970: #  Side effects:
                   4971: #     reply is written to $client.
                   4972: #
                   4973: sub put_domain_handler {
                   4974:     my ($cmd,$tail,$client) = @_;
                   4975: 
                   4976:     my $userinput = "$cmd:$tail";
                   4977: 
                   4978:     my ($udom,$namespace,$what) =split(/:/,$tail,3);
                   4979:     chomp($what);
                   4980:     my @pairs=split(/\&/,$what);
                   4981:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_WRCREAT(),
                   4982:                                    "P", $what);
                   4983:     if ($hashref) {
                   4984:         foreach my $pair (@pairs) {
                   4985:             my ($key,$value)=split(/=/,$pair);
                   4986:             $hashref->{$key}=$value;
                   4987:         }
                   4988:         if (&untie_domain_hash($hashref)) {
                   4989:             &Reply($client, "ok\n", $userinput);
                   4990:         } else {
                   4991:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4992:                      "while attempting putdom\n", $userinput);
                   4993:         }
                   4994:     } else {
                   4995:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4996:                   "while attempting putdom\n", $userinput);
                   4997:     }
                   4998: 
                   4999:     return 1;
                   5000: }
                   5001: &register_handler("putdom", \&put_domain_handler, 0, 1, 0);
                   5002: 
1.517     raeburn  5003: # Updates one or more entries in clickers.db file at the domain level
                   5004: #
                   5005: # Parameters:
                   5006: #    $cmd      - The command that got us here.
                   5007: #    $tail     - Tail of the command (remaining parameters).
                   5008: #                In this case a colon separated list containing:
                   5009: #                (a) the domain for which we are updating the entries,
                   5010: #                (b) the action required -- add or del -- and
                   5011: #                (c) a &-separated list of entries to add or delete.
                   5012: #    $client   - File descriptor connected to client.
                   5013: # Returns
                   5014: #     1        - Continue processing.
                   5015: #     0        - Requested to exit, caller should shut down.
                   5016: #  Side effects:
                   5017: #     reply is written to $client.
                   5018: #
                   5019: 
                   5020: 
                   5021: sub update_clickers {
                   5022:     my ($cmd, $tail, $client)  = @_;
                   5023: 
                   5024:     my $userinput = "$cmd:$tail";
                   5025:     my ($udom,$action,$what) =split(/:/,$tail,3);
                   5026:     chomp($what);
                   5027: 
                   5028:     my $hashref = &tie_domain_hash($udom, "clickers", &GDBM_WRCREAT(),
                   5029:                                  "U","$action:$what");
                   5030: 
                   5031:     if (!$hashref) {
                   5032:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5033:                   "while attempting updateclickers\n", $userinput);
                   5034:         return 1;
                   5035:     }
                   5036: 
                   5037:     my @pairs=split(/\&/,$what);
                   5038:     foreach my $pair (@pairs) {
                   5039:         my ($key,$value)=split(/=/,$pair);
                   5040:         if ($action eq 'add') {
                   5041:             if (exists($hashref->{$key})) {
                   5042:                 my @newvals = split(/,/,&unescape($value));
                   5043:                 my @currvals = split(/,/,&unescape($hashref->{$key}));
                   5044:                 my @merged = sort(keys(%{{map { $_ => 1 } (@newvals,@currvals)}}));
                   5045:                 $hashref->{$key}=&escape(join(',',@merged));
                   5046:             } else {
                   5047:                 $hashref->{$key}=$value;
                   5048:             }
                   5049:         } elsif ($action eq 'del') {
                   5050:             if (exists($hashref->{$key})) {
                   5051:                 my %current;
                   5052:                 map { $current{$_} = 1; } split(/,/,&unescape($hashref->{$key}));
                   5053:                 map { delete($current{$_}); } split(/,/,&unescape($value));
                   5054:                 if (keys(%current)) {
                   5055:                     $hashref->{$key}=&escape(join(',',sort(keys(%current))));
                   5056:                 } else {
                   5057:                     delete($hashref->{$key});
                   5058:                 }
                   5059:             }
                   5060:         }
                   5061:     }
                   5062:     if (&untie_user_hash($hashref)) {
                   5063:         &Reply( $client, "ok\n", $userinput);
                   5064:     } else {
                   5065:         &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   5066:                  "while attempting put\n",
                   5067:                  $userinput);
                   5068:     }
                   5069:     return 1;
                   5070: }
                   5071: &register_handler("updateclickers", \&update_clickers, 0, 1, 0);
                   5072: 
                   5073: 
                   5074: # Deletes one or more entries in a namespace db file at the domain level
                   5075: #
                   5076: # Parameters:
                   5077: #    $cmd      - The command that got us here.
                   5078: #    $tail     - Tail of the command (remaining parameters).
                   5079: #                In this case a colon separated list containing:
                   5080: #                (a) the domain for which we are deleting the entries,
                   5081: #                (b) &-separated list of keys to delete.  
                   5082: #    $client   - File descriptor connected to client.
                   5083: # Returns
                   5084: #     1        - Continue processing.
                   5085: #     0        - Requested to exit, caller should shut down.
                   5086: #  Side effects:
                   5087: #     reply is written to $client.
                   5088: #
                   5089: 
                   5090: sub del_domain_handler {
                   5091:     my ($cmd,$tail,$client) = @_;
                   5092: 
                   5093:     my $userinput = "$cmd:$tail";
                   5094: 
                   5095:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   5096:     chomp($what);
                   5097:     my $hashref = &tie_domain_hash($udom,$namespace,&GDBM_WRCREAT(),
                   5098:                                    "D", $what);
                   5099:     if ($hashref) {
                   5100:         my @keys=split(/\&/,$what);
                   5101:         foreach my $key (@keys) {
                   5102:             delete($hashref->{$key});
                   5103:         }
                   5104:         if (&untie_user_hash($hashref)) {
                   5105:             &Reply($client, "ok\n", $userinput);
                   5106:         } else {
                   5107:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5108:                     "while attempting deldom\n", $userinput);
                   5109:         }
                   5110:     } else {
                   5111:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5112:                  "while attempting deldom\n", $userinput);
                   5113:     }
                   5114:     return 1;
                   5115: }
                   5116: &register_handler("deldom", \&del_domain_handler, 0, 1, 0);
                   5117: 
                   5118: 
1.348     raeburn  5119: # Unencrypted get from the namespace database file at the domain level.
                   5120: # This function retrieves a keyed item from a specific named database in the
                   5121: # domain directory.
                   5122: #
                   5123: # Parameters:
1.565     raeburn  5124: #   $cmd             - Command request keyword (getdom).
1.348     raeburn  5125: #   $tail            - Tail of the command.  This is a colon separated list
                   5126: #                      consisting of the domain and the 'namespace' 
                   5127: #                      which selects the gdbm file to do the lookup in,
                   5128: #                      & separated list of keys to lookup.  Note that
                   5129: #                      the values are returned as an & separated list too.
                   5130: #   $client          - File descriptor open on the client.
                   5131: # Returns:
                   5132: #   1       - Continue processing.
                   5133: #   0       - Exit.
                   5134: #  Side effects:
                   5135: #     reply is written to $client.
                   5136: #
                   5137: 
                   5138: sub get_domain_handler {
                   5139:     my ($cmd, $tail, $client) = @_;
                   5140: 
1.536     raeburn  5141:     my $userinput = "$cmd:$tail";
                   5142: 
                   5143:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   5144:     if ($namespace =~ /^enc/) {
                   5145:         &Failure( $client, "refused\n", $userinput);
                   5146:     } else {
1.565     raeburn  5147:         my $res = LONCAPA::Lond::get_dom($userinput);
                   5148:         if ($res =~ /^error:/) {
                   5149:             &Failure($client, \$res, $userinput);
1.536     raeburn  5150:         } else {
1.565     raeburn  5151:             &Reply($client, \$res, $userinput);
1.536     raeburn  5152:         }
                   5153:     }
                   5154: 
                   5155:     return 1;
                   5156: }
                   5157: &register_handler("getdom", \&get_domain_handler, 0, 1, 0);
                   5158: 
                   5159: sub encrypted_get_domain_handler {
                   5160:     my ($cmd, $tail, $client) = @_;
                   5161: 
                   5162:     my $userinput = "$cmd:$tail";
1.348     raeburn  5163: 
1.565     raeburn  5164:     my $res = LONCAPA::Lond::get_dom($userinput);
                   5165:     if ($res =~ /^error:/) {
                   5166:         &Failure($client, \$res, $userinput);
                   5167:     } else {
                   5168:         if ($cipher) {
                   5169:             my $cmdlength=length($res);
                   5170:             $res.="         ";
                   5171:             my $encres='';
                   5172:             for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   5173:                 $encres.= unpack("H16",
                   5174:                                  $cipher->encrypt(substr($res,
                   5175:                                                          $encidx,
                   5176:                                                          8)));
1.536     raeburn  5177:             }
1.565     raeburn  5178:             &Reply( $client,"enc:$cmdlength:$encres\n",$userinput);
1.348     raeburn  5179:         } else {
1.565     raeburn  5180:             &Failure( $client, "error:no_key\n",$userinput);
1.348     raeburn  5181:         }
                   5182:     }
                   5183:     return 1;
                   5184: }
1.536     raeburn  5185: &register_handler("egetdom", \&encrypted_get_domain_handler, 1, 1, 0);
1.348     raeburn  5186: 
1.420     raeburn  5187: #
1.238     foxr     5188: #  Puts an id to a domains id database. 
                   5189: #
                   5190: #  Parameters:
                   5191: #   $cmd     - The command that triggered us.
                   5192: #   $tail    - Remainder of the request other than the command. This is a 
                   5193: #              colon separated list containing:
                   5194: #              $domain  - The domain for which we are writing the id.
                   5195: #              $pairs  - The id info to write... this is and & separated list
                   5196: #                        of keyword=value.
                   5197: #   $client  - Socket open on the client.
                   5198: #  Returns:
                   5199: #    1   - Continue processing.
                   5200: #  Side effects:
                   5201: #     reply is written to $client.
                   5202: #
                   5203: sub put_id_handler {
                   5204:     my ($cmd,$tail,$client) = @_;
                   5205: 
                   5206: 
                   5207:     my $userinput = "$cmd:$tail";
                   5208: 
                   5209:     my ($udom,$what)=split(/:/,$tail);
                   5210:     chomp($what);
                   5211:     my @pairs=split(/\&/,$what);
                   5212:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   5213: 				   "P", $what);
                   5214:     if ($hashref) {
                   5215: 	foreach my $pair (@pairs) {
                   5216: 	    my ($key,$value)=split(/=/,$pair);
                   5217: 	    $hashref->{$key}=$value;
                   5218: 	}
1.311     albertel 5219: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     5220: 	    &Reply($client, "ok\n", $userinput);
                   5221: 	} else {
                   5222: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5223: 		     "while attempting idput\n", $userinput);
                   5224: 	}
                   5225:     } else {
                   5226: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5227: 		  "while attempting idput\n", $userinput);
                   5228:     }
                   5229: 
                   5230:     return 1;
                   5231: }
1.263     albertel 5232: &register_handler("idput", \&put_id_handler, 0, 1, 0);
1.238     foxr     5233: 
                   5234: #
                   5235: #  Retrieves a set of id values from the id database.
                   5236: #  Returns an & separated list of results, one for each requested id to the
                   5237: #  client.
                   5238: #
                   5239: # Parameters:
                   5240: #   $cmd       - Command keyword that caused us to be dispatched.
                   5241: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5242: #               domain - the domain whose id table we dump
                   5243: #               ids      Consists of an & separated list of
                   5244: #                        id keywords whose values will be fetched.
                   5245: #                        nonexisting keywords will have an empty value.
                   5246: #   $client    - Socket open on the client.
                   5247: #
                   5248: # Returns:
                   5249: #    1 - indicating processing should continue.
                   5250: # Side effects:
                   5251: #   An & separated list of results is written to $client.
                   5252: #
                   5253: sub get_id_handler {
                   5254:     my ($cmd, $tail, $client) = @_;
                   5255: 
                   5256:     
                   5257:     my $userinput = "$client:$tail";
                   5258:     
                   5259:     my ($udom,$what)=split(/:/,$tail);
                   5260:     chomp($what);
                   5261:     my @queries=split(/\&/,$what);
                   5262:     my $qresult='';
                   5263:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
                   5264:     if ($hashref) {
                   5265: 	for (my $i=0;$i<=$#queries;$i++) {
                   5266: 	    $qresult.="$hashref->{$queries[$i]}&";
                   5267: 	}
1.311     albertel 5268: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     5269: 	    $qresult=~s/\&$//;
1.387     albertel 5270: 	    &Reply($client, \$qresult, $userinput);
1.238     foxr     5271: 	} else {
                   5272: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5273: 		      "while attempting idget\n",$userinput);
                   5274: 	}
                   5275:     } else {
                   5276: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5277: 		 "while attempting idget\n",$userinput);
                   5278:     }
                   5279:     
                   5280:     return 1;
                   5281: }
1.263     albertel 5282: &register_handler("idget", \&get_id_handler, 0, 1, 0);
1.238     foxr     5283: 
1.501     raeburn  5284: #   Deletes one or more ids in a domain's id database.
                   5285: #
                   5286: #   Parameters:
                   5287: #       $cmd                  - Command keyword (iddel).
                   5288: #       $tail                 - Command tail.  In this case a colon
                   5289: #                               separated list containing:
                   5290: #                               The domain for which we are deleting the id(s).
                   5291: #                               &-separated list of id(s) to delete.
                   5292: #       $client               - File open on client socket.
                   5293: # Returns:
                   5294: #     1   - Continue processing
                   5295: #     0   - Exit server.
                   5296: #     
                   5297: #
                   5298: 
                   5299: sub del_id_handler {
                   5300:     my ($cmd,$tail,$client) = @_;
                   5301: 
                   5302:     my $userinput = "$cmd:$tail";
                   5303: 
                   5304:     my ($udom,$what)=split(/:/,$tail);
                   5305:     chomp($what);
                   5306:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   5307:                                    "D", $what);
                   5308:     if ($hashref) {
                   5309:         my @keys=split(/\&/,$what);
                   5310:         foreach my $key (@keys) {
                   5311:             delete($hashref->{$key});
                   5312:         }
                   5313:         if (&untie_user_hash($hashref)) {
                   5314:             &Reply($client, "ok\n", $userinput);
                   5315:         } else {
                   5316:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5317:                     "while attempting iddel\n", $userinput);
                   5318:         }
                   5319:     } else {
                   5320:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5321:                  "while attempting iddel\n", $userinput);
                   5322:     }
                   5323:     return 1;
                   5324: }
                   5325: &register_handler("iddel", \&del_id_handler, 0, 1, 0);
                   5326: 
1.238     foxr     5327: #
1.299     raeburn  5328: # Puts broadcast e-mail sent by Domain Coordinator in nohist_dcmail database 
                   5329: #
                   5330: # Parameters
                   5331: #   $cmd       - Command keyword that caused us to be dispatched.
                   5332: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5333: #               domain - the domain whose dcmail we are recording
                   5334: #               email    Consists of key=value pair 
                   5335: #                        where key is unique msgid
                   5336: #                        and value is message (in XML)
                   5337: #   $client    - Socket open on the client.
                   5338: #
                   5339: # Returns:
                   5340: #    1 - indicating processing should continue.
                   5341: # Side effects
                   5342: #     reply is written to $client.
                   5343: #
                   5344: sub put_dcmail_handler {
                   5345:     my ($cmd,$tail,$client) = @_;
                   5346:     my $userinput = "$cmd:$tail";
1.463     foxr     5347: 
                   5348: 
1.299     raeburn  5349:     my ($udom,$what)=split(/:/,$tail);
                   5350:     chomp($what);
                   5351:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   5352:     if ($hashref) {
                   5353:         my ($key,$value)=split(/=/,$what);
                   5354:         $hashref->{$key}=$value;
                   5355:     }
1.311     albertel 5356:     if (&untie_domain_hash($hashref)) {
1.299     raeburn  5357:         &Reply($client, "ok\n", $userinput);
                   5358:     } else {
                   5359:         &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5360:                  "while attempting dcmailput\n", $userinput);
                   5361:     }
                   5362:     return 1;
                   5363: }
                   5364: &register_handler("dcmailput", \&put_dcmail_handler, 0, 1, 0);
                   5365: 
                   5366: #
                   5367: # Retrieves broadcast e-mail from nohist_dcmail database
                   5368: # Returns to client an & separated list of key=value pairs,
                   5369: # where key is msgid and value is message information.
                   5370: #
                   5371: # Parameters
                   5372: #   $cmd       - Command keyword that caused us to be dispatched.
                   5373: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5374: #               domain - the domain whose dcmail table we dump
                   5375: #               startfilter - beginning of time window 
                   5376: #               endfilter - end of time window
                   5377: #               sendersfilter - & separated list of username:domain 
                   5378: #                 for senders to search for.
                   5379: #   $client    - Socket open on the client.
                   5380: #
                   5381: # Returns:
                   5382: #    1 - indicating processing should continue.
                   5383: # Side effects
                   5384: #     reply (& separated list of msgid=messageinfo pairs) is 
                   5385: #     written to $client.
                   5386: #
                   5387: sub dump_dcmail_handler {
                   5388:     my ($cmd, $tail, $client) = @_;
                   5389:                                                                                 
                   5390:     my $userinput = "$cmd:$tail";
                   5391:     my ($udom,$startfilter,$endfilter,$sendersfilter) = split(/:/,$tail);
                   5392:     chomp($sendersfilter);
                   5393:     my @senders = ();
                   5394:     if (defined($startfilter)) {
                   5395:         $startfilter=&unescape($startfilter);
                   5396:     } else {
                   5397:         $startfilter='.';
                   5398:     }
                   5399:     if (defined($endfilter)) {
                   5400:         $endfilter=&unescape($endfilter);
                   5401:     } else {
                   5402:         $endfilter='.';
                   5403:     }
                   5404:     if (defined($sendersfilter)) {
                   5405:         $sendersfilter=&unescape($sendersfilter);
1.300     albertel 5406: 	@senders = map { &unescape($_) } split(/\&/,$sendersfilter);
1.299     raeburn  5407:     }
                   5408: 
                   5409:     my $qresult='';
                   5410:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   5411:     if ($hashref) {
                   5412:         while (my ($key,$value) = each(%$hashref)) {
                   5413:             my $match = 1;
1.303     albertel 5414:             my ($timestamp,$subj,$uname,$udom) = 
                   5415: 		split(/:/,&unescape(&unescape($key)),5); # yes, twice really
1.299     raeburn  5416:             $subj = &unescape($subj);
                   5417:             unless ($startfilter eq '.' || !defined($startfilter)) {
                   5418:                 if ($timestamp < $startfilter) {
                   5419:                     $match = 0;
                   5420:                 }
                   5421:             }
                   5422:             unless ($endfilter eq '.' || !defined($endfilter)) {
                   5423:                 if ($timestamp > $endfilter) {
                   5424:                     $match = 0;
                   5425:                 }
                   5426:             }
                   5427:             unless (@senders < 1) {
                   5428:                 unless (grep/^$uname:$udom$/,@senders) {
                   5429:                     $match = 0;
                   5430:                 }
                   5431:             }
                   5432:             if ($match == 1) {
                   5433:                 $qresult.=$key.'='.$value.'&';
                   5434:             }
                   5435:         }
1.311     albertel 5436:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5437:             chop($qresult);
1.387     albertel 5438:             &Reply($client, \$qresult, $userinput);
1.299     raeburn  5439:         } else {
                   5440:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5441:                     "while attempting dcmaildump\n", $userinput);
                   5442:         }
                   5443:     } else {
                   5444:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5445:                 "while attempting dcmaildump\n", $userinput);
                   5446:     }
                   5447:     return 1;
                   5448: }
                   5449: 
                   5450: &register_handler("dcmaildump", \&dump_dcmail_handler, 0, 1, 0);
                   5451: 
                   5452: #
                   5453: # Puts domain roles in nohist_domainroles database
                   5454: #
                   5455: # Parameters
                   5456: #   $cmd       - Command keyword that caused us to be dispatched.
                   5457: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5458: #               domain - the domain whose roles we are recording  
                   5459: #               role -   Consists of key=value pair
                   5460: #                        where key is unique role
                   5461: #                        and value is start/end date information
                   5462: #   $client    - Socket open on the client.
                   5463: #
                   5464: # Returns:
                   5465: #    1 - indicating processing should continue.
                   5466: # Side effects
                   5467: #     reply is written to $client.
                   5468: #
                   5469: 
                   5470: sub put_domainroles_handler {
                   5471:     my ($cmd,$tail,$client) = @_;
                   5472: 
                   5473:     my $userinput = "$cmd:$tail";
                   5474:     my ($udom,$what)=split(/:/,$tail);
                   5475:     chomp($what);
                   5476:     my @pairs=split(/\&/,$what);
                   5477:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   5478:     if ($hashref) {
                   5479:         foreach my $pair (@pairs) {
                   5480:             my ($key,$value)=split(/=/,$pair);
                   5481:             $hashref->{$key}=$value;
                   5482:         }
1.311     albertel 5483:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5484:             &Reply($client, "ok\n", $userinput);
                   5485:         } else {
                   5486:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5487:                      "while attempting domroleput\n", $userinput);
                   5488:         }
                   5489:     } else {
                   5490:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5491:                   "while attempting domroleput\n", $userinput);
                   5492:     }
                   5493:                                                                                   
                   5494:     return 1;
                   5495: }
                   5496: 
                   5497: &register_handler("domroleput", \&put_domainroles_handler, 0, 1, 0);
                   5498: 
                   5499: #
                   5500: # Retrieves domain roles from nohist_domainroles database
                   5501: # Returns to client an & separated list of key=value pairs,
                   5502: # where key is role and value is start and end date information.
                   5503: #
                   5504: # Parameters
                   5505: #   $cmd       - Command keyword that caused us to be dispatched.
                   5506: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5507: #               domain - the domain whose domain roles table we dump
                   5508: #   $client    - Socket open on the client.
                   5509: #
                   5510: # Returns:
                   5511: #    1 - indicating processing should continue.
                   5512: # Side effects
                   5513: #     reply (& separated list of role=start/end info pairs) is
                   5514: #     written to $client.
                   5515: #
                   5516: sub dump_domainroles_handler {
                   5517:     my ($cmd, $tail, $client) = @_;
                   5518:                                                                                            
                   5519:     my $userinput = "$cmd:$tail";
                   5520:     my ($udom,$startfilter,$endfilter,$rolesfilter) = split(/:/,$tail);
                   5521:     chomp($rolesfilter);
                   5522:     my @roles = ();
                   5523:     if (defined($startfilter)) {
                   5524:         $startfilter=&unescape($startfilter);
                   5525:     } else {
                   5526:         $startfilter='.';
                   5527:     }
                   5528:     if (defined($endfilter)) {
                   5529:         $endfilter=&unescape($endfilter);
                   5530:     } else {
                   5531:         $endfilter='.';
                   5532:     }
                   5533:     if (defined($rolesfilter)) {
                   5534:         $rolesfilter=&unescape($rolesfilter);
1.300     albertel 5535: 	@roles = split(/\&/,$rolesfilter);
1.299     raeburn  5536:     }
1.421     raeburn  5537: 
1.299     raeburn  5538:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   5539:     if ($hashref) {
                   5540:         my $qresult = '';
                   5541:         while (my ($key,$value) = each(%$hashref)) {
                   5542:             my $match = 1;
1.421     raeburn  5543:             my ($end,$start) = split(/:/,&unescape($value));
1.299     raeburn  5544:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,&unescape($key));
1.421     raeburn  5545:             unless (@roles < 1) {
                   5546:                 unless (grep/^\Q$trole\E$/,@roles) {
                   5547:                     $match = 0;
                   5548:                     next;
                   5549:                 }
                   5550:             }
1.299     raeburn  5551:             unless ($startfilter eq '.' || !defined($startfilter)) {
1.415     raeburn  5552:                 if ((defined($start)) && ($start >= $startfilter)) {
1.299     raeburn  5553:                     $match = 0;
1.421     raeburn  5554:                     next;
1.299     raeburn  5555:                 }
                   5556:             }
                   5557:             unless ($endfilter eq '.' || !defined($endfilter)) {
1.421     raeburn  5558:                 if ((defined($end)) && (($end > 0) && ($end <= $endfilter))) {
1.299     raeburn  5559:                     $match = 0;
1.421     raeburn  5560:                     next;
1.299     raeburn  5561:                 }
                   5562:             }
                   5563:             if ($match == 1) {
                   5564:                 $qresult.=$key.'='.$value.'&';
                   5565:             }
                   5566:         }
1.311     albertel 5567:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5568:             chop($qresult);
1.387     albertel 5569:             &Reply($client, \$qresult, $userinput);
1.299     raeburn  5570:         } else {
                   5571:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5572:                     "while attempting domrolesdump\n", $userinput);
                   5573:         }
                   5574:     } else {
                   5575:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5576:                 "while attempting domrolesdump\n", $userinput);
                   5577:     }
                   5578:     return 1;
                   5579: }
                   5580: 
                   5581: &register_handler("domrolesdump", \&dump_domainroles_handler, 0, 1, 0);
                   5582: 
                   5583: 
1.238     foxr     5584: #  Process the tmpput command I'm not sure what this does.. Seems to
                   5585: #  create a file in the lonDaemons/tmp directory of the form $id.tmp
                   5586: # where Id is the client's ip concatenated with a sequence number.
                   5587: # The file will contain some value that is passed in.  Is this e.g.
                   5588: # a login token?
                   5589: #
                   5590: # Parameters:
                   5591: #    $cmd     - The command that got us dispatched.
                   5592: #    $tail    - The remainder of the request following $cmd:
                   5593: #               In this case this will be the contents of the file.
                   5594: #    $client  - Socket connected to the client.
                   5595: # Returns:
                   5596: #    1 indicating processing can continue.
                   5597: # Side effects:
                   5598: #   A file is created in the local filesystem.
                   5599: #   A reply is sent to the client.
                   5600: sub tmp_put_handler {
                   5601:     my ($cmd, $what, $client) = @_;
                   5602: 
                   5603:     my $userinput = "$cmd:$what";	# Reconstruct for logging.
                   5604: 
1.347     raeburn  5605:     my ($record,$context) = split(/:/,$what);
                   5606:     if ($context ne '') {
                   5607:         chomp($context);
                   5608:         $context = &unescape($context);
                   5609:     }
                   5610:     my ($id,$store);
1.238     foxr     5611:     $tmpsnum++;
1.454     raeburn  5612:     if (($context eq 'resetpw') || ($context eq 'createaccount')) {
1.347     raeburn  5613:         $id = &md5_hex(&md5_hex(time.{}.rand().$$));
                   5614:     } else {
                   5615:         $id = $$.'_'.$clientip.'_'.$tmpsnum;
                   5616:     }
1.238     foxr     5617:     $id=~s/\W/\_/g;
1.347     raeburn  5618:     $record=~s/\n//g;
1.238     foxr     5619:     my $execdir=$perlvar{'lonDaemons'};
                   5620:     if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
1.347     raeburn  5621: 	print $store $record;
1.238     foxr     5622: 	close $store;
1.387     albertel 5623: 	&Reply($client, \$id, $userinput);
1.238     foxr     5624:     } else {
                   5625: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   5626: 		  "while attempting tmpput\n", $userinput);
                   5627:     }
                   5628:     return 1;
                   5629:   
                   5630: }
                   5631: &register_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
1.263     albertel 5632: 
1.238     foxr     5633: #   Processes the tmpget command.  This command returns the contents
                   5634: #  of a temporary resource file(?) created via tmpput.
                   5635: #
                   5636: # Paramters:
                   5637: #    $cmd      - Command that got us dispatched.
                   5638: #    $id       - Tail of the command, contain the id of the resource
                   5639: #                we want to fetch.
                   5640: #    $client   - socket open on the client.
                   5641: # Return:
                   5642: #    1         - Inidcating processing can continue.
                   5643: # Side effects:
                   5644: #   A reply is sent to the client.
                   5645: #
                   5646: sub tmp_get_handler {
                   5647:     my ($cmd, $id, $client) = @_;
                   5648: 
                   5649:     my $userinput = "$cmd:$id"; 
                   5650:     
                   5651: 
                   5652:     $id=~s/\W/\_/g;
                   5653:     my $store;
                   5654:     my $execdir=$perlvar{'lonDaemons'};
                   5655:     if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
                   5656: 	my $reply=<$store>;
1.387     albertel 5657: 	&Reply( $client, \$reply, $userinput);
1.238     foxr     5658: 	close $store;
                   5659:     } else {
                   5660: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   5661: 		  "while attempting tmpget\n", $userinput);
                   5662:     }
                   5663: 
                   5664:     return 1;
                   5665: }
                   5666: &register_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
1.263     albertel 5667: 
1.238     foxr     5668: #
                   5669: #  Process the tmpdel command.  This command deletes a temp resource
                   5670: #  created by the tmpput command.
                   5671: #
                   5672: # Parameters:
                   5673: #   $cmd      - Command that got us here.
                   5674: #   $id       - Id of the temporary resource created.
                   5675: #   $client   - socket open on the client process.
                   5676: #
                   5677: # Returns:
                   5678: #   1     - Indicating processing should continue.
                   5679: # Side Effects:
                   5680: #   A file is deleted
                   5681: #   A reply is sent to the client.
                   5682: sub tmp_del_handler {
                   5683:     my ($cmd, $id, $client) = @_;
                   5684:     
                   5685:     my $userinput= "$cmd:$id";
                   5686:     
                   5687:     chomp($id);
                   5688:     $id=~s/\W/\_/g;
                   5689:     my $execdir=$perlvar{'lonDaemons'};
                   5690:     if (unlink("$execdir/tmp/$id.tmp")) {
                   5691: 	&Reply($client, "ok\n", $userinput);
                   5692:     } else {
                   5693: 	&Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
                   5694: 		  "while attempting tmpdel\n", $userinput);
                   5695:     }
                   5696:     
                   5697:     return 1;
                   5698: 
                   5699: }
                   5700: &register_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
1.263     albertel 5701: 
1.238     foxr     5702: #
1.564     raeburn  5703: #  Process the updatebalcookie command.  This command updates a
                   5704: #  cookie in the lonBalancedir directory on a load balancer node.
                   5705: #
                   5706: # Parameters:
                   5707: #   $cmd      - Command that got us here.
                   5708: #   $tail     - Tail of the request (escaped cookie: escaped current entry)
                   5709: #
                   5710: #   $client   - socket open on the client process.
                   5711: #
                   5712: # Returns:
                   5713: #   1     - Indicating processing should continue.
                   5714: # Side Effects:
                   5715: #   A cookie file is updated from the lonBalancedir directory
                   5716: #   A reply is sent to the client.
                   5717: #
                   5718: sub update_balcookie_handler {
                   5719:     my ($cmd, $tail, $client) = @_;
                   5720: 
                   5721:     my $userinput= "$cmd:$tail";
                   5722:     chomp($tail);
                   5723:     my ($cookie,$lastentry) = map { &unescape($_) } (split(/:/,$tail));
                   5724: 
                   5725:     my $updatedone;
                   5726:     if ($cookie =~ /^$LONCAPA::match_domain\_$LONCAPA::match_username\_[a-f0-9]{32}$/) {
                   5727:         my $execdir=$perlvar{'lonBalanceDir'};
                   5728:         if (-e "$execdir/$cookie.id") {
                   5729:             my $doupdate;
                   5730:             if (open(my $fh,'<',"$execdir/$cookie.id")) {
                   5731:                 while (my $line = <$fh>) {
                   5732:                     chomp($line);
                   5733:                     if ($line eq $lastentry) {
                   5734:                         $doupdate = 1;
                   5735:                         last;
                   5736:                     }
                   5737:                 }
                   5738:                 close($fh);
                   5739:             }
                   5740:             if ($doupdate) {
                   5741:                 if (open(my $fh,'>',"$execdir/$cookie.id")) {
                   5742:                     print $fh $clientname;
                   5743:                     close($fh);
                   5744:                     $updatedone = 1;
                   5745:                 }
                   5746:             }
                   5747:         }
                   5748:     }
                   5749:     if ($updatedone) {
                   5750:         &Reply($client, "ok\n", $userinput);
                   5751:     } else {
                   5752:         &Failure( $client, "error: ".($!+0)."file update failed ".
                   5753:                   "while attempting updatebalcookie\n", $userinput);
                   5754:     }
                   5755:     return 1;
                   5756: }
                   5757: &register_handler("updatebalcookie", \&update_balcookie_handler, 0, 1, 0);
                   5758: 
                   5759: #
1.551     raeburn  5760: #  Process the delbalcookie command. This command deletes a balancer
1.564     raeburn  5761: #  cookie in the lonBalancedir directory on a load balancer node.
1.551     raeburn  5762: #
                   5763: # Parameters:
                   5764: #   $cmd      - Command that got us here.
                   5765: #   $cookie   - Cookie to be deleted.
                   5766: #   $client   - socket open on the client process.
                   5767: #
                   5768: # Returns:
                   5769: #   1     - Indicating processing should continue.
                   5770: # Side Effects:
                   5771: #   A cookie file is deleted from the lonBalancedir directory
                   5772: #   A reply is sent to the client.
                   5773: sub del_balcookie_handler {
                   5774:     my ($cmd, $cookie, $client) = @_;
                   5775: 
                   5776:     my $userinput= "$cmd:$cookie";
                   5777: 
                   5778:     chomp($cookie);
1.564     raeburn  5779:     $cookie = &unescape($cookie);
1.551     raeburn  5780:     my $deleted = '';
                   5781:     if ($cookie =~ /^$LONCAPA::match_domain\_$LONCAPA::match_username\_[a-f0-9]{32}$/) {
                   5782:         my $execdir=$perlvar{'lonBalanceDir'};
                   5783:         if (-e "$execdir/$cookie.id") {
                   5784:             if (open(my $fh,'<',"$execdir/$cookie.id")) {
                   5785:                 my $dodelete;
                   5786:                 while (my $line = <$fh>) {
                   5787:                     chomp($line);
                   5788:                     if ($line eq $clientname) {
                   5789:                         $dodelete = 1;
1.554     raeburn  5790:                         last;
1.551     raeburn  5791:                     }
                   5792:                 }
1.554     raeburn  5793:                 close($fh);
1.551     raeburn  5794:                 if ($dodelete) {
                   5795:                     if (unlink("$execdir/$cookie.id")) {
                   5796:                         $deleted = 1;
                   5797:                     }
                   5798:                 }
                   5799:             }
                   5800:         }
                   5801:     }
                   5802:     if ($deleted) {
                   5803:         &Reply($client, "ok\n", $userinput);
                   5804:     } else {
                   5805:         &Failure( $client, "error: ".($!+0)."Unlinking cookie file Failed ".
                   5806:                   "while attempting delbalcookie\n", $userinput);
                   5807:     }
                   5808:     return 1;
                   5809: }
                   5810: &register_handler("delbalcookie", \&del_balcookie_handler, 0, 1, 0);
                   5811: 
                   5812: #
1.246     foxr     5813: #   Processes the setannounce command.  This command
                   5814: #   creates a file named announce.txt in the top directory of
                   5815: #   the documentn root and sets its contents.  The announce.txt file is
                   5816: #   printed in its entirety at the LonCAPA login page.  Note:
                   5817: #   once the announcement.txt fileis created it cannot be deleted.
                   5818: #   However, setting the contents of the file to empty removes the
                   5819: #   announcement from the login page of loncapa so who cares.
                   5820: #
                   5821: # Parameters:
                   5822: #    $cmd          - The command that got us dispatched.
                   5823: #    $announcement - The text of the announcement.
                   5824: #    $client       - Socket open on the client process.
                   5825: # Retunrns:
                   5826: #   1             - Indicating request processing should continue
                   5827: # Side Effects:
                   5828: #   The file {DocRoot}/announcement.txt is created.
                   5829: #   A reply is sent to $client.
                   5830: #
                   5831: sub set_announce_handler {
                   5832:     my ($cmd, $announcement, $client) = @_;
                   5833:   
                   5834:     my $userinput    = "$cmd:$announcement";
                   5835: 
                   5836:     chomp($announcement);
                   5837:     $announcement=&unescape($announcement);
                   5838:     if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
                   5839: 				'/announcement.txt')) {
                   5840: 	print $store $announcement;
                   5841: 	close $store;
                   5842: 	&Reply($client, "ok\n", $userinput);
                   5843:     } else {
                   5844: 	&Failure($client, "error: ".($!+0)."\n", $userinput);
                   5845:     }
                   5846: 
                   5847:     return 1;
                   5848: }
                   5849: &register_handler("setannounce", \&set_announce_handler, 0, 1, 0);
1.263     albertel 5850: 
1.246     foxr     5851: #
                   5852: #  Return the version of the daemon.  This can be used to determine
                   5853: #  the compatibility of cross version installations or, alternatively to
                   5854: #  simply know who's out of date and who isn't.  Note that the version
                   5855: #  is returned concatenated with the tail.
                   5856: # Parameters:
                   5857: #   $cmd        - the request that dispatched to us.
                   5858: #   $tail       - Tail of the request (client's version?).
                   5859: #   $client     - Socket open on the client.
                   5860: #Returns:
                   5861: #   1 - continue processing requests.
                   5862: # Side Effects:
                   5863: #   Replies with version to $client.
                   5864: sub get_version_handler {
                   5865:     my ($cmd, $tail, $client) = @_;
                   5866: 
                   5867:     my $userinput  = $cmd.$tail;
                   5868:     
                   5869:     &Reply($client, &version($userinput)."\n", $userinput);
                   5870: 
                   5871: 
                   5872:     return 1;
                   5873: }
                   5874: &register_handler("version", \&get_version_handler, 0, 1, 0);
1.263     albertel 5875: 
1.246     foxr     5876: #  Set the current host and domain.  This is used to support
                   5877: #  multihomed systems.  Each IP of the system, or even separate daemons
                   5878: #  on the same IP can be treated as handling a separate lonCAPA virtual
                   5879: #  machine.  This command selects the virtual lonCAPA.  The client always
                   5880: #  knows the right one since it is lonc and it is selecting the domain/system
                   5881: #  from the hosts.tab file.
                   5882: # Parameters:
                   5883: #    $cmd      - Command that dispatched us.
                   5884: #    $tail     - Tail of the command (domain/host requested).
                   5885: #    $socket   - Socket open on the client.
                   5886: #
                   5887: # Returns:
                   5888: #     1   - Indicates the program should continue to process requests.
                   5889: # Side-effects:
                   5890: #     The default domain/system context is modified for this daemon.
                   5891: #     a reply is sent to the client.
                   5892: #
                   5893: sub set_virtual_host_handler {
                   5894:     my ($cmd, $tail, $socket) = @_;
                   5895:   
                   5896:     my $userinput  ="$cmd:$tail";
                   5897: 
                   5898:     &Reply($client, &sethost($userinput)."\n", $userinput);
                   5899: 
                   5900: 
                   5901:     return 1;
                   5902: }
1.247     albertel 5903: &register_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
1.246     foxr     5904: 
                   5905: #  Process a request to exit:
                   5906: #   - "bye" is sent to the client.
                   5907: #   - The client socket is shutdown and closed.
                   5908: #   - We indicate to the caller that we should exit.
                   5909: # Formal Parameters:
                   5910: #   $cmd                - The command that got us here.
                   5911: #   $tail               - Tail of the command (empty).
                   5912: #   $client             - Socket open on the tail.
                   5913: # Returns:
                   5914: #   0      - Indicating the program should exit!!
                   5915: #
                   5916: sub exit_handler {
                   5917:     my ($cmd, $tail, $client) = @_;
                   5918: 
                   5919:     my $userinput = "$cmd:$tail";
                   5920: 
                   5921:     &logthis("Client $clientip ($clientname) hanging up: $userinput");
                   5922:     &Reply($client, "bye\n", $userinput);
                   5923:     $client->shutdown(2);        # shutdown the socket forcibly.
                   5924:     $client->close();
                   5925: 
                   5926:     return 0;
                   5927: }
1.248     foxr     5928: &register_handler("exit", \&exit_handler, 0,1,1);
                   5929: &register_handler("init", \&exit_handler, 0,1,1);
                   5930: &register_handler("quit", \&exit_handler, 0,1,1);
                   5931: 
                   5932: #  Determine if auto-enrollment is enabled.
                   5933: #  Note that the original had what I believe to be a defect.
                   5934: #  The original returned 0 if the requestor was not a registerd client.
                   5935: #  It should return "refused".
                   5936: # Formal Parameters:
                   5937: #   $cmd       - The command that invoked us.
                   5938: #   $tail      - The tail of the command (Extra command parameters.
                   5939: #   $client    - The socket open on the client that issued the request.
                   5940: # Returns:
                   5941: #    1         - Indicating processing should continue.
                   5942: #
                   5943: sub enrollment_enabled_handler {
                   5944:     my ($cmd, $tail, $client) = @_;
                   5945:     my $userinput = $cmd.":".$tail; # For logging purposes.
                   5946: 
                   5947:     
1.337     albertel 5948:     my ($cdom) = split(/:/, $tail, 2);   # Domain we're asking about.
                   5949: 
1.248     foxr     5950:     my $outcome  = &localenroll::run($cdom);
1.387     albertel 5951:     &Reply($client, \$outcome, $userinput);
1.248     foxr     5952: 
                   5953:     return 1;
                   5954: }
                   5955: &register_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
                   5956: 
1.417     raeburn  5957: #
1.423     raeburn  5958: #   Validate an institutional code used for a LON-CAPA course.          
1.417     raeburn  5959: #
                   5960: # Formal Parameters:
                   5961: #   $cmd          - The command request that got us dispatched.
                   5962: #   $tail         - The tail of the command.  In this case,
                   5963: #                   this is a colon separated set of words that will be split
                   5964: #                   into:
1.424     raeburn  5965: #                        $dom      - The domain for which the check of 
                   5966: #                                    institutional course code will occur.
                   5967: #
                   5968: #                        $instcode - The institutional code for the course
                   5969: #                                    being requested, or validated for rights
                   5970: #                                    to request.
                   5971: #
                   5972: #                        $owner    - The course requestor (who will be the
                   5973: #                                    course owner, in the form username:domain
                   5974: #
1.417     raeburn  5975: #   $client       - Socket open on the client.
                   5976: # Returns:
                   5977: #    1           - Indicating processing should continue.
                   5978: #
                   5979: sub validate_instcode_handler {
                   5980:     my ($cmd, $tail, $client) = @_;
                   5981:     my $userinput = "$cmd:$tail";
1.423     raeburn  5982:     my ($dom,$instcode,$owner) = split(/:/, $tail);
1.422     raeburn  5983:     $instcode = &unescape($instcode);
                   5984:     $owner = &unescape($owner);
1.498     raeburn  5985:     my ($outcome,$description,$credits) = 
1.426     raeburn  5986:         &localenroll::validate_instcode($dom,$instcode,$owner);
1.498     raeburn  5987:     my $result = &escape($outcome).'&'.&escape($description).'&'.
                   5988:                  &escape($credits);
1.426     raeburn  5989:     &Reply($client, \$result, $userinput);
1.417     raeburn  5990: 
                   5991:     return 1;
                   5992: }
                   5993: &register_handler("autovalidateinstcode", \&validate_instcode_handler, 0, 1, 0);
                   5994: 
1.566     raeburn  5995: #
                   5996: #  Validate co-owner for cross-listed institutional code and
                   5997: #  institutional course code itself used for a LON-CAPA course.
                   5998: #
                   5999: # Formal Parameters:
                   6000: #   $cmd          - The command request that got us dispatched.
                   6001: #   $tail         - The tail of the command.  In this case,
                   6002: #                   this is a colon separated string containing:
                   6003: #      $dom            - Course's LON-CAPA domain
                   6004: #      $instcode       - Institutional course code for the course
                   6005: #      $inst_xlist     - Institutional course Id for the crosslisting
                   6006: #      $coowner        - Username of co-owner
                   6007: #      (values for all but $dom have been escaped). 
                   6008: #
                   6009: #   $client       - Socket open on the client.
                   6010: # Returns:
                   6011: #    1           - Indicating processing should continue.
                   6012: #
                   6013: sub validate_instcrosslist_handler  {
                   6014:     my ($cmd, $tail, $client) = @_;
                   6015:     my $userinput = "$cmd:$tail";
                   6016:     my ($dom,$instcode,$inst_xlist,$coowner) = split(/:/,$tail);
                   6017:     $instcode = &unescape($instcode);
                   6018:     $inst_xlist = &unescape($inst_xlist);
                   6019:     $coowner = &unescape($coowner);
                   6020:     my $outcome = &localenroll::validate_crosslist_access($dom,$instcode,
                   6021:                                                           $inst_xlist,$coowner);
                   6022:     &Reply($client, \$outcome, $userinput);
                   6023: 
                   6024:     return 1;
                   6025: }
                   6026: &register_handler("autovalidateinstcrosslist", \&validate_instcrosslist_handler, 0, 1, 0);
                   6027: 
1.248     foxr     6028: #   Get the official sections for which auto-enrollment is possible.
                   6029: #   Since the admin people won't know about 'unofficial sections' 
                   6030: #   we cannot auto-enroll on them.
                   6031: # Formal Parameters:
                   6032: #    $cmd     - The command request that got us dispatched here.
                   6033: #    $tail    - The remainder of the request.  In our case this
                   6034: #               will be split into:
                   6035: #               $coursecode   - The course name from the admin point of view.
                   6036: #               $cdom         - The course's domain(?).
                   6037: #    $client  - Socket open on the client.
                   6038: # Returns:
                   6039: #    1    - Indiciting processing should continue.
                   6040: #
                   6041: sub get_sections_handler {
                   6042:     my ($cmd, $tail, $client) = @_;
                   6043:     my $userinput = "$cmd:$tail";
                   6044: 
                   6045:     my ($coursecode, $cdom) = split(/:/, $tail);
                   6046:     my @secs = &localenroll::get_sections($coursecode,$cdom);
                   6047:     my $seclist = &escape(join(':',@secs));
                   6048: 
1.387     albertel 6049:     &Reply($client, \$seclist, $userinput);
1.248     foxr     6050:     
                   6051: 
                   6052:     return 1;
                   6053: }
                   6054: &register_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
                   6055: 
                   6056: #   Validate the owner of a new course section.  
                   6057: #
                   6058: # Formal Parameters:
                   6059: #   $cmd      - Command that got us dispatched.
                   6060: #   $tail     - the remainder of the command.  For us this consists of a
                   6061: #               colon separated string containing:
                   6062: #                  $inst    - Course Id from the institutions point of view.
                   6063: #                  $owner   - Proposed owner of the course.
                   6064: #                  $cdom    - Domain of the course (from the institutions
                   6065: #                             point of view?)..
                   6066: #   $client   - Socket open on the client.
                   6067: #
                   6068: # Returns:
                   6069: #   1        - Processing should continue.
                   6070: #
                   6071: sub validate_course_owner_handler {
                   6072:     my ($cmd, $tail, $client)  = @_;
                   6073:     my $userinput = "$cmd:$tail";
1.470     raeburn  6074:     my ($inst_course_id, $owner, $cdom, $coowners) = split(/:/, $tail);
                   6075:     
1.336     raeburn  6076:     $owner = &unescape($owner);
1.470     raeburn  6077:     $coowners = &unescape($coowners);
                   6078:     my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom,$coowners);
1.387     albertel 6079:     &Reply($client, \$outcome, $userinput);
1.248     foxr     6080: 
                   6081: 
                   6082: 
                   6083:     return 1;
                   6084: }
                   6085: &register_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
1.263     albertel 6086: 
1.248     foxr     6087: #
                   6088: #   Validate a course section in the official schedule of classes
                   6089: #   from the institutions point of view (part of autoenrollment).
                   6090: #
                   6091: # Formal Parameters:
                   6092: #   $cmd          - The command request that got us dispatched.
                   6093: #   $tail         - The tail of the command.  In this case,
                   6094: #                   this is a colon separated set of words that will be split
                   6095: #                   into:
                   6096: #                        $inst_course_id - The course/section id from the
                   6097: #                                          institutions point of view.
                   6098: #                        $cdom           - The domain from the institutions
                   6099: #                                          point of view.
                   6100: #   $client       - Socket open on the client.
                   6101: # Returns:
                   6102: #    1           - Indicating processing should continue.
                   6103: #
                   6104: sub validate_course_section_handler {
                   6105:     my ($cmd, $tail, $client) = @_;
                   6106:     my $userinput = "$cmd:$tail";
                   6107:     my ($inst_course_id, $cdom) = split(/:/, $tail);
                   6108: 
                   6109:     my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
1.387     albertel 6110:     &Reply($client, \$outcome, $userinput);
1.248     foxr     6111: 
                   6112: 
                   6113:     return 1;
                   6114: }
                   6115: &register_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
                   6116: 
                   6117: #
1.340     raeburn  6118: #   Validate course owner's access to enrollment data for specific class section. 
                   6119: #   
                   6120: #
                   6121: # Formal Parameters:
                   6122: #    $cmd     - The command request that got us dispatched.
                   6123: #    $tail    - The tail of the command.   In this case this is a colon separated
1.542     raeburn  6124: #               set of values that will be split into:
1.340     raeburn  6125: #               $inst_class  - Institutional code for the specific class section   
1.542     raeburn  6126: #               $ownerlist   - An escaped comma-separated list of username:domain 
                   6127: #                              of the course owner, and co-owner(s).
1.340     raeburn  6128: #               $cdom        - The domain of the course from the institution's
                   6129: #                              point of view.
                   6130: #    $client  - The socket open on the client.
                   6131: # Returns:
                   6132: #    1 - continue processing.
                   6133: #
                   6134: 
                   6135: sub validate_class_access_handler {
                   6136:     my ($cmd, $tail, $client) = @_;
                   6137:     my $userinput = "$cmd:$tail";
1.383     raeburn  6138:     my ($inst_class,$ownerlist,$cdom) = split(/:/, $tail);
1.392     raeburn  6139:     my $owners = &unescape($ownerlist);
1.341     albertel 6140:     my $outcome;
                   6141:     eval {
                   6142: 	local($SIG{__DIE__})='DEFAULT';
1.392     raeburn  6143: 	$outcome=&localenroll::check_section($inst_class,$owners,$cdom);
1.341     albertel 6144:     };
1.387     albertel 6145:     &Reply($client,\$outcome, $userinput);
1.340     raeburn  6146: 
                   6147:     return 1;
                   6148: }
                   6149: &register_handler("autovalidateclass_sec", \&validate_class_access_handler, 0, 1, 0);
                   6150: 
                   6151: #
1.567     raeburn  6152: #    Modify institutional sections (using customized &instsec_reformat()
                   6153: #    routine in localenroll.pm), to either clutter or declutter, for  
                   6154: #    purposes of ensuring an institutional course section (string) can
                   6155: #    be unambiguously separated into institutional course and section.
                   6156: #
                   6157: # Formal Parameters:
                   6158: #    $cmd     - The command request that got us dispatched.
                   6159: #    $tail    - The tail of the command.   In this case this is a colon separated
                   6160: #               set of values that will be split into:
                   6161: #               $cdom        - The LON-CAPA domain of the course.
                   6162: #               $action      - Either: clutter or declutter
                   6163: #                              clutter adds character(s) to eliminate ambiguity
                   6164: #                              declutter removes the added characters (e.g., for
                   6165: #                              display of the institutional course section string.
                   6166: #               $info        - A frozen hash in which keys are: 
                   6167: #                              LON-CAPA course number:Institutional course code
                   6168: #                              and values are a reference to an array of the
                   6169: #                              items to modify -- either institutional sections,
                   6170: #                              or institutional course sections (for crosslistings). 
                   6171: #    $client  - The socket open on the client.
                   6172: # Returns:
                   6173: #    1 - continue processing.
                   6174: #   
                   6175: 
                   6176: sub instsec_reformat_handler {
                   6177:     my ($cmd, $tail, $client) = @_;
                   6178:     my $userinput = "$cmd:$tail";
                   6179:     my ($cdom,$action,$info) = split(/:/,$tail);
                   6180:     my $instsecref = &Apache::lonnet::thaw_unescape($info);
                   6181:     my ($outcome,$result);
                   6182:     eval {
                   6183:         local($SIG{__DIE__})='DEFAULT';
                   6184:         $outcome=&localenroll::instsec_reformat($cdom,$action,$instsecref);
                   6185:         if ($outcome eq 'ok') {
                   6186:             if (ref($instsecref) eq 'HASH') {
                   6187:                 foreach my $key (keys(%{$instsecref})) {
                   6188:                     $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($instsecref->{$key}).'&';
                   6189:                 }
                   6190:                 $result =~ s/\&$//;
                   6191:             }
                   6192:         }
                   6193:     };
                   6194:     if (!$@) {
                   6195:         if ($outcome eq 'ok') {
                   6196:             &Reply( $client, \$result, $userinput);
                   6197:         } else {
                   6198:             &Reply($client,\$outcome, $userinput);
                   6199:         }
                   6200:     } else {
                   6201:         &Failure($client,"unknown_cmd\n",$userinput);
                   6202:     }
                   6203:     return 1;
                   6204: }
                   6205: &register_handler("autoinstsecreformat",\&instsec_reformat_handler, 0, 1, 0);
                   6206: 
                   6207: #
1.542     raeburn  6208: #   Validate course owner or co-owners(s) access to enrollment data for all sections
                   6209: #   and crosslistings for a particular course.
                   6210: #
                   6211: #
                   6212: # Formal Parameters:
                   6213: #    $cmd     - The command request that got us dispatched.
                   6214: #    $tail    - The tail of the command.   In this case this is a colon separated
                   6215: #               set of values that will be split into:
                   6216: #               $ownerlist   - An escaped comma-separated list of username:domain
                   6217: #                              of the course owner, and co-owner(s).
                   6218: #               $cdom        - The domain of the course from the institution's
                   6219: #                              point of view.
                   6220: #               $classes     - Frozen hash of institutional course sections and
                   6221: #                              crosslistings.
                   6222: #    $client  - The socket open on the client.
                   6223: # Returns:
                   6224: #    1 - continue processing.
                   6225: #
                   6226: 
                   6227: sub validate_classes_handler {
                   6228:     my ($cmd, $tail, $client) = @_;
                   6229:     my $userinput = "$cmd:$tail";
                   6230:     my ($ownerlist,$cdom,$classes) = split(/:/, $tail);
                   6231:     my $classesref = &Apache::lonnet::thaw_unescape($classes);
                   6232:     my $owners = &unescape($ownerlist);
                   6233:     my $result;
                   6234:     eval {
                   6235:         local($SIG{__DIE__})='DEFAULT';
                   6236:         my %validations;
                   6237:         my $response = &localenroll::check_instclasses($owners,$cdom,$classesref,
                   6238:                                                        \%validations);
                   6239:         if ($response eq 'ok') {
                   6240:             foreach my $key (keys(%validations)) {
                   6241:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
                   6242:             }
                   6243:             $result =~ s/\&$//;
                   6244:         } else {
                   6245:             $result = 'error';
                   6246:         }
                   6247:     };
                   6248:     if (!$@) {
                   6249:         &Reply($client, \$result, $userinput);
                   6250:     } else {
                   6251:         &Failure($client,"unknown_cmd\n",$userinput);
                   6252:     }
                   6253:     return 1;
                   6254: }
                   6255: &register_handler("autovalidateinstclasses", \&validate_classes_handler, 0, 1, 0);
                   6256: 
                   6257: #
1.340     raeburn  6258: #   Create a password for a new LON-CAPA user added by auto-enrollment.
                   6259: #   Only used for case where authentication method for new user is localauth
1.248     foxr     6260: #
                   6261: # Formal Parameters:
                   6262: #    $cmd     - The command request that got us dispatched.
                   6263: #    $tail    - The tail of the command.   In this case this is a colon separated
                   6264: #               set of words that will be split into:
1.340     raeburn  6265: #               $authparam - An authentication parameter (localauth parameter).
1.248     foxr     6266: #               $cdom      - The domain of the course from the institution's
                   6267: #                            point of view.
                   6268: #    $client  - The socket open on the client.
                   6269: # Returns:
                   6270: #    1 - continue processing.
                   6271: #
                   6272: sub create_auto_enroll_password_handler {
                   6273:     my ($cmd, $tail, $client) = @_;
                   6274:     my $userinput = "$cmd:$tail";
                   6275: 
                   6276:     my ($authparam, $cdom) = split(/:/, $userinput);
                   6277: 
                   6278:     my ($create_passwd,$authchk);
                   6279:     ($authparam,
                   6280:      $create_passwd,
                   6281:      $authchk) = &localenroll::create_password($authparam,$cdom);
                   6282: 
                   6283:     &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
                   6284: 	   $userinput);
                   6285: 
                   6286: 
                   6287:     return 1;
                   6288: }
                   6289: &register_handler("autocreatepassword", \&create_auto_enroll_password_handler, 
                   6290: 		  0, 1, 0);
                   6291: 
1.522     raeburn  6292: sub auto_export_grades_handler {
                   6293:     my ($cmd, $tail, $client) = @_;
                   6294:     my $userinput = "$cmd:$tail";
                   6295:     my ($cdom,$cnum,$info,$data) = split(/:/,$tail);
                   6296:     my $inforef = &Apache::lonnet::thaw_unescape($info);
                   6297:     my $dataref = &Apache::lonnet::thaw_unescape($data);
                   6298:     my ($outcome,$result);;
                   6299:     eval {
                   6300:         local($SIG{__DIE__})='DEFAULT';
                   6301:         my %rtnhash;
                   6302:         $outcome=&localenroll::export_grades($cdom,$cnum,$inforef,$dataref,\%rtnhash);
                   6303:         if ($outcome eq 'ok') {
                   6304:             foreach my $key (keys(%rtnhash)) {
                   6305:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
                   6306:             }
                   6307:             $result =~ s/\&$//;
                   6308:         }
                   6309:     };
                   6310:     if (!$@) {
                   6311:         if ($outcome eq 'ok') {
                   6312:             if ($cipher) {
                   6313:                 my $cmdlength=length($result);
                   6314:                 $result.="         ";
                   6315:                 my $encresult='';
                   6316:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   6317:                     $encresult.= unpack("H16",
                   6318:                                         $cipher->encrypt(substr($result,
                   6319:                                                                 $encidx,
                   6320:                                                                 8)));
                   6321:                 }
                   6322:                 &Reply( $client, "enc:$cmdlength:$encresult\n", $userinput);
                   6323:             } else {
                   6324:                 &Failure( $client, "error:no_key\n", $userinput);
                   6325:             }
                   6326:         } else {
                   6327:             &Reply($client, "$outcome\n", $userinput);
                   6328:         }
                   6329:     } else {
                   6330:         &Failure($client,"export_error\n",$userinput);
                   6331:     }
                   6332:     return 1;
                   6333: }
                   6334: &register_handler("autoexportgrades", \&auto_export_grades_handler,
1.536     raeburn  6335:                   1, 1, 0);
1.522     raeburn  6336: 
1.248     foxr     6337: #   Retrieve and remove temporary files created by/during autoenrollment.
                   6338: #
                   6339: # Formal Parameters:
                   6340: #    $cmd      - The command that got us dispatched.
                   6341: #    $tail     - The tail of the command.  In our case this is a colon 
                   6342: #                separated list that will be split into:
1.526     raeburn  6343: #                $filename - The name of the file to retrieve.
1.248     foxr     6344: #                            The filename is given as a path relative to
                   6345: #                            the LonCAPA temp file directory.
                   6346: #    $client   - Socket open on the client.
                   6347: #
                   6348: # Returns:
                   6349: #   1     - Continue processing.
                   6350: sub retrieve_auto_file_handler {
                   6351:     my ($cmd, $tail, $client)    = @_;
                   6352:     my $userinput                = "cmd:$tail";
                   6353: 
                   6354:     my ($filename)   = split(/:/, $tail);
                   6355: 
                   6356:     my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
1.521     raeburn  6357: 
                   6358:     if ($filename =~m{/\.\./}) {
                   6359:         &Failure($client, "refused\n", $userinput);
1.526     raeburn  6360:     } elsif ($filename !~ /^$LONCAPA::match_domain\_$LONCAPA::match_courseid\_.+_classlist\.xml$/) {
                   6361:         &Failure($client, "refused\n", $userinput);
1.521     raeburn  6362:     } elsif ( (-e $source) && ($filename ne '') ) {
1.248     foxr     6363: 	my $reply = '';
                   6364: 	if (open(my $fh,$source)) {
                   6365: 	    while (<$fh>) {
                   6366: 		chomp($_);
                   6367: 		$_ =~ s/^\s+//g;
                   6368: 		$_ =~ s/\s+$//g;
                   6369: 		$reply .= $_;
                   6370: 	    }
                   6371: 	    close($fh);
                   6372: 	    &Reply($client, &escape($reply)."\n", $userinput);
                   6373: 
                   6374: #   Does this have to be uncommented??!?  (RF).
                   6375: #
                   6376: #                                unlink($source);
                   6377: 	} else {
                   6378: 	    &Failure($client, "error\n", $userinput);
                   6379: 	}
                   6380:     } else {
                   6381: 	&Failure($client, "error\n", $userinput);
                   6382:     }
                   6383:     
                   6384: 
                   6385:     return 1;
                   6386: }
                   6387: &register_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
                   6388: 
1.423     raeburn  6389: sub crsreq_checks_handler {
                   6390:     my ($cmd, $tail, $client) = @_;
                   6391:     my $userinput = "$cmd:$tail";
                   6392:     my $dom = $tail;
                   6393:     my $result;
1.519     raeburn  6394:     my @reqtypes = ('official','unofficial','community','textbook','placement');
1.423     raeburn  6395:     eval {
                   6396:         local($SIG{__DIE__})='DEFAULT';
                   6397:         my %validations;
1.424     raeburn  6398:         my $response = &localenroll::crsreq_checks($dom,\@reqtypes,
                   6399:                                                    \%validations);
1.423     raeburn  6400:         if ($response eq 'ok') { 
                   6401:             foreach my $key (keys(%validations)) {
                   6402:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
                   6403:             }
                   6404:             $result =~ s/\&$//;
                   6405:         } else {
                   6406:             $result = 'error';
                   6407:         }
                   6408:     };
                   6409:     if (!$@) {
                   6410:         &Reply($client, \$result, $userinput);
                   6411:     } else {
                   6412:         &Failure($client,"unknown_cmd\n",$userinput);
                   6413:     }
                   6414:     return 1;
                   6415: }
                   6416: &register_handler("autocrsreqchecks", \&crsreq_checks_handler, 0, 1, 0);
                   6417: 
                   6418: sub validate_crsreq_handler {
                   6419:     my ($cmd, $tail, $client) = @_;
                   6420:     my $userinput = "$cmd:$tail";
1.508     raeburn  6421:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$customdata) = split(/:/, $tail);
1.423     raeburn  6422:     $instcode = &unescape($instcode);
                   6423:     $owner = &unescape($owner);
                   6424:     $crstype = &unescape($crstype);
                   6425:     $inststatuslist = &unescape($inststatuslist);
                   6426:     $instcode = &unescape($instcode);
                   6427:     $instseclist = &unescape($instseclist);
1.508     raeburn  6428:     my $custominfo = &Apache::lonnet::thaw_unescape($customdata);
1.423     raeburn  6429:     my $outcome;
                   6430:     eval {
                   6431:         local($SIG{__DIE__})='DEFAULT';
                   6432:         $outcome = &localenroll::validate_crsreq($dom,$owner,$crstype,
                   6433:                                                  $inststatuslist,$instcode,
1.508     raeburn  6434:                                                  $instseclist,$custominfo);
1.423     raeburn  6435:     };
                   6436:     if (!$@) {
                   6437:         &Reply($client, \$outcome, $userinput);
                   6438:     } else {
                   6439:         &Failure($client,"unknown_cmd\n",$userinput);
                   6440:     }
                   6441:     return 1;
                   6442: }
                   6443: &register_handler("autocrsreqvalidation", \&validate_crsreq_handler, 0, 1, 0);
                   6444: 
1.506     raeburn  6445: sub crsreq_update_handler {
                   6446:     my ($cmd, $tail, $client) = @_;
                   6447:     my $userinput = "$cmd:$tail";
1.509     raeburn  6448:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,$code,
                   6449:         $accessstart,$accessend,$infohashref) =
1.506     raeburn  6450:         split(/:/, $tail);
                   6451:     $crstype = &unescape($crstype);
                   6452:     $action = &unescape($action);
                   6453:     $ownername = &unescape($ownername);
                   6454:     $ownerdomain = &unescape($ownerdomain);
                   6455:     $fullname = &unescape($fullname);
                   6456:     $title = &unescape($title);
                   6457:     $code = &unescape($code);
1.509     raeburn  6458:     $accessstart = &unescape($accessstart);
                   6459:     $accessend = &unescape($accessend);
1.506     raeburn  6460:     my $incoming = &Apache::lonnet::thaw_unescape($infohashref);
                   6461:     my ($result,$outcome);
                   6462:     eval {
                   6463:         local($SIG{__DIE__})='DEFAULT';
                   6464:         my %rtnhash;
                   6465:         $outcome = &localenroll::crsreq_updates($cdom,$cnum,$crstype,$action,
                   6466:                                                 $ownername,$ownerdomain,$fullname,
1.509     raeburn  6467:                                                 $title,$code,$accessstart,$accessend,
                   6468:                                                 $incoming,\%rtnhash);
1.506     raeburn  6469:         if ($outcome eq 'ok') {
1.515     raeburn  6470:             my @posskeys = qw(createdweb createdmsg createdcustomized createdactions queuedweb queuedmsg formitems reviewweb validationjs onload javascript);
1.506     raeburn  6471:             foreach my $key (keys(%rtnhash)) {
                   6472:                 if (grep(/^\Q$key\E/,@posskeys)) {
                   6473:                     $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
                   6474:                 }
                   6475:             }
                   6476:             $result =~ s/\&$//;
                   6477:         }
                   6478:     };
                   6479:     if (!$@) {
                   6480:         if ($outcome eq 'ok') {
                   6481:             &Reply($client, \$result, $userinput);
                   6482:         } else {
                   6483:             &Reply($client, "format_error\n", $userinput);
                   6484:         }
                   6485:     } else {
                   6486:         &Failure($client,"unknown_cmd\n",$userinput);
                   6487:     }
                   6488:     return 1;
                   6489: }
                   6490: &register_handler("autocrsrequpdate", \&crsreq_update_handler, 0, 1, 0);
                   6491: 
1.248     foxr     6492: #
                   6493: #   Read and retrieve institutional code format (for support form).
                   6494: # Formal Parameters:
                   6495: #    $cmd        - Command that dispatched us.
                   6496: #    $tail       - Tail of the command.  In this case it conatins 
                   6497: #                  the course domain and the coursename.
                   6498: #    $client     - Socket open on the client.
                   6499: # Returns:
                   6500: #    1     - Continue processing.
                   6501: #
                   6502: sub get_institutional_code_format_handler {
                   6503:     my ($cmd, $tail, $client)   = @_;
                   6504:     my $userinput               = "$cmd:$tail";
                   6505: 
                   6506:     my $reply;
                   6507:     my($cdom,$course) = split(/:/,$tail);
                   6508:     my @pairs = split/\&/,$course;
                   6509:     my %instcodes = ();
                   6510:     my %codes = ();
                   6511:     my @codetitles = ();
                   6512:     my %cat_titles = ();
                   6513:     my %cat_order = ();
                   6514:     foreach (@pairs) {
                   6515: 	my ($key,$value) = split/=/,$_;
                   6516: 	$instcodes{&unescape($key)} = &unescape($value);
                   6517:     }
                   6518:     my $formatreply = &localenroll::instcode_format($cdom,
                   6519: 						    \%instcodes,
                   6520: 						    \%codes,
                   6521: 						    \@codetitles,
                   6522: 						    \%cat_titles,
                   6523: 						    \%cat_order);
                   6524:     if ($formatreply eq 'ok') {
1.365     albertel 6525: 	my $codes_str = &Apache::lonnet::hash2str(%codes);
                   6526: 	my $codetitles_str = &Apache::lonnet::array2str(@codetitles);
                   6527: 	my $cat_titles_str = &Apache::lonnet::hash2str(%cat_titles);
                   6528: 	my $cat_order_str = &Apache::lonnet::hash2str(%cat_order);
1.248     foxr     6529: 	&Reply($client,
                   6530: 	       $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
                   6531: 	       .$cat_order_str."\n",
                   6532: 	       $userinput);
                   6533:     } else {
                   6534: 	# this else branch added by RF since if not ok, lonc will
                   6535: 	# hang waiting on reply until timeout.
                   6536: 	#
                   6537: 	&Reply($client, "format_error\n", $userinput);
                   6538:     }
                   6539:     
                   6540:     return 1;
                   6541: }
1.265     albertel 6542: &register_handler("autoinstcodeformat",
                   6543: 		  \&get_institutional_code_format_handler,0,1,0);
1.246     foxr     6544: 
1.345     raeburn  6545: sub get_institutional_defaults_handler {
                   6546:     my ($cmd, $tail, $client)   = @_;
                   6547:     my $userinput               = "$cmd:$tail";
                   6548: 
                   6549:     my $dom = $tail;
                   6550:     my %defaults_hash;
                   6551:     my @code_order;
                   6552:     my $outcome;
                   6553:     eval {
                   6554:         local($SIG{__DIE__})='DEFAULT';
                   6555:         $outcome = &localenroll::instcode_defaults($dom,\%defaults_hash,
                   6556:                                                    \@code_order);
                   6557:     };
                   6558:     if (!$@) {
                   6559:         if ($outcome eq 'ok') {
                   6560:             my $result='';
                   6561:             while (my ($key,$value) = each(%defaults_hash)) {
                   6562:                 $result.=&escape($key).'='.&escape($value).'&';
                   6563:             }
                   6564:             $result .= 'code_order='.&escape(join('&',@code_order));
1.387     albertel 6565:             &Reply($client,\$result,$userinput);
1.345     raeburn  6566:         } else {
                   6567:             &Reply($client,"error\n", $userinput);
                   6568:         }
                   6569:     } else {
                   6570:         &Failure($client,"unknown_cmd\n",$userinput);
                   6571:     }
                   6572: }
                   6573: &register_handler("autoinstcodedefaults",
                   6574:                   \&get_institutional_defaults_handler,0,1,0);
                   6575: 
1.416     raeburn  6576: sub get_possible_instcodes_handler {
                   6577:     my ($cmd, $tail, $client)   = @_;
                   6578:     my $userinput               = "$cmd:$tail";
                   6579: 
                   6580:     my $reply;
                   6581:     my $cdom = $tail;
1.417     raeburn  6582:     my (@codetitles,%cat_titles,%cat_order,@code_order);
1.416     raeburn  6583:     my $formatreply = &localenroll::possible_instcodes($cdom,
                   6584:                                                        \@codetitles,
                   6585:                                                        \%cat_titles,
1.417     raeburn  6586:                                                        \%cat_order,
                   6587:                                                        \@code_order);
1.416     raeburn  6588:     if ($formatreply eq 'ok') {
                   6589:         my $result = join('&',map {&escape($_);} (@codetitles)).':';
1.417     raeburn  6590:         $result .= join('&',map {&escape($_);} (@code_order)).':';
1.416     raeburn  6591:         foreach my $key (keys(%cat_titles)) {
                   6592:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_titles{$key}).'&';
                   6593:         }
                   6594:         $result =~ s/\&$//;
                   6595:         $result .= ':';
                   6596:         foreach my $key (keys(%cat_order)) {
                   6597:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_order{$key}).'&';
                   6598:         }
                   6599:         $result =~ s/\&$//;
                   6600:         &Reply($client,\$result,$userinput);
                   6601:     } else {
                   6602:         &Reply($client, "format_error\n", $userinput);
                   6603:     }
                   6604:     return 1;
                   6605: }
                   6606: &register_handler("autopossibleinstcodes",
                   6607:                   \&get_possible_instcodes_handler,0,1,0);
                   6608: 
1.381     raeburn  6609: sub get_institutional_user_rules {
                   6610:     my ($cmd, $tail, $client)   = @_;
                   6611:     my $userinput               = "$cmd:$tail";
                   6612:     my $dom = &unescape($tail);
                   6613:     my (%rules_hash,@rules_order);
                   6614:     my $outcome;
                   6615:     eval {
                   6616:         local($SIG{__DIE__})='DEFAULT';
                   6617:         $outcome = &localenroll::username_rules($dom,\%rules_hash,\@rules_order);
                   6618:     };
                   6619:     if (!$@) {
                   6620:         if ($outcome eq 'ok') {
                   6621:             my $result;
                   6622:             foreach my $key (keys(%rules_hash)) {
                   6623:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6624:             }
                   6625:             $result =~ s/\&$//;
                   6626:             $result .= ':';
                   6627:             if (@rules_order > 0) {
                   6628:                 foreach my $item (@rules_order) {
                   6629:                     $result .= &escape($item).'&';
                   6630:                 }
                   6631:             }
                   6632:             $result =~ s/\&$//;
1.387     albertel 6633:             &Reply($client,\$result,$userinput);
1.381     raeburn  6634:         } else {
                   6635:             &Reply($client,"error\n", $userinput);
                   6636:         }
                   6637:     } else {
                   6638:         &Failure($client,"unknown_cmd\n",$userinput);
                   6639:     }
                   6640: }
                   6641: &register_handler("instuserrules",\&get_institutional_user_rules,0,1,0);
                   6642: 
1.389     raeburn  6643: sub get_institutional_id_rules {
                   6644:     my ($cmd, $tail, $client)   = @_;
                   6645:     my $userinput               = "$cmd:$tail";
                   6646:     my $dom = &unescape($tail);
                   6647:     my (%rules_hash,@rules_order);
                   6648:     my $outcome;
                   6649:     eval {
                   6650:         local($SIG{__DIE__})='DEFAULT';
                   6651:         $outcome = &localenroll::id_rules($dom,\%rules_hash,\@rules_order);
                   6652:     };
                   6653:     if (!$@) {
                   6654:         if ($outcome eq 'ok') {
                   6655:             my $result;
                   6656:             foreach my $key (keys(%rules_hash)) {
                   6657:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6658:             }
                   6659:             $result =~ s/\&$//;
                   6660:             $result .= ':';
                   6661:             if (@rules_order > 0) {
                   6662:                 foreach my $item (@rules_order) {
                   6663:                     $result .= &escape($item).'&';
                   6664:                 }
                   6665:             }
                   6666:             $result =~ s/\&$//;
                   6667:             &Reply($client,\$result,$userinput);
                   6668:         } else {
                   6669:             &Reply($client,"error\n", $userinput);
                   6670:         }
                   6671:     } else {
                   6672:         &Failure($client,"unknown_cmd\n",$userinput);
                   6673:     }
                   6674: }
                   6675: &register_handler("instidrules",\&get_institutional_id_rules,0,1,0);
                   6676: 
1.397     raeburn  6677: sub get_institutional_selfcreate_rules {
1.396     raeburn  6678:     my ($cmd, $tail, $client)   = @_;
                   6679:     my $userinput               = "$cmd:$tail";
                   6680:     my $dom = &unescape($tail);
                   6681:     my (%rules_hash,@rules_order);
                   6682:     my $outcome;
                   6683:     eval {
                   6684:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  6685:         $outcome = &localenroll::selfcreate_rules($dom,\%rules_hash,\@rules_order);
1.396     raeburn  6686:     };
                   6687:     if (!$@) {
                   6688:         if ($outcome eq 'ok') {
                   6689:             my $result;
                   6690:             foreach my $key (keys(%rules_hash)) {
                   6691:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6692:             }
                   6693:             $result =~ s/\&$//;
                   6694:             $result .= ':';
                   6695:             if (@rules_order > 0) {
                   6696:                 foreach my $item (@rules_order) {
                   6697:                     $result .= &escape($item).'&';
                   6698:                 }
                   6699:             }
                   6700:             $result =~ s/\&$//;
                   6701:             &Reply($client,\$result,$userinput);
                   6702:         } else {
                   6703:             &Reply($client,"error\n", $userinput);
                   6704:         }
                   6705:     } else {
                   6706:         &Failure($client,"unknown_cmd\n",$userinput);
                   6707:     }
                   6708: }
1.397     raeburn  6709: &register_handler("instemailrules",\&get_institutional_selfcreate_rules,0,1,0);
1.396     raeburn  6710: 
1.381     raeburn  6711: 
                   6712: sub institutional_username_check {
                   6713:     my ($cmd, $tail, $client)   = @_;
                   6714:     my $userinput               = "$cmd:$tail";
                   6715:     my %rulecheck;
                   6716:     my $outcome;
                   6717:     my ($udom,$uname,@rules) = split(/:/,$tail);
                   6718:     $udom = &unescape($udom);
                   6719:     $uname = &unescape($uname);
                   6720:     @rules = map {&unescape($_);} (@rules);
                   6721:     eval {
                   6722:         local($SIG{__DIE__})='DEFAULT';
                   6723:         $outcome = &localenroll::username_check($udom,$uname,\@rules,\%rulecheck);
                   6724:     };
                   6725:     if (!$@) {
                   6726:         if ($outcome eq 'ok') {
                   6727:             my $result='';
                   6728:             foreach my $key (keys(%rulecheck)) {
                   6729:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6730:             }
1.387     albertel 6731:             &Reply($client,\$result,$userinput);
1.381     raeburn  6732:         } else {
                   6733:             &Reply($client,"error\n", $userinput);
                   6734:         }
                   6735:     } else {
                   6736:         &Failure($client,"unknown_cmd\n",$userinput);
                   6737:     }
                   6738: }
                   6739: &register_handler("instrulecheck",\&institutional_username_check,0,1,0);
                   6740: 
1.389     raeburn  6741: sub institutional_id_check {
                   6742:     my ($cmd, $tail, $client)   = @_;
                   6743:     my $userinput               = "$cmd:$tail";
                   6744:     my %rulecheck;
                   6745:     my $outcome;
                   6746:     my ($udom,$id,@rules) = split(/:/,$tail);
                   6747:     $udom = &unescape($udom);
                   6748:     $id = &unescape($id);
                   6749:     @rules = map {&unescape($_);} (@rules);
                   6750:     eval {
                   6751:         local($SIG{__DIE__})='DEFAULT';
                   6752:         $outcome = &localenroll::id_check($udom,$id,\@rules,\%rulecheck);
                   6753:     };
                   6754:     if (!$@) {
                   6755:         if ($outcome eq 'ok') {
                   6756:             my $result='';
                   6757:             foreach my $key (keys(%rulecheck)) {
                   6758:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6759:             }
                   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("instidrulecheck",\&institutional_id_check,0,1,0);
1.345     raeburn  6769: 
1.397     raeburn  6770: sub institutional_selfcreate_check {
1.396     raeburn  6771:     my ($cmd, $tail, $client)   = @_;
                   6772:     my $userinput               = "$cmd:$tail";
                   6773:     my %rulecheck;
                   6774:     my $outcome;
                   6775:     my ($udom,$email,@rules) = split(/:/,$tail);
                   6776:     $udom = &unescape($udom);
                   6777:     $email = &unescape($email);
                   6778:     @rules = map {&unescape($_);} (@rules);
                   6779:     eval {
                   6780:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  6781:         $outcome = &localenroll::selfcreate_check($udom,$email,\@rules,\%rulecheck);
1.396     raeburn  6782:     };
                   6783:     if (!$@) {
                   6784:         if ($outcome eq 'ok') {
                   6785:             my $result='';
                   6786:             foreach my $key (keys(%rulecheck)) {
                   6787:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6788:             }
                   6789:             &Reply($client,\$result,$userinput);
                   6790:         } else {
                   6791:             &Reply($client,"error\n", $userinput);
                   6792:         }
                   6793:     } else {
                   6794:         &Failure($client,"unknown_cmd\n",$userinput);
                   6795:     }
                   6796: }
1.397     raeburn  6797: &register_handler("instselfcreatecheck",\&institutional_selfcreate_check,0,1,0);
1.396     raeburn  6798: 
1.317     raeburn  6799: # Get domain specific conditions for import of student photographs to a course
                   6800: #
                   6801: # Retrieves information from photo_permission subroutine in localenroll.
                   6802: # Returns outcome (ok) if no processing errors, and whether course owner is 
                   6803: # required to accept conditions of use (yes/no).
                   6804: #
                   6805: #    
                   6806: sub photo_permission_handler {
                   6807:     my ($cmd, $tail, $client)   = @_;
                   6808:     my $userinput               = "$cmd:$tail";
                   6809:     my $cdom = $tail;
                   6810:     my ($perm_reqd,$conditions);
1.320     albertel 6811:     my $outcome;
                   6812:     eval {
                   6813: 	local($SIG{__DIE__})='DEFAULT';
                   6814: 	$outcome = &localenroll::photo_permission($cdom,\$perm_reqd,
                   6815: 						  \$conditions);
                   6816:     };
                   6817:     if (!$@) {
                   6818: 	&Reply($client, &escape($outcome.':'.$perm_reqd.':'. $conditions)."\n",
                   6819: 	       $userinput);
                   6820:     } else {
                   6821: 	&Failure($client,"unknown_cmd\n",$userinput);
                   6822:     }
                   6823:     return 1;
1.317     raeburn  6824: }
                   6825: &register_handler("autophotopermission",\&photo_permission_handler,0,1,0);
                   6826: 
                   6827: #
                   6828: # Checks if student photo is available for a user in the domain, in the user's
                   6829: # directory (in /userfiles/internal/studentphoto.jpg).
                   6830: # Uses localstudentphoto:fetch() to ensure there is an up to date copy of
                   6831: # the student's photo.   
                   6832: 
                   6833: sub photo_check_handler {
                   6834:     my ($cmd, $tail, $client)   = @_;
                   6835:     my $userinput               = "$cmd:$tail";
                   6836:     my ($udom,$uname,$pid) = split(/:/,$tail);
                   6837:     $udom = &unescape($udom);
                   6838:     $uname = &unescape($uname);
                   6839:     $pid = &unescape($pid);
                   6840:     my $path=&propath($udom,$uname).'/userfiles/internal/';
                   6841:     if (!-e $path) {
                   6842:         &mkpath($path);
                   6843:     }
                   6844:     my $response;
                   6845:     my $result = &localstudentphoto::fetch($udom,$uname,$pid,\$response);
                   6846:     $result .= ':'.$response;
                   6847:     &Reply($client, &escape($result)."\n",$userinput);
1.320     albertel 6848:     return 1;
1.317     raeburn  6849: }
                   6850: &register_handler("autophotocheck",\&photo_check_handler,0,1,0);
                   6851: 
                   6852: #
                   6853: # Retrieve information from localenroll about whether to provide a button     
                   6854: # for users who have enbled import of student photos to initiate an 
                   6855: # update of photo files for registered students. Also include 
                   6856: # comment to display alongside button.  
                   6857: 
                   6858: sub photo_choice_handler {
                   6859:     my ($cmd, $tail, $client) = @_;
                   6860:     my $userinput             = "$cmd:$tail";
                   6861:     my $cdom                  = &unescape($tail);
1.320     albertel 6862:     my ($update,$comment);
                   6863:     eval {
                   6864: 	local($SIG{__DIE__})='DEFAULT';
                   6865: 	($update,$comment)    = &localenroll::manager_photo_update($cdom);
                   6866:     };
                   6867:     if (!$@) {
                   6868: 	&Reply($client,&escape($update).':'.&escape($comment)."\n",$userinput);
                   6869:     } else {
                   6870: 	&Failure($client,"unknown_cmd\n",$userinput);
                   6871:     }
                   6872:     return 1;
1.317     raeburn  6873: }
                   6874: &register_handler("autophotochoice",\&photo_choice_handler,0,1,0);
                   6875: 
1.265     albertel 6876: #
                   6877: # Gets a student's photo to exist (in the correct image type) in the user's 
                   6878: # directory.
                   6879: # Formal Parameters:
                   6880: #    $cmd     - The command request that got us dispatched.
                   6881: #    $tail    - A colon separated set of words that will be split into:
                   6882: #               $domain - student's domain
                   6883: #               $uname  - student username
                   6884: #               $type   - image type desired
                   6885: #    $client  - The socket open on the client.
                   6886: # Returns:
                   6887: #    1 - continue processing.
1.317     raeburn  6888: 
1.265     albertel 6889: sub student_photo_handler {
                   6890:     my ($cmd, $tail, $client) = @_;
1.317     raeburn  6891:     my ($domain,$uname,$ext,$type) = split(/:/, $tail);
1.265     albertel 6892: 
1.317     raeburn  6893:     my $path=&propath($domain,$uname). '/userfiles/internal/';
                   6894:     my $filename = 'studentphoto.'.$ext;
                   6895:     if ($type eq 'thumbnail') {
                   6896:         $filename = 'studentphoto_tn.'.$ext;
                   6897:     }
                   6898:     if (-e $path.$filename) {
1.265     albertel 6899: 	&Reply($client,"ok\n","$cmd:$tail");
                   6900: 	return 1;
                   6901:     }
                   6902:     &mkpath($path);
1.317     raeburn  6903:     my $file;
                   6904:     if ($type eq 'thumbnail') {
1.320     albertel 6905: 	eval {
                   6906: 	    local($SIG{__DIE__})='DEFAULT';
                   6907: 	    $file=&localstudentphoto::fetch_thumbnail($domain,$uname);
                   6908: 	};
1.317     raeburn  6909:     } else {
                   6910:         $file=&localstudentphoto::fetch($domain,$uname);
                   6911:     }
1.265     albertel 6912:     if (!$file) {
                   6913: 	&Failure($client,"unavailable\n","$cmd:$tail");
                   6914: 	return 1;
                   6915:     }
1.317     raeburn  6916:     if (!-e $path.$filename) { &convert_photo($file,$path.$filename); }
                   6917:     if (-e $path.$filename) {
1.265     albertel 6918: 	&Reply($client,"ok\n","$cmd:$tail");
                   6919: 	return 1;
                   6920:     }
                   6921:     &Failure($client,"unable_to_convert\n","$cmd:$tail");
                   6922:     return 1;
                   6923: }
                   6924: &register_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
1.246     foxr     6925: 
1.361     raeburn  6926: sub inst_usertypes_handler {
                   6927:     my ($cmd, $domain, $client) = @_;
                   6928:     my $res;
                   6929:     my $userinput = $cmd.":".$domain; # For logging purposes.
1.370     albertel 6930:     my (%typeshash,@order,$result);
                   6931:     eval {
                   6932: 	local($SIG{__DIE__})='DEFAULT';
                   6933: 	$result=&localenroll::inst_usertypes($domain,\%typeshash,\@order);
                   6934:     };
                   6935:     if ($result eq 'ok') {
1.361     raeburn  6936:         if (keys(%typeshash) > 0) {
                   6937:             foreach my $key (keys(%typeshash)) {
                   6938:                 $res.=&escape($key).'='.&escape($typeshash{$key}).'&';
                   6939:             }
                   6940:         }
                   6941:         $res=~s/\&$//;
                   6942:         $res .= ':';
                   6943:         if (@order > 0) {
                   6944:             foreach my $item (@order) {
                   6945:                 $res .= &escape($item).'&';
                   6946:             }
                   6947:         }
                   6948:         $res=~s/\&$//;
                   6949:     }
1.387     albertel 6950:     &Reply($client, \$res, $userinput);
1.361     raeburn  6951:     return 1;
                   6952: }
                   6953: &register_handler("inst_usertypes", \&inst_usertypes_handler, 0, 1, 0);
                   6954: 
1.264     albertel 6955: # mkpath makes all directories for a file, expects an absolute path with a
                   6956: # file or a trailing / if just a dir is passed
                   6957: # returns 1 on success 0 on failure
                   6958: sub mkpath {
                   6959:     my ($file)=@_;
                   6960:     my @parts=split(/\//,$file,-1);
                   6961:     my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
                   6962:     for (my $i=3;$i<= ($#parts-1);$i++) {
1.265     albertel 6963: 	$now.='/'.$parts[$i]; 
1.264     albertel 6964: 	if (!-e $now) {
                   6965: 	    if  (!mkdir($now,0770)) { return 0; }
                   6966: 	}
                   6967:     }
                   6968:     return 1;
                   6969: }
                   6970: 
1.207     foxr     6971: #---------------------------------------------------------------
                   6972: #
                   6973: #   Getting, decoding and dispatching requests:
                   6974: #
                   6975: #
                   6976: #   Get a Request:
                   6977: #   Gets a Request message from the client.  The transaction
                   6978: #   is defined as a 'line' of text.  We remove the new line
                   6979: #   from the text line.  
1.226     foxr     6980: #
1.211     albertel 6981: sub get_request {
1.207     foxr     6982:     my $input = <$client>;
                   6983:     chomp($input);
1.226     foxr     6984: 
1.234     foxr     6985:     &Debug("get_request: Request = $input\n");
1.207     foxr     6986: 
                   6987:     &status('Processing '.$clientname.':'.$input);
                   6988: 
                   6989:     return $input;
                   6990: }
1.212     foxr     6991: #---------------------------------------------------------------
                   6992: #
                   6993: #  Process a request.  This sub should shrink as each action
                   6994: #  gets farmed out into a separat sub that is registered 
                   6995: #  with the dispatch hash.  
                   6996: #
                   6997: # Parameters:
                   6998: #    user_input   - The request received from the client (lonc).
1.525     raeburn  6999: #
1.212     foxr     7000: # Returns:
                   7001: #    true to keep processing, false if caller should exit.
                   7002: #
                   7003: sub process_request {
1.525     raeburn  7004:     my ($userinput) = @_; # Easier for now to break style than to
                   7005:                           # fix all the userinput -> user_input.
1.212     foxr     7006:     my $wasenc    = 0;		# True if request was encrypted.
                   7007: # ------------------------------------------------------------ See if encrypted
1.322     albertel 7008:     # for command
                   7009:     # sethost:<server>
                   7010:     # <command>:<args>
                   7011:     #   we just send it to the processor
                   7012:     # for
                   7013:     # sethost:<server>:<command>:<args>
                   7014:     #  we do the implict set host and then do the command
                   7015:     if ($userinput =~ /^sethost:/) {
                   7016: 	(my $cmd,my $newid,$userinput) = split(':',$userinput,3);
                   7017: 	if (defined($userinput)) {
                   7018: 	    &sethost("$cmd:$newid");
                   7019: 	} else {
                   7020: 	    $userinput = "$cmd:$newid";
                   7021: 	}
                   7022:     }
                   7023: 
1.212     foxr     7024:     if ($userinput =~ /^enc/) {
                   7025: 	$userinput = decipher($userinput);
                   7026: 	$wasenc=1;
                   7027: 	if(!$userinput) {	# Cipher not defined.
1.251     foxr     7028: 	    &Failure($client, "error: Encrypted data without negotated key\n");
1.212     foxr     7029: 	    return 0;
                   7030: 	}
                   7031:     }
                   7032:     Debug("process_request: $userinput\n");
                   7033:     
1.213     foxr     7034:     #  
                   7035:     #   The 'correct way' to add a command to lond is now to
                   7036:     #   write a sub to execute it and Add it to the command dispatch
                   7037:     #   hash via a call to register_handler..  The comments to that
                   7038:     #   sub should give you enough to go on to show how to do this
                   7039:     #   along with the examples that are building up as this code
                   7040:     #   is getting refactored.   Until all branches of the
                   7041:     #   if/elseif monster below have been factored out into
                   7042:     #   separate procesor subs, if the dispatch hash is missing
                   7043:     #   the command keyword, we will fall through to the remainder
                   7044:     #   of the if/else chain below in order to keep this thing in 
                   7045:     #   working order throughout the transmogrification.
                   7046: 
                   7047:     my ($command, $tail) = split(/:/, $userinput, 2);
                   7048:     chomp($command);
                   7049:     chomp($tail);
                   7050:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
1.214     foxr     7051:     $command =~ s/(\r)//;	# And this too for parameterless commands.
                   7052:     if(!$tail) {
                   7053: 	$tail ="";		# defined but blank.
                   7054:     }
1.213     foxr     7055: 
                   7056:     &Debug("Command received: $command, encoded = $wasenc");
                   7057: 
                   7058:     if(defined $Dispatcher{$command}) {
                   7059: 
                   7060: 	my $dispatch_info = $Dispatcher{$command};
                   7061: 	my $handler       = $$dispatch_info[0];
                   7062: 	my $need_encode   = $$dispatch_info[1];
                   7063: 	my $client_types  = $$dispatch_info[2];
                   7064: 	Debug("Matched dispatch hash: mustencode: $need_encode "
                   7065: 	      ."ClientType $client_types");
                   7066:       
                   7067: 	#  Validate the request:
                   7068:       
                   7069: 	my $ok = 1;
                   7070: 	my $requesterprivs = 0;
                   7071: 	if(&isClient()) {
                   7072: 	    $requesterprivs |= $CLIENT_OK;
                   7073: 	}
                   7074: 	if(&isManager()) {
                   7075: 	    $requesterprivs |= $MANAGER_OK;
                   7076: 	}
                   7077: 	if($need_encode && (!$wasenc)) {
                   7078: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
                   7079: 	    $ok = 0;
                   7080: 	}
                   7081: 	if(($client_types & $requesterprivs) == 0) {
                   7082: 	    Debug("Client not privileged to do this operation");
                   7083: 	    $ok = 0;
                   7084: 	}
1.525     raeburn  7085:         if ($ok) {
1.535     raeburn  7086:             my $realcommand = $command;
                   7087:             if ($command eq 'querysend') {
                   7088:                 my ($query,$rest)=split(/\:/,$tail,2);
                   7089:                 $query=~s/\n*$//g;
                   7090:                 my @possqueries = 
                   7091:                     qw(userlog courselog fetchenrollment institutionalphotos usersearch instdirsearch getinstuser getmultinstusers);
                   7092:                 if (grep(/^\Q$query\E$/,@possqueries)) {
                   7093:                     $command .= '_'.$query;
                   7094:                 } elsif ($query eq 'prepare activity log') {
                   7095:                     $command .= '_activitylog';
                   7096:                 }
                   7097:             }
1.525     raeburn  7098:             if (ref($trust{$command}) eq 'HASH') {
                   7099:                 my $donechecks;
                   7100:                 if ($trust{$command}{'anywhere'}) {
                   7101:                    $donechecks = 1;
                   7102:                 } elsif ($trust{$command}{'manageronly'}) {
                   7103:                     unless (&isManager()) {
                   7104:                         $ok = 0;
                   7105:                     }
                   7106:                     $donechecks = 1;
                   7107:                 } elsif ($trust{$command}{'institutiononly'}) {
                   7108:                     unless ($clientsameinst) {
                   7109:                         $ok = 0;
                   7110:                     }
                   7111:                     $donechecks = 1;
                   7112:                 } elsif ($clientsameinst) {
                   7113:                     $donechecks = 1;
                   7114:                 }
                   7115:                 unless ($donechecks) {
                   7116:                     foreach my $rule (keys(%{$trust{$command}})) {
                   7117:                         next if ($rule eq 'remote');
                   7118:                         if ($trust{$command}{$rule}) {
                   7119:                             if ($clientprohibited{$rule}) {
                   7120:                                 $ok = 0;
                   7121:                             } else {
                   7122:                                 $ok = 1;
                   7123:                                 $donechecks = 1;
                   7124:                                 last;
                   7125:                             }
                   7126:                         }
                   7127:                     }
                   7128:                 }
                   7129:                 unless ($donechecks) {
                   7130:                     if ($trust{$command}{'remote'}) {
                   7131:                         if ($clientremoteok) {
                   7132:                             $ok = 1;
                   7133:                         } else {
                   7134:                             $ok = 0;
                   7135:                         } 
                   7136:                     }
                   7137:                 }
                   7138:             }
1.535     raeburn  7139:             $command = $realcommand;
1.525     raeburn  7140:         }
1.213     foxr     7141: 
                   7142: 	if($ok) {
                   7143: 	    Debug("Dispatching to handler $command $tail");
                   7144: 	    my $keep_going = &$handler($command, $tail, $client);
                   7145: 	    return $keep_going;
                   7146: 	} else {
                   7147: 	    Debug("Refusing to dispatch because client did not match requirements");
                   7148: 	    Failure($client, "refused\n", $userinput);
                   7149: 	    return 1;
                   7150: 	}
1.525     raeburn  7151:     }
1.213     foxr     7152: 
1.262     foxr     7153:     print $client "unknown_cmd\n";
1.212     foxr     7154: # -------------------------------------------------------------------- complete
                   7155:     Debug("process_request - returning 1");
                   7156:     return 1;
                   7157: }
1.207     foxr     7158: #
                   7159: #   Decipher encoded traffic
                   7160: #  Parameters:
                   7161: #     input      - Encoded data.
                   7162: #  Returns:
                   7163: #     Decoded data or undef if encryption key was not yet negotiated.
                   7164: #  Implicit input:
                   7165: #     cipher  - This global holds the negotiated encryption key.
                   7166: #
1.211     albertel 7167: sub decipher {
1.207     foxr     7168:     my ($input)  = @_;
                   7169:     my $output = '';
1.212     foxr     7170:     
                   7171:     
1.207     foxr     7172:     if($cipher) {
                   7173: 	my($enc, $enclength, $encinput) = split(/:/, $input);
                   7174: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
                   7175: 	    $output .= 
                   7176: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
                   7177: 	}
                   7178: 	return substr($output, 0, $enclength);
                   7179:     } else {
                   7180: 	return undef;
                   7181:     }
                   7182: }
                   7183: 
                   7184: #
                   7185: #   Register a command processor.  This function is invoked to register a sub
                   7186: #   to process a request.  Once registered, the ProcessRequest sub can automatically
                   7187: #   dispatch requests to an appropriate sub, and do the top level validity checking
                   7188: #   as well:
                   7189: #    - Is the keyword recognized.
                   7190: #    - Is the proper client type attempting the request.
                   7191: #    - Is the request encrypted if it has to be.
                   7192: #   Parameters:
                   7193: #    $request_name         - Name of the request being registered.
                   7194: #                           This is the command request that will match
                   7195: #                           against the hash keywords to lookup the information
                   7196: #                           associated with the dispatch information.
                   7197: #    $procedure           - Reference to a sub to call to process the request.
                   7198: #                           All subs get called as follows:
                   7199: #                             Procedure($cmd, $tail, $replyfd, $key)
                   7200: #                             $cmd    - the actual keyword that invoked us.
                   7201: #                             $tail   - the tail of the request that invoked us.
                   7202: #                             $replyfd- File descriptor connected to the client
                   7203: #    $must_encode          - True if the request must be encoded to be good.
                   7204: #    $client_ok            - True if it's ok for a client to request this.
                   7205: #    $manager_ok           - True if it's ok for a manager to request this.
                   7206: # Side effects:
                   7207: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
                   7208: #      - On failure, the program will die as it's a bad internal bug to try to 
                   7209: #        register a duplicate command handler.
                   7210: #
1.211     albertel 7211: sub register_handler {
1.212     foxr     7212:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
1.207     foxr     7213: 
                   7214:     #  Don't allow duplication#
                   7215:    
                   7216:     if (defined $Dispatcher{$request_name}) {
                   7217: 	die "Attempting to define a duplicate request handler for $request_name\n";
                   7218:     }
                   7219:     #   Build the client type mask:
                   7220:     
                   7221:     my $client_type_mask = 0;
                   7222:     if($client_ok) {
                   7223: 	$client_type_mask  |= $CLIENT_OK;
                   7224:     }
                   7225:     if($manager_ok) {
                   7226: 	$client_type_mask  |= $MANAGER_OK;
                   7227:     }
                   7228:    
                   7229:     #  Enter the hash:
                   7230:       
                   7231:     my @entry = ($procedure, $must_encode, $client_type_mask);
                   7232:    
                   7233:     $Dispatcher{$request_name} = \@entry;
                   7234:    
                   7235: }
                   7236: 
                   7237: 
                   7238: #------------------------------------------------------------------
                   7239: 
                   7240: 
                   7241: 
                   7242: 
1.141     foxr     7243: #
1.96      foxr     7244: #  Convert an error return code from lcpasswd to a string value.
                   7245: #
                   7246: sub lcpasswdstrerror {
                   7247:     my $ErrorCode = shift;
1.97      foxr     7248:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96      foxr     7249: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
                   7250:     } else {
1.98      foxr     7251: 	return $passwderrors[$ErrorCode];
1.96      foxr     7252:     }
                   7253: }
                   7254: 
1.23      harris41 7255: # grabs exception and records it to log before exiting
                   7256: sub catchexception {
1.27      albertel 7257:     my ($error)=@_;
1.25      www      7258:     $SIG{'QUIT'}='DEFAULT';
                   7259:     $SIG{__DIE__}='DEFAULT';
1.165     albertel 7260:     &status("Catching exception");
1.190     albertel 7261:     &logthis("<font color='red'>CRITICAL: "
1.373     albertel 7262:      ."ABNORMAL EXIT. Child $$ for server ".$perlvar{'lonHostID'}." died through "
1.27      albertel 7263:      ."a crash with this error msg->[$error]</font>");
1.57      www      7264:     &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27      albertel 7265:     if ($client) { print $client "error: $error\n"; }
1.59      www      7266:     $server->close();
1.27      albertel 7267:     die($error);
1.23      harris41 7268: }
1.63      www      7269: sub timeout {
1.165     albertel 7270:     &status("Handling Timeout");
1.190     albertel 7271:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
1.63      www      7272:     &catchexception('Timeout');
                   7273: }
1.22      harris41 7274: # -------------------------------- Set signal handlers to record abnormal exits
                   7275: 
1.226     foxr     7276: 
1.22      harris41 7277: $SIG{'QUIT'}=\&catchexception;
                   7278: $SIG{__DIE__}=\&catchexception;
                   7279: 
1.81      matthew  7280: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95      harris41 7281: &status("Read loncapa.conf and loncapa_apache.conf");
                   7282: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141     foxr     7283: %perlvar=%{$perlvarref};
1.80      harris41 7284: undef $perlvarref;
1.19      www      7285: 
1.35      harris41 7286: # ----------------------------- Make sure this process is running from user=www
                   7287: my $wwwid=getpwnam('www');
                   7288: if ($wwwid!=$<) {
1.134     albertel 7289:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   7290:    my $subj="LON: $currenthostid User ID mismatch";
1.550     raeburn  7291:    system("echo 'User ID mismatch.  lond must be run as user www.' |".
                   7292:           " mail -s '$subj' $emailto > /dev/null");
1.35      harris41 7293:    exit 1;
                   7294: }
                   7295: 
1.19      www      7296: # --------------------------------------------- Check if other instance running
                   7297: 
                   7298: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
                   7299: 
                   7300: if (-e $pidfile) {
                   7301:    my $lfh=IO::File->new("$pidfile");
                   7302:    my $pide=<$lfh>;
                   7303:    chomp($pide);
1.29      harris41 7304:    if (kill 0 => $pide) { die "already running"; }
1.19      www      7305: }
1.1       albertel 7306: 
                   7307: # ------------------------------------------------------------- Read hosts file
                   7308: 
                   7309: 
                   7310: 
                   7311: # establish SERVER socket, bind and listen.
                   7312: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
                   7313:                                 Type      => SOCK_STREAM,
                   7314:                                 Proto     => 'tcp',
1.469     foxr     7315:                                 ReuseAddr     => 1,
1.1       albertel 7316:                                 Listen    => 10 )
1.29      harris41 7317:   or die "making socket: $@\n";
1.1       albertel 7318: 
                   7319: # --------------------------------------------------------- Do global variables
                   7320: 
                   7321: # global variables
                   7322: 
1.134     albertel 7323: my %children               = ();       # keys are current child process IDs
1.1       albertel 7324: 
                   7325: sub REAPER {                        # takes care of dead children
                   7326:     $SIG{CHLD} = \&REAPER;
1.165     albertel 7327:     &status("Handling child death");
1.178     foxr     7328:     my $pid;
                   7329:     do {
                   7330: 	$pid = waitpid(-1,&WNOHANG());
                   7331: 	if (defined($children{$pid})) {
                   7332: 	    &logthis("Child $pid died");
                   7333: 	    delete($children{$pid});
1.183     albertel 7334: 	} elsif ($pid > 0) {
1.178     foxr     7335: 	    &logthis("Unknown Child $pid died");
                   7336: 	}
                   7337:     } while ( $pid > 0 );
                   7338:     foreach my $child (keys(%children)) {
                   7339: 	$pid = waitpid($child,&WNOHANG());
                   7340: 	if ($pid > 0) {
                   7341: 	    &logthis("Child $child - $pid looks like we missed it's death");
                   7342: 	    delete($children{$pid});
                   7343: 	}
1.176     albertel 7344:     }
1.165     albertel 7345:     &status("Finished Handling child death");
1.1       albertel 7346: }
                   7347: 
                   7348: sub HUNTSMAN {                      # signal handler for SIGINT
1.165     albertel 7349:     &status("Killing children (INT)");
1.1       albertel 7350:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
                   7351:     kill 'INT' => keys %children;
1.59      www      7352:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1       albertel 7353:     my $execdir=$perlvar{'lonDaemons'};
                   7354:     unlink("$execdir/logs/lond.pid");
1.190     albertel 7355:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.165     albertel 7356:     &status("Done killing children");
1.1       albertel 7357:     exit;                           # clean up with dignity
                   7358: }
                   7359: 
                   7360: sub HUPSMAN {                      # signal handler for SIGHUP
                   7361:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
1.165     albertel 7362:     &status("Killing children for restart (HUP)");
1.1       albertel 7363:     kill 'INT' => keys %children;
1.59      www      7364:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.190     albertel 7365:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.134     albertel 7366:     my $execdir=$perlvar{'lonDaemons'};
1.30      harris41 7367:     unlink("$execdir/logs/lond.pid");
1.165     albertel 7368:     &status("Restarting self (HUP)");
1.1       albertel 7369:     exec("$execdir/lond");         # here we go again
                   7370: }
                   7371: 
1.144     foxr     7372: #
1.148     foxr     7373: #  Reload the Apache daemon's state.
1.150     foxr     7374: #  This is done by invoking /home/httpd/perl/apachereload
                   7375: #  a setuid perl script that can be root for us to do this job.
1.148     foxr     7376: #
                   7377: sub ReloadApache {
1.473     raeburn  7378: # --------------------------- Handle case of another apachereload process (locking)
1.474     raeburn  7379:     if (&LONCAPA::try_to_lock('/tmp/lock_apachereload')) {
                   7380:         my $execdir = $perlvar{'lonDaemons'};
                   7381:         my $script  = $execdir."/apachereload";
                   7382:         system($script);
                   7383:         unlink('/tmp/lock_apachereload'); #  Remove the lock file.
                   7384:     }
1.148     foxr     7385: }
                   7386: 
                   7387: #
1.144     foxr     7388: #   Called in response to a USR2 signal.
                   7389: #   - Reread hosts.tab
                   7390: #   - All children connected to hosts that were removed from hosts.tab
                   7391: #     are killed via SIGINT
                   7392: #   - All children connected to previously existing hosts are sent SIGUSR1
                   7393: #   - Our internal hosts hash is updated to reflect the new contents of
                   7394: #     hosts.tab causing connections from hosts added to hosts.tab to
                   7395: #     now be honored.
                   7396: #
                   7397: sub UpdateHosts {
1.165     albertel 7398:     &status("Reload hosts.tab");
1.147     foxr     7399:     logthis('<font color="blue"> Updating connections </font>');
1.148     foxr     7400:     #
                   7401:     #  The %children hash has the set of IP's we currently have children
                   7402:     #  on.  These need to be matched against records in the hosts.tab
                   7403:     #  Any ip's no longer in the table get killed off they correspond to
                   7404:     #  either dropped or changed hosts.  Note that the re-read of the table
                   7405:     #  will take care of new and changed hosts as connections come into being.
                   7406: 
1.371     albertel 7407:     &Apache::lonnet::reset_hosts_info();
1.532     raeburn  7408:     my %active;
1.148     foxr     7409: 
1.368     albertel 7410:     foreach my $child (keys(%children)) {
1.148     foxr     7411: 	my $childip = $children{$child};
1.374     albertel 7412: 	if ($childip ne '127.0.0.1'
                   7413: 	    && !defined(&Apache::lonnet::get_hosts_from_ip($childip))) {
1.149     foxr     7414: 	    logthis('<font color="blue"> UpdateHosts killing child '
                   7415: 		    ." $child for ip $childip </font>");
1.148     foxr     7416: 	    kill('INT', $child);
1.149     foxr     7417: 	} else {
1.532     raeburn  7418:             $active{$child} = $childip;
1.149     foxr     7419: 	    logthis('<font color="green"> keeping child for ip '
                   7420: 		    ." $childip (pid=$child) </font>");
1.148     foxr     7421: 	}
                   7422:     }
1.532     raeburn  7423: 
                   7424:     my %oldconf = %secureconf;
                   7425:     my %connchange;
1.555     raeburn  7426:     if (lonssl::Read_Connect_Config(\%secureconf,\%perlvar,\%crlchecked) eq 'ok') {
1.545     raeburn  7427:         logthis('<font color="blue"> Reloaded SSL connection rules and cleared CRL checking history </font>');
1.532     raeburn  7428:     } else {
1.545     raeburn  7429:         logthis('<font color="yellow"> Failed to reload SSL connection rules and clear CRL checking history </font>');
1.532     raeburn  7430:     }
                   7431:     if ((ref($oldconf{'connfrom'}) eq 'HASH') && (ref($secureconf{'connfrom'}) eq 'HASH')) {
                   7432:         foreach my $type ('dom','intdom','other') {
                   7433:             if ((($oldconf{'connfrom'}{$type} eq 'no') && ($secureconf{'connfrom'}{$type} eq 'req')) ||
                   7434:                 (($oldconf{'connfrom'}{$type} eq 'req') && ($secureconf{'connfrom'}{$type} eq 'no'))) {
                   7435:                 $connchange{$type} = 1;
                   7436:             }
                   7437:         }
                   7438:     }
                   7439:     if (keys(%connchange)) {
                   7440:         foreach my $child (keys(%active)) {
                   7441:             my $childip = $active{$child};
                   7442:             if ($childip ne '127.0.0.1') {
                   7443:                 my $childhostname  = gethostbyaddr(Socket::inet_aton($childip),AF_INET);
                   7444:                 if ($childhostname ne '') {
                   7445:                     my $childlonhost = &Apache::lonnet::get_server_homeID($childhostname);
                   7446:                     my ($samedom,$sameinst) = &set_client_info($childlonhost);
                   7447:                     if ($samedom) {
                   7448:                         if ($connchange{'dom'}) {
                   7449:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7450:                                    ." $child for ip $childip </font>");
                   7451:                             kill('INT', $child);
                   7452:                         }
                   7453:                     } elsif ($sameinst) {
                   7454:                         if ($connchange{'intdom'}) {
                   7455:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7456:                                    ." $child for ip $childip </font>");
                   7457:                            kill('INT', $child);
                   7458:                         }
                   7459:                     } else {
                   7460:                         if ($connchange{'other'}) {
                   7461:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7462:                                    ." $child for ip $childip </font>");
                   7463:                             kill('INT', $child);
                   7464:                         }
                   7465:                     }
                   7466:                 }
                   7467:             }
                   7468:         }
                   7469:     }
1.148     foxr     7470:     ReloadApache;
1.165     albertel 7471:     &status("Finished reloading hosts.tab");
1.144     foxr     7472: }
                   7473: 
1.57      www      7474: sub checkchildren {
1.165     albertel 7475:     &status("Checking on the children (sending signals)");
1.57      www      7476:     &initnewstatus();
                   7477:     &logstatus();
                   7478:     &logthis('Going to check on the children');
1.134     albertel 7479:     my $docdir=$perlvar{'lonDocRoot'};
1.61      harris41 7480:     foreach (sort keys %children) {
1.221     albertel 7481: 	#sleep 1;
1.57      www      7482:         unless (kill 'USR1' => $_) {
                   7483: 	    &logthis ('Child '.$_.' is dead');
                   7484:             &logstatus($$.' is dead');
1.221     albertel 7485: 	    delete($children{$_});
1.57      www      7486:         } 
1.61      harris41 7487:     }
1.63      www      7488:     sleep 5;
1.212     foxr     7489:     $SIG{ALRM} = sub { Debug("timeout"); 
                   7490: 		       die "timeout";  };
1.113     albertel 7491:     $SIG{__DIE__} = 'DEFAULT';
1.165     albertel 7492:     &status("Checking on the children (waiting for reports)");
1.63      www      7493:     foreach (sort keys %children) {
                   7494:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113     albertel 7495:           eval {
                   7496:             alarm(300);
1.63      www      7497: 	    &logthis('Child '.$_.' did not respond');
1.67      albertel 7498: 	    kill 9 => $_;
1.131     albertel 7499: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   7500: 	    #$subj="LON: $currenthostid killed lond process $_";
                   7501: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
                   7502: 	    #$execdir=$perlvar{'lonDaemons'};
                   7503: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.221     albertel 7504: 	    delete($children{$_});
1.113     albertel 7505: 	    alarm(0);
                   7506: 	  }
1.63      www      7507:         }
                   7508:     }
1.113     albertel 7509:     $SIG{ALRM} = 'DEFAULT';
1.155     albertel 7510:     $SIG{__DIE__} = \&catchexception;
1.165     albertel 7511:     &status("Finished checking children");
1.221     albertel 7512:     &logthis('Finished Checking children');
1.57      www      7513: }
                   7514: 
1.1       albertel 7515: # --------------------------------------------------------------------- Logging
                   7516: 
                   7517: sub logthis {
                   7518:     my $message=shift;
                   7519:     my $execdir=$perlvar{'lonDaemons'};
                   7520:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
                   7521:     my $now=time;
                   7522:     my $local=localtime($now);
1.58      www      7523:     $lastlog=$local.': '.$message;
1.1       albertel 7524:     print $fh "$local ($$): $message\n";
                   7525: }
                   7526: 
1.77      foxr     7527: # ------------------------- Conditional log if $DEBUG true.
                   7528: sub Debug {
                   7529:     my $message = shift;
                   7530:     if($DEBUG) {
                   7531: 	&logthis($message);
                   7532:     }
                   7533: }
1.161     foxr     7534: 
                   7535: #
                   7536: #   Sub to do replies to client.. this gives a hook for some
                   7537: #   debug tracing too:
                   7538: #  Parameters:
                   7539: #     fd      - File open on client.
                   7540: #     reply   - Text to send to client.
                   7541: #     request - Original request from client.
                   7542: #
1.490     droeschl 7543: #NOTE $reply must be terminated by exactly *one* \n. If $reply is a reference
                   7544: #this is done automatically ($$reply must not contain any \n in this case). 
                   7545: #If $reply is a string the caller has to ensure this.
1.161     foxr     7546: sub Reply {
1.192     foxr     7547:     my ($fd, $reply, $request) = @_;
1.387     albertel 7548:     if (ref($reply)) {
                   7549: 	print $fd $$reply;
                   7550: 	print $fd "\n";
                   7551: 	if ($DEBUG) { Debug("Request was $request  Reply was $$reply"); }
                   7552:     } else {
                   7553: 	print $fd $reply;
                   7554: 	if ($DEBUG) { Debug("Request was $request  Reply was $reply"); }
                   7555:     }
1.212     foxr     7556:     $Transactions++;
                   7557: }
                   7558: 
                   7559: 
                   7560: #
                   7561: #    Sub to report a failure.
                   7562: #    This function:
                   7563: #     -   Increments the failure statistic counters.
                   7564: #     -   Invokes Reply to send the error message to the client.
                   7565: # Parameters:
                   7566: #    fd       - File descriptor open on the client
                   7567: #    reply    - Reply text to emit.
                   7568: #    request  - The original request message (used by Reply
                   7569: #               to debug if that's enabled.
                   7570: # Implicit outputs:
                   7571: #    $Failures- The number of failures is incremented.
                   7572: #    Reply (invoked here) sends a message to the 
                   7573: #    client:
                   7574: #
                   7575: sub Failure {
                   7576:     my $fd      = shift;
                   7577:     my $reply   = shift;
                   7578:     my $request = shift;
                   7579:    
                   7580:     $Failures++;
                   7581:     Reply($fd, $reply, $request);      # That's simple eh?
1.161     foxr     7582: }
1.57      www      7583: # ------------------------------------------------------------------ Log status
                   7584: 
                   7585: sub logstatus {
1.178     foxr     7586:     &status("Doing logging");
                   7587:     my $docdir=$perlvar{'lonDocRoot'};
                   7588:     {
                   7589: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
1.200     matthew  7590:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
1.178     foxr     7591:         $fh->close();
                   7592:     }
1.221     albertel 7593:     &status("Finished $$.txt");
                   7594:     {
                   7595: 	open(LOG,">>$docdir/lon-status/londstatus.txt");
                   7596: 	flock(LOG,LOCK_EX);
                   7597: 	print LOG $$."\t".$clientname."\t".$currenthostid."\t"
                   7598: 	    .$status."\t".$lastlog."\t $keymode\n";
1.275     albertel 7599: 	flock(LOG,LOCK_UN);
1.221     albertel 7600: 	close(LOG);
                   7601:     }
1.178     foxr     7602:     &status("Finished logging");
1.57      www      7603: }
                   7604: 
                   7605: sub initnewstatus {
                   7606:     my $docdir=$perlvar{'lonDocRoot'};
                   7607:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
1.460     foxr     7608:     my $now=time();
1.57      www      7609:     my $local=localtime($now);
                   7610:     print $fh "LOND status $local - parent $$\n\n";
1.64      www      7611:     opendir(DIR,"$docdir/lon-status/londchld");
1.134     albertel 7612:     while (my $filename=readdir(DIR)) {
1.64      www      7613:         unlink("$docdir/lon-status/londchld/$filename");
                   7614:     }
                   7615:     closedir(DIR);
1.57      www      7616: }
                   7617: 
                   7618: # -------------------------------------------------------------- Status setting
                   7619: 
                   7620: sub status {
                   7621:     my $what=shift;
                   7622:     my $now=time;
                   7623:     my $local=localtime($now);
1.178     foxr     7624:     $status=$local.': '.$what;
                   7625:     $0='lond: '.$what.' '.$local;
1.57      www      7626: }
1.11      www      7627: 
1.13      www      7628: # -------------------------------------------------------------- Talk to lonsql
                   7629: 
1.234     foxr     7630: sub sql_reply {
1.12      harris41 7631:     my ($cmd)=@_;
1.234     foxr     7632:     my $answer=&sub_sql_reply($cmd);
                   7633:     if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
1.12      harris41 7634:     return $answer;
                   7635: }
                   7636: 
1.234     foxr     7637: sub sub_sql_reply {
1.12      harris41 7638:     my ($cmd)=@_;
                   7639:     my $unixsock="mysqlsock";
                   7640:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
                   7641:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                   7642:                                       Type    => SOCK_STREAM,
                   7643:                                       Timeout => 10)
                   7644:        or return "con_lost";
1.319     www      7645:     print $sclient "$cmd:$currentdomainid\n";
1.12      harris41 7646:     my $answer=<$sclient>;
                   7647:     chomp($answer);
                   7648:     if (!$answer) { $answer="con_lost"; }
                   7649:     return $answer;
                   7650: }
                   7651: 
1.1       albertel 7652: # --------------------------------------- Is this the home server of an author?
1.11      www      7653: 
1.1       albertel 7654: sub ishome {
                   7655:     my $author=shift;
                   7656:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   7657:     my ($udom,$uname)=split(/\//,$author);
                   7658:     my $proname=propath($udom,$uname);
                   7659:     if (-e $proname) {
                   7660: 	return 'owner';
                   7661:     } else {
                   7662:         return 'not_owner';
                   7663:     }
                   7664: }
                   7665: 
                   7666: # ======================================================= Continue main program
                   7667: # ---------------------------------------------------- Fork once and dissociate
                   7668: 
1.134     albertel 7669: my $fpid=fork;
1.1       albertel 7670: exit if $fpid;
1.29      harris41 7671: die "Couldn't fork: $!" unless defined ($fpid);
1.1       albertel 7672: 
1.29      harris41 7673: POSIX::setsid() or die "Can't start new session: $!";
1.1       albertel 7674: 
                   7675: # ------------------------------------------------------- Write our PID on disk
                   7676: 
1.134     albertel 7677: my $execdir=$perlvar{'lonDaemons'};
1.1       albertel 7678: open (PIDSAVE,">$execdir/logs/lond.pid");
                   7679: print PIDSAVE "$$\n";
                   7680: close(PIDSAVE);
1.190     albertel 7681: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.57      www      7682: &status('Starting');
1.1       albertel 7683: 
1.106     foxr     7684: 
1.1       albertel 7685: 
                   7686: # ----------------------------------------------------- Install signal handlers
                   7687: 
1.57      www      7688: 
1.1       albertel 7689: $SIG{CHLD} = \&REAPER;
                   7690: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   7691: $SIG{HUP}  = \&HUPSMAN;
1.57      www      7692: $SIG{USR1} = \&checkchildren;
1.144     foxr     7693: $SIG{USR2} = \&UpdateHosts;
1.106     foxr     7694: 
1.148     foxr     7695: #  Read the host hashes:
1.368     albertel 7696: &Apache::lonnet::load_hosts_tab();
1.447     raeburn  7697: my %iphost = &Apache::lonnet::get_iphost(1);
1.106     foxr     7698: 
1.480     raeburn  7699: $dist=`$perlvar{'lonDaemons'}/distprobe`;
1.286     albertel 7700: 
1.471     raeburn  7701: my $arch = `uname -i`;
1.475     raeburn  7702: chomp($arch);
1.471     raeburn  7703: if ($arch eq 'unknown') {
                   7704:     $arch = `uname -m`;
1.475     raeburn  7705:     chomp($arch);
1.471     raeburn  7706: }
                   7707: 
1.555     raeburn  7708: unless (lonssl::Read_Connect_Config(\%secureconf,\%perlvar,\%crlchecked) eq 'ok') {
1.532     raeburn  7709:     &logthis('<font color="blue">No connectionrules table. Will fallback to loncapa.conf</font>');
                   7710: }
                   7711: 
1.106     foxr     7712: # --------------------------------------------------------------
                   7713: #   Accept connections.  When a connection comes in, it is validated
                   7714: #   and if good, a child process is created to process transactions
                   7715: #   along the connection.
                   7716: 
1.1       albertel 7717: while (1) {
1.165     albertel 7718:     &status('Starting accept');
1.106     foxr     7719:     $client = $server->accept() or next;
1.165     albertel 7720:     &status('Accepted '.$client.' off to spawn');
1.386     albertel 7721:     make_new_child($client);
1.165     albertel 7722:     &status('Finished spawning');
1.1       albertel 7723: }
                   7724: 
1.212     foxr     7725: sub make_new_child {
                   7726:     my $pid;
                   7727: #    my $cipher;     # Now global
                   7728:     my $sigset;
1.178     foxr     7729: 
1.212     foxr     7730:     $client = shift;
                   7731:     &status('Starting new child '.$client);
                   7732:     &logthis('<font color="green"> Attempting to start child ('.$client.
                   7733: 	     ")</font>");    
                   7734:     # block signal for fork
                   7735:     $sigset = POSIX::SigSet->new(SIGINT);
                   7736:     sigprocmask(SIG_BLOCK, $sigset)
                   7737:         or die "Can't block SIGINT for fork: $!\n";
1.178     foxr     7738: 
1.212     foxr     7739:     die "fork: $!" unless defined ($pid = fork);
1.178     foxr     7740: 
1.212     foxr     7741:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
                   7742: 	                               # connection liveness.
1.178     foxr     7743: 
1.212     foxr     7744:     #
                   7745:     #  Figure out who we're talking to so we can record the peer in 
                   7746:     #  the pid hash.
                   7747:     #
                   7748:     my $caller = getpeername($client);
                   7749:     my ($port,$iaddr);
                   7750:     if (defined($caller) && length($caller) > 0) {
                   7751: 	($port,$iaddr)=unpack_sockaddr_in($caller);
                   7752:     } else {
                   7753: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
                   7754:     }
                   7755:     if (defined($iaddr)) {
                   7756: 	$clientip  = inet_ntoa($iaddr);
                   7757: 	Debug("Connected with $clientip");
                   7758:     } else {
                   7759: 	&logthis("Unable to determine clientip");
                   7760: 	$clientip='Unavailable';
                   7761:     }
                   7762:     
                   7763:     if ($pid) {
                   7764:         # Parent records the child's birth and returns.
                   7765:         sigprocmask(SIG_UNBLOCK, $sigset)
                   7766:             or die "Can't unblock SIGINT for fork: $!\n";
                   7767:         $children{$pid} = $clientip;
                   7768:         &status('Started child '.$pid);
1.462     foxr     7769: 	close($client);
1.212     foxr     7770:         return;
                   7771:     } else {
                   7772:         # Child can *not* return from this subroutine.
                   7773:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
                   7774:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
                   7775:                                 #don't get intercepted
                   7776:         $SIG{USR1}= \&logstatus;
                   7777:         $SIG{ALRM}= \&timeout;
1.468     foxr     7778: 	#
                   7779: 	# Block sigpipe as it gets thrownon socket disconnect and we want to 
                   7780: 	# deal with that as a read faiure instead.
                   7781: 	#
                   7782: 	my $blockset = POSIX::SigSet->new(SIGPIPE);
                   7783: 	sigprocmask(SIG_BLOCK, $blockset);
                   7784: 
1.212     foxr     7785:         $lastlog='Forked ';
                   7786:         $status='Forked';
1.178     foxr     7787: 
1.212     foxr     7788:         # unblock signals
                   7789:         sigprocmask(SIG_UNBLOCK, $sigset)
                   7790:             or die "Can't unblock SIGINT for fork: $!\n";
1.178     foxr     7791: 
1.212     foxr     7792: #        my $tmpsnum=0;            # Now global
                   7793: #---------------------------------------------------- kerberos 5 initialization
                   7794:         &Authen::Krb5::init_context();
1.511     raeburn  7795: 
                   7796:         my $no_ets;
1.559     raeburn  7797:         if ($dist =~ /^(?:centos|rhes|scientific|oracle)(\d+)$/) {
1.511     raeburn  7798:             if ($1 >= 7) {
                   7799:                 $no_ets = 1;
                   7800:             }
                   7801:         } elsif ($dist =~ /^suse(\d+\.\d+)$/) {
                   7802:             if (($1 eq '9.3') || ($1 >= 12.2)) {
                   7803:                 $no_ets = 1; 
                   7804:             }
1.514     raeburn  7805:         } elsif ($dist =~ /^sles(\d+)$/) {
                   7806:             if ($1 > 11) {
                   7807:                 $no_ets = 1;
                   7808:             }
1.511     raeburn  7809:         } elsif ($dist =~ /^fedora(\d+)$/) {
                   7810:             if ($1 < 7) {
                   7811:                 $no_ets = 1;
                   7812:             }
                   7813:         }
                   7814:         unless ($no_ets) {
1.286     albertel 7815: 	    &Authen::Krb5::init_ets();
                   7816: 	}
1.209     albertel 7817: 
1.212     foxr     7818: 	&status('Accepted connection');
                   7819: # =============================================================================
                   7820:             # do something with the connection
                   7821: # -----------------------------------------------------------------------------
                   7822: 	# see if we know client and 'check' for spoof IP by ineffective challenge
1.178     foxr     7823: 
1.278     albertel 7824: 	my $outsideip=$clientip;
                   7825: 	if ($clientip eq '127.0.0.1') {
1.368     albertel 7826: 	    $outsideip=&Apache::lonnet::get_host_ip($perlvar{'lonHostID'});
1.278     albertel 7827: 	}
1.412     foxr     7828: 	&ReadManagerTable();
1.368     albertel 7829: 	my $clientrec=defined(&Apache::lonnet::get_hosts_from_ip($outsideip));
1.278     albertel 7830: 	my $ismanager=($managers{$outsideip}    ne undef);
1.432     raeburn  7831: 	$clientname  = "[unknown]";
1.212     foxr     7832: 	if($clientrec) {	# Establish client type.
                   7833: 	    $ConnectionType = "client";
1.368     albertel 7834: 	    $clientname = (&Apache::lonnet::get_hosts_from_ip($outsideip))[-1];
1.212     foxr     7835: 	    if($ismanager) {
                   7836: 		$ConnectionType = "both";
                   7837: 	    }
                   7838: 	} else {
                   7839: 	    $ConnectionType = "manager";
1.278     albertel 7840: 	    $clientname = $managers{$outsideip};
1.212     foxr     7841: 	}
1.556     raeburn  7842: 	my $clientok;
1.178     foxr     7843: 
1.212     foxr     7844: 	if ($clientrec || $ismanager) {
                   7845: 	    &status("Waiting for init from $clientip $clientname");
                   7846: 	    &logthis('<font color="yellow">INFO: Connection, '.
                   7847: 		     $clientip.
                   7848: 		  " ($clientname) connection type = $ConnectionType </font>" );
                   7849: 	    &status("Connecting $clientip  ($clientname))"); 
                   7850: 	    my $remotereq=<$client>;
                   7851: 	    chomp($remotereq);
                   7852: 	    Debug("Got init: $remotereq");
1.337     albertel 7853: 
1.212     foxr     7854: 	    if ($remotereq =~ /^init/) {
                   7855: 		&sethost("sethost:$perlvar{'lonHostID'}");
                   7856: 		#
                   7857: 		#  If the remote is attempting a local init... give that a try:
                   7858: 		#
1.432     raeburn  7859: 		(my $i, my $inittype, $clientversion) = split(/:/, $remotereq);
1.492     droeschl 7860:         # For LON-CAPA 2.9, the  client session will have sent its LON-CAPA
                   7861:         # version when initiating the connection. For LON-CAPA 2.8 and older,
                   7862:         # the version is retrieved from the global %loncaparevs in lonnet.pm.            
1.494     droeschl 7863:         # $clientversion contains path to keyfile if $inittype eq 'local'
                   7864:         # it's overridden below in this case
1.492     droeschl 7865:         $clientversion ||= $Apache::lonnet::loncaparevs{$clientname};
1.209     albertel 7866: 
1.212     foxr     7867: 		# If the connection type is ssl, but I didn't get my
                   7868: 		# certificate files yet, then I'll drop  back to 
                   7869: 		# insecure (if allowed).
1.532     raeburn  7870: 
                   7871:                 if ($inittype eq "ssl") {
                   7872:                     my $context;
                   7873:                     if ($clientsamedom) {
                   7874:                         $context = 'dom';
                   7875:                         if ($secureconf{'connfrom'}{'dom'} eq 'no') {
                   7876:                             $inittype = "";
                   7877:                         }
                   7878:                     } elsif ($clientsameinst) {
                   7879:                         $context = 'intdom';
                   7880:                         if ($secureconf{'connfrom'}{'intdom'} eq 'no') {
                   7881:                             $inittype = "";
                   7882:                         }
                   7883:                     } else {
                   7884:                         $context = 'other';
                   7885:                         if ($secureconf{'connfrom'}{'other'} eq 'no') {
                   7886:                             $inittype = "";
                   7887:                         }
                   7888:                     }
                   7889:                     if ($inittype eq '') {
                   7890:                         &logthis("<font color=\"blue\"> Domain config set "
                   7891:                                 ."to no ssl for $clientname (context: $context)"
                   7892:                                 ." -- trying insecure auth</font>");
                   7893:                     }
                   7894:                 }
                   7895: 
1.212     foxr     7896: 		if($inittype eq "ssl") {
                   7897: 		    my ($ca, $cert) = lonssl::CertificateFile;
                   7898: 		    my $kfile       = lonssl::KeyFile;
                   7899: 		    if((!$ca)   || 
                   7900: 		       (!$cert) || 
                   7901: 		       (!$kfile)) {
                   7902: 			$inittype = ""; # This forces insecure attempt.
                   7903: 			&logthis("<font color=\"blue\"> Certificates not "
                   7904: 				 ."installed -- trying insecure auth</font>");
1.224     foxr     7905: 		    } else {	# SSL certificates are in place so
1.212     foxr     7906: 		    }		# Leave the inittype alone.
                   7907: 		}
                   7908: 
                   7909: 		if($inittype eq "local") {
1.432     raeburn  7910:                     $clientversion = $perlvar{'lonVersion'};
1.212     foxr     7911: 		    my $key = LocalConnection($client, $remotereq);
                   7912: 		    if($key) {
                   7913: 			Debug("Got local key $key");
                   7914: 			$clientok     = 1;
                   7915: 			my $cipherkey = pack("H32", $key);
                   7916: 			$cipher       = new IDEA($cipherkey);
                   7917: 			print $client "ok:local\n";
1.442     www      7918: 			&logthis('<font color="green">'
1.212     foxr     7919: 				 . "Successful local authentication </font>");
                   7920: 			$keymode = "local"
1.178     foxr     7921: 		    } else {
1.212     foxr     7922: 			Debug("Failed to get local key");
                   7923: 			$clientok = 0;
                   7924: 			shutdown($client, 3);
                   7925: 			close $client;
1.178     foxr     7926: 		    }
1.212     foxr     7927: 		} elsif ($inittype eq "ssl") {
1.532     raeburn  7928: 		    my $key = SSLConnection($client,$clientname);
1.212     foxr     7929: 		    if ($key) {
                   7930: 			$clientok = 1;
                   7931: 			my $cipherkey = pack("H32", $key);
                   7932: 			$cipher       = new IDEA($cipherkey);
                   7933: 			&logthis('<font color="green">'
                   7934: 				 ."Successfull ssl authentication with $clientname </font>");
                   7935: 			$keymode = "ssl";
                   7936: 	     
1.178     foxr     7937: 		    } else {
1.212     foxr     7938: 			$clientok = 0;
                   7939: 			close $client;
1.178     foxr     7940: 		    }
1.212     foxr     7941: 	   
                   7942: 		} else {
                   7943: 		    my $ok = InsecureConnection($client);
                   7944: 		    if($ok) {
                   7945: 			$clientok = 1;
                   7946: 			&logthis('<font color="green">'
                   7947: 				 ."Successful insecure authentication with $clientname </font>");
                   7948: 			print $client "ok\n";
                   7949: 			$keymode = "insecure";
1.178     foxr     7950: 		    } else {
1.212     foxr     7951: 			&logthis('<font color="yellow">'
                   7952: 				  ."Attempted insecure connection disallowed </font>");
                   7953: 			close $client;
                   7954: 			$clientok = 0;
1.178     foxr     7955: 		    }
                   7956: 		}
1.212     foxr     7957: 	    } else {
                   7958: 		&logthis(
                   7959: 			 "<font color='blue'>WARNING: "
                   7960: 			 ."$clientip failed to initialize: >$remotereq< </font>");
                   7961: 		&status('No init '.$clientip);
                   7962: 	    }
                   7963: 	} else {
                   7964: 	    &logthis(
                   7965: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
                   7966: 	    &status('Hung up on '.$clientip);
                   7967: 	}
                   7968:  
                   7969: 	if ($clientok) {
                   7970: # ---------------- New known client connecting, could mean machine online again
1.368     albertel 7971: 	    if (&Apache::lonnet::get_host_ip($currenthostid) ne $clientip 
1.367     albertel 7972: 		&& $clientip ne '127.0.0.1') {
1.375     albertel 7973: 		&Apache::lonnet::reconlonc($clientname);
1.212     foxr     7974: 	    }
                   7975: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
                   7976: 	    &status('Will listen to '.$clientname);
                   7977: # ------------------------------------------------------------ Process requests
                   7978: 	    my $keep_going = 1;
                   7979: 	    my $user_input;
1.556     raeburn  7980: 
1.212     foxr     7981: 	    while(($user_input = get_request) && $keep_going) {
                   7982: 		alarm(120);
                   7983: 		Debug("Main: Got $user_input\n");
                   7984: 		$keep_going = &process_request($user_input);
1.178     foxr     7985: 		alarm(0);
1.212     foxr     7986: 		&status('Listening to '.$clientname." ($keymode)");	   
1.161     foxr     7987: 	    }
1.212     foxr     7988: 
1.59      www      7989: # --------------------------------------------- client unknown or fishy, refuse
1.212     foxr     7990: 	}  else {
1.161     foxr     7991: 	    print $client "refused\n";
                   7992: 	    $client->close();
1.190     albertel 7993: 	    &logthis("<font color='blue'>WARNING: "
1.161     foxr     7994: 		     ."Rejected client $clientip, closing connection</font>");
                   7995: 	}
1.525     raeburn  7996:     }
1.161     foxr     7997:     
1.1       albertel 7998: # =============================================================================
1.161     foxr     7999:     
1.190     albertel 8000:     &logthis("<font color='red'>CRITICAL: "
1.161     foxr     8001: 	     ."Disconnect from $clientip ($clientname)</font>");    
                   8002:     
                   8003:     
                   8004:     # this exit is VERY important, otherwise the child will become
                   8005:     # a producer of more and more children, forking yourself into
                   8006:     # process death.
                   8007:     exit;
1.106     foxr     8008:     
1.78      foxr     8009: }
1.532     raeburn  8010: 
                   8011: #
                   8012: #  Used to determine if a particular client is from the same domain
1.556     raeburn  8013: #  as the current server, or from the same internet domain, and
                   8014: #  also if the client can host sessions for the domain's users.
                   8015: #  A hash is populated with keys set to commands sent by the client
                   8016: #  which may not be executed for this domain.
1.532     raeburn  8017: #
                   8018: #  Optional input -- the client to check for domain and internet domain.
                   8019: #  If not specified, defaults to the package variable: $clientname
                   8020: #
                   8021: #  If called in array context will not set package variables, but will
                   8022: #  instead return an array of two values - (a) true if client is in the
1.556     raeburn  8023: #  same domain as the server, and (b) true if client is in the same 
                   8024: #  internet domain.
1.532     raeburn  8025: #
                   8026: #  If called in scalar context, sets package variables for current client:
                   8027: #
1.556     raeburn  8028: #  $clienthomedom    - LonCAPA domain of homeID for client.
                   8029: #  $clientsamedom    - LonCAPA domain same for this host and client.
                   8030: #  $clientintdom     - LonCAPA "internet domain" for client.
                   8031: #  $clientsameinst   - LonCAPA "internet domain" same for this host & client.
                   8032: #  $clientremoteok   - If current domain permits hosting on this client: 1
                   8033: #  %clientprohibited - Commands prohibited for domain's users for this client.
                   8034: #
                   8035: #  if the host and client have the same "internet domain", then the value
                   8036: #  of $clientremoteok is not used, and no commands are prohibited.
1.532     raeburn  8037: #
                   8038: #  returns 1 to indicate package variables have been set for current client.
                   8039: #
                   8040: 
                   8041: sub set_client_info {
                   8042:     my ($lonhost) = @_;
                   8043:     $lonhost ||= $clientname;
                   8044:     my $clienthost = &Apache::lonnet::hostname($lonhost);
                   8045:     my $clientserverhomeID = &Apache::lonnet::get_server_homeID($clienthost);
                   8046:     my $homedom = &Apache::lonnet::host_domain($clientserverhomeID);
                   8047:     my $samedom = 0;
1.557     raeburn  8048:     if ($perlvar{'lonDefDomain'} eq $homedom) {
1.532     raeburn  8049:         $samedom = 1;
                   8050:     }
                   8051:     my $intdom = &Apache::lonnet::internet_dom($clientserverhomeID);
                   8052:     my $sameinst = 0;
                   8053:     if ($intdom ne '') {
                   8054:         my $internet_names = &Apache::lonnet::get_internet_names($currenthostid);
                   8055:         if (ref($internet_names) eq 'ARRAY') {
                   8056:             if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   8057:                 $sameinst = 1;
                   8058:             }
                   8059:         }
                   8060:     }
                   8061:     if (wantarray) {
                   8062:         return ($samedom,$sameinst);
                   8063:     } else {
                   8064:         $clienthomedom = $homedom;
                   8065:         $clientsamedom = $samedom;
                   8066:         $clientintdom = $intdom;
                   8067:         $clientsameinst = $sameinst;
1.556     raeburn  8068:         if ($clientsameinst) {
                   8069:             undef($clientremoteok);
                   8070:             undef(%clientprohibited);
                   8071:         } else {
                   8072:             $clientremoteok = &get_remote_hostable($currentdomainid);
                   8073:             %clientprohibited = &get_prohibited($currentdomainid);
                   8074:         }
1.532     raeburn  8075:         return 1;
                   8076:     }
                   8077: }
                   8078: 
1.261     foxr     8079: #
                   8080: #   Determine if a user is an author for the indicated domain.
                   8081: #
                   8082: # Parameters:
                   8083: #    domain          - domain to check in .
                   8084: #    user            - Name of user to check.
                   8085: #
                   8086: # Return:
                   8087: #     1             - User is an author for domain.
                   8088: #     0             - User is not an author for domain.
                   8089: sub is_author {
                   8090:     my ($domain, $user) = @_;
                   8091: 
                   8092:     &Debug("is_author: $user @ $domain");
                   8093: 
                   8094:     my $hashref = &tie_user_hash($domain, $user, "roles",
                   8095: 				 &GDBM_READER());
                   8096: 
                   8097:     #  Author role should show up as a key /domain/_au
1.78      foxr     8098: 
1.321     albertel 8099:     my $value;
1.487     foxr     8100:     if ($hashref) {
1.78      foxr     8101: 
1.487     foxr     8102: 	my $key    = "/$domain/_au";
                   8103: 	if (defined($hashref)) {
                   8104: 	    $value = $hashref->{$key};
                   8105: 	    if(!untie_user_hash($hashref)) {
                   8106: 		return 'error: ' .  ($!+0)." untie (GDBM) Failed";
                   8107: 	    }
                   8108: 	}
                   8109: 	
                   8110: 	if(defined($value)) {
                   8111: 	    &Debug("$user @ $domain is an author");
                   8112: 	}
                   8113:     } else {
                   8114: 	return 'error: '.($!+0)." tie (GDBM) Failed";
1.261     foxr     8115:     }
                   8116: 
                   8117:     return defined($value);
                   8118: }
1.78      foxr     8119: #
                   8120: #   Checks to see if the input roleput request was to set
1.482     www      8121: # an author role.  If so, creates construction space 
1.78      foxr     8122: # Parameters:
                   8123: #    request   - The request sent to the rolesput subchunk.
                   8124: #                We're looking for  /domain/_au
                   8125: #    domain    - The domain in which the user is having roles doctored.
                   8126: #    user      - Name of the user for which the role is being put.
                   8127: #    authtype  - The authentication type associated with the user.
                   8128: #
1.289     albertel 8129: sub manage_permissions {
1.192     foxr     8130:     my ($request, $domain, $user, $authtype) = @_;
1.78      foxr     8131:     # See if the request is of the form /$domain/_au
1.289     albertel 8132:     if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
1.484     raeburn  8133:         my $path=$perlvar{'lonDocRoot'}."/priv/$domain";
1.482     www      8134:         unless (-e $path) {        
                   8135:            mkdir($path);
                   8136:         }
                   8137:         unless (-e $path.'/'.$user) {
                   8138:            mkdir($path.'/'.$user);
                   8139:         }
1.78      foxr     8140:     }
                   8141: }
1.222     foxr     8142: 
                   8143: 
                   8144: #
                   8145: #  Return the full path of a user password file, whether it exists or not.
                   8146: # Parameters:
                   8147: #   domain     - Domain in which the password file lives.
                   8148: #   user       - name of the user.
                   8149: # Returns:
                   8150: #    Full passwd path:
                   8151: #
                   8152: sub password_path {
                   8153:     my ($domain, $user) = @_;
1.264     albertel 8154:     return &propath($domain, $user).'/passwd';
1.222     foxr     8155: }
                   8156: 
                   8157: #   Password Filename
                   8158: #   Returns the path to a passwd file given domain and user... only if
                   8159: #  it exists.
                   8160: # Parameters:
                   8161: #   domain    - Domain in which to search.
                   8162: #   user      - username.
                   8163: # Returns:
                   8164: #   - If the password file exists returns its path.
                   8165: #   - If the password file does not exist, returns undefined.
                   8166: #
                   8167: sub password_filename {
                   8168:     my ($domain, $user) = @_;
                   8169: 
                   8170:     Debug ("PasswordFilename called: dom = $domain user = $user");
                   8171: 
                   8172:     my $path  = &password_path($domain, $user);
                   8173:     Debug("PasswordFilename got path: $path");
                   8174:     if(-e $path) {
                   8175: 	return $path;
                   8176:     } else {
                   8177: 	return undef;
                   8178:     }
                   8179: }
                   8180: 
                   8181: #
                   8182: #   Rewrite the contents of the user's passwd file.
                   8183: #  Parameters:
                   8184: #    domain    - domain of the user.
                   8185: #    name      - User's name.
                   8186: #    contents  - New contents of the file.
1.533     raeburn  8187: #    saveold   - (optional). If true save old file in a passwd.bak file.
1.222     foxr     8188: # Returns:
                   8189: #   0    - Failed.
                   8190: #   1    - Success.
                   8191: #
                   8192: sub rewrite_password_file {
1.533     raeburn  8193:     my ($domain, $user, $contents, $saveold) = @_;
1.222     foxr     8194: 
                   8195:     my $file = &password_filename($domain, $user);
                   8196:     if (defined $file) {
1.533     raeburn  8197:         if ($saveold) {
                   8198:             my $bakfile = $file.'.bak';
                   8199:             if (CopyFile($file,$bakfile)) {
                   8200:                 chmod(0400,$bakfile);
                   8201:                 &logthis("Old password saved in passwd.bak for internally authenticated user: $user:$domain");
                   8202:             } else {
                   8203:                 &logthis("Failed to save old password in passwd.bak for internally authenticated user: $user:$domain");
                   8204:             }
                   8205:         }
1.222     foxr     8206: 	my $pf = IO::File->new(">$file");
                   8207: 	if($pf) {
                   8208: 	    print $pf "$contents\n";
                   8209: 	    return 1;
                   8210: 	} else {
                   8211: 	    return 0;
                   8212: 	}
                   8213:     } else {
                   8214: 	return 0;
                   8215:     }
                   8216: 
                   8217: }
                   8218: 
1.78      foxr     8219: #
1.222     foxr     8220: #   get_auth_type - Determines the authorization type of a user in a domain.
1.78      foxr     8221: 
                   8222: #     Returns the authorization type or nouser if there is no such user.
                   8223: #
1.436     raeburn  8224: sub get_auth_type {
1.192     foxr     8225:     my ($domain, $user)  = @_;
1.78      foxr     8226: 
1.222     foxr     8227:     Debug("get_auth_type( $domain, $user ) \n");
1.78      foxr     8228:     my $proname    = &propath($domain, $user); 
                   8229:     my $passwdfile = "$proname/passwd";
                   8230:     if( -e $passwdfile ) {
                   8231: 	my $pf = IO::File->new($passwdfile);
                   8232: 	my $realpassword = <$pf>;
                   8233: 	chomp($realpassword);
1.79      foxr     8234: 	Debug("Password info = $realpassword\n");
1.78      foxr     8235: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79      foxr     8236: 	Debug("Authtype = $authtype, content = $contentpwd\n");
1.259     raeburn  8237: 	return "$authtype:$contentpwd";     
1.224     foxr     8238:     } else {
1.79      foxr     8239: 	Debug("Returning nouser");
1.78      foxr     8240: 	return "nouser";
                   8241:     }
1.1       albertel 8242: }
                   8243: 
1.220     foxr     8244: #
                   8245: #  Validate a user given their domain, name and password.  This utility
                   8246: #  function is used by both  AuthenticateHandler and ChangePasswordHandler
                   8247: #  to validate the login credentials of a user.
                   8248: # Parameters:
                   8249: #    $domain    - The domain being logged into (this is required due to
                   8250: #                 the capability for multihomed systems.
                   8251: #    $user      - The name of the user being validated.
                   8252: #    $password  - The user's propoposed password.
                   8253: #
                   8254: # Returns:
                   8255: #     1        - The domain,user,pasword triplet corresponds to a valid
                   8256: #                user.
                   8257: #     0        - The domain,user,password triplet is not a valid user.
                   8258: #
                   8259: sub validate_user {
1.396     raeburn  8260:     my ($domain, $user, $password, $checkdefauth) = @_;
1.220     foxr     8261: 
                   8262:     # Why negative ~pi you may well ask?  Well this function is about
                   8263:     # authentication, and therefore very important to get right.
                   8264:     # I've initialized the flag that determines whether or not I've 
                   8265:     # validated correctly to a value it's not supposed to get.
                   8266:     # At the end of this function. I'll ensure that it's not still that
                   8267:     # value so we don't just wind up returning some accidental value
                   8268:     # as a result of executing an unforseen code path that
1.249     foxr     8269:     # did not set $validated.  At the end of valid execution paths,
                   8270:     # validated shoule be 1 for success or 0 for failuer.
1.220     foxr     8271: 
                   8272:     my $validated = -3.14159;
                   8273: 
                   8274:     #  How we authenticate is determined by the type of authentication
                   8275:     #  the user has been assigned.  If the authentication type is
                   8276:     #  "nouser", the user does not exist so we will return 0.
                   8277: 
1.222     foxr     8278:     my $contents = &get_auth_type($domain, $user);
1.220     foxr     8279:     my ($howpwd, $contentpwd) = split(/:/, $contents);
                   8280: 
                   8281:     my $null = pack("C",0);	# Used by kerberos auth types.
                   8282: 
1.395     raeburn  8283:     if ($howpwd eq 'nouser') {
1.396     raeburn  8284:         if ($checkdefauth) {
                   8285:             my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   8286:             if ($domdefaults{'auth_def'} eq 'localauth') {
                   8287:                 $howpwd = $domdefaults{'auth_def'};
                   8288:                 $contentpwd = $domdefaults{'auth_arg_def'};
                   8289:             } elsif ((($domdefaults{'auth_def'} eq 'krb4') || 
                   8290:                       ($domdefaults{'auth_def'} eq 'krb5')) &&
                   8291:                      ($domdefaults{'auth_arg_def'} ne '')) {
                   8292:                 $howpwd = $domdefaults{'auth_def'};
                   8293:                 $contentpwd = $domdefaults{'auth_arg_def'}; 
                   8294:             }
1.395     raeburn  8295:         }
1.533     raeburn  8296:     }
1.220     foxr     8297:     if ($howpwd ne 'nouser') {
                   8298: 	if($howpwd eq "internal") { # Encrypted is in local password file.
1.518     raeburn  8299:             if (length($contentpwd) == 13) {
                   8300:                 $validated = (crypt($password,$contentpwd) eq $contentpwd);
                   8301:                 if ($validated) {
1.533     raeburn  8302:                     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   8303:                     if ($domdefaults{'intauth_switch'}) {
                   8304:                         my $ncpass = &hash_passwd($domain,$password);
                   8305:                         my $saveold;
                   8306:                         if ($domdefaults{'intauth_switch'} == 2) {
                   8307:                             $saveold = 1;
                   8308:                         }
                   8309:                         if (&rewrite_password_file($domain,$user,"$howpwd:$ncpass",$saveold)) {
                   8310:                             &update_passwd_history($user,$domain,$howpwd,'conversion');
                   8311:                             &logthis("Validated password hashed with bcrypt for $user:$domain");
                   8312:                         }
1.518     raeburn  8313:                     }
                   8314:                 }
                   8315:             } else {
1.533     raeburn  8316:                 $validated = &check_internal_passwd($password,$contentpwd,$domain,$user);
1.518     raeburn  8317:             }
1.220     foxr     8318: 	}
                   8319: 	elsif ($howpwd eq "unix") { # User is a normal unix user.
                   8320: 	    $contentpwd = (getpwnam($user))[1];
                   8321: 	    if($contentpwd) {
                   8322: 		if($contentpwd eq 'x') { # Shadow password file...
                   8323: 		    my $pwauth_path = "/usr/local/sbin/pwauth";
                   8324: 		    open PWAUTH,  "|$pwauth_path" or
                   8325: 			die "Cannot invoke authentication";
                   8326: 		    print PWAUTH "$user\n$password\n";
                   8327: 		    close PWAUTH;
                   8328: 		    $validated = ! $?;
                   8329: 
                   8330: 		} else { 	         # Passwords in /etc/passwd. 
                   8331: 		    $validated = (crypt($password,
                   8332: 					$contentpwd) eq $contentpwd);
                   8333: 		}
                   8334: 	    } else {
                   8335: 		$validated = 0;
                   8336: 	    }
1.439     raeburn  8337: 	} elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
                   8338:             my $checkwithkrb5 = 0;
                   8339:             if ($dist =~/^fedora(\d+)$/) {
                   8340:                 if ($1 > 11) {
                   8341:                     $checkwithkrb5 = 1;
                   8342:                 }
                   8343:             } elsif ($dist =~ /^suse([\d.]+)$/) {
                   8344:                 if ($1 > 11.1) {
                   8345:                     $checkwithkrb5 = 1; 
                   8346:                 }
                   8347:             }
                   8348:             if ($checkwithkrb5) {
                   8349:                 $validated = &krb5_authen($password,$null,$user,$contentpwd);
                   8350:             } else {
                   8351:                 $validated = &krb4_authen($password,$null,$user,$contentpwd);
                   8352:             }
1.224     foxr     8353: 	} elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
1.439     raeburn  8354:             $validated = &krb5_authen($password,$null,$user,$contentpwd);
1.224     foxr     8355: 	} elsif ($howpwd eq "localauth") { 
1.220     foxr     8356: 	    #  Authenticate via installation specific authentcation method:
                   8357: 	    $validated = &localauth::localauth($user, 
                   8358: 					       $password, 
1.353     albertel 8359: 					       $contentpwd,
                   8360: 					       $domain);
1.358     albertel 8361: 	    if ($validated < 0) {
1.357     albertel 8362: 		&logthis("localauth for $contentpwd $user:$domain returned a $validated");
                   8363: 		$validated = 0;
                   8364: 	    }
1.224     foxr     8365: 	} else {			# Unrecognized auth is also bad.
1.220     foxr     8366: 	    $validated = 0;
                   8367: 	}
                   8368:     } else {
                   8369: 	$validated = 0;
                   8370:     }
                   8371:     #
                   8372:     #  $validated has the correct stat of the authentication:
                   8373:     #
                   8374: 
                   8375:     unless ($validated != -3.14159) {
1.249     foxr     8376: 	#  I >really really< want to know if this happens.
                   8377: 	#  since it indicates that user authentication is badly
                   8378: 	#  broken in some code path.
                   8379:         #
                   8380: 	die "ValidateUser - failed to set the value of validated $domain, $user $password";
1.220     foxr     8381:     }
                   8382:     return $validated;
                   8383: }
                   8384: 
1.518     raeburn  8385: sub check_internal_passwd {
1.533     raeburn  8386:     my ($plainpass,$stored,$domain,$user) = @_;
1.518     raeburn  8387:     my (undef,$method,@rest) = split(/!/,$stored);
1.533     raeburn  8388:     if ($method eq 'bcrypt') {
1.518     raeburn  8389:         my $result = &hash_passwd($domain,$plainpass,@rest);
                   8390:         if ($result ne $stored) {
                   8391:             return 0;
                   8392:         }
1.533     raeburn  8393:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   8394:         if ($domdefaults{'intauth_check'}) {
                   8395:             # Upgrade to a larger number of rounds if necessary
                   8396:             my $defaultcost = $domdefaults{'intauth_cost'};
                   8397:             if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
                   8398:                 $defaultcost = 10;
                   8399:             }
                   8400:             if (int($rest[0])<int($defaultcost)) {
                   8401:                 if ($domdefaults{'intauth_check'} == 1) { 
                   8402:                     my $ncpass = &hash_passwd($domain,$plainpass);
                   8403:                     if (&rewrite_password_file($domain,$user,"internal:$ncpass")) {
                   8404:                         &update_passwd_history($user,$domain,'internal','update cost');
                   8405:                         &logthis("Validated password hashed with bcrypt for $user:$domain");
                   8406:                     }
                   8407:                     return 1;
                   8408:                 } elsif ($domdefaults{'intauth_check'} == 2) {
                   8409:                     return 0;
                   8410:                 }
                   8411:             }
                   8412:         } else {
                   8413:             return 1;
1.518     raeburn  8414:         }
                   8415:     }
                   8416:     return 0;
                   8417: }
                   8418: 
                   8419: sub get_last_authchg {
                   8420:     my ($domain,$user) = @_;
                   8421:     my $lastmod;
                   8422:     my $logname = &propath($domain,$user).'/passwd.log';
                   8423:     if (-e "$logname") {
                   8424:         $lastmod = (stat("$logname"))[9];
                   8425:     }
                   8426:     return $lastmod;
                   8427: }
                   8428: 
1.439     raeburn  8429: sub krb4_authen {
                   8430:     my ($password,$null,$user,$contentpwd) = @_;
                   8431:     my $validated = 0;
                   8432:     if (!($password =~ /$null/) ) {  # Null password not allowed.
                   8433:         eval {
                   8434:             require Authen::Krb4;
                   8435:         };
                   8436:         if (!$@) {
                   8437:             my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
                   8438:                                                        "",
                   8439:                                                        $contentpwd,,
                   8440:                                                        'krbtgt',
                   8441:                                                        $contentpwd,
                   8442:                                                        1,
                   8443:                                                        $password);
                   8444:             if(!$k4error) {
                   8445:                 $validated = 1;
                   8446:             } else {
                   8447:                 $validated = 0;
                   8448:                 &logthis('krb4: '.$user.', '.$contentpwd.', '.
                   8449:                           &Authen::Krb4::get_err_txt($Authen::Krb4::error));
                   8450:             }
                   8451:         } else {
                   8452:             $validated = krb5_authen($password,$null,$user,$contentpwd);
                   8453:         }
                   8454:     }
                   8455:     return $validated;
                   8456: }
                   8457: 
                   8458: sub krb5_authen {
                   8459:     my ($password,$null,$user,$contentpwd) = @_;
                   8460:     my $validated = 0;
                   8461:     if(!($password =~ /$null/)) { # Null password not allowed.
                   8462:         my $krbclient = &Authen::Krb5::parse_name($user.'@'
                   8463:                                                   .$contentpwd);
                   8464:         my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
                   8465:         my $krbserver  = &Authen::Krb5::parse_name($krbservice);
                   8466:         my $credentials= &Authen::Krb5::cc_default();
                   8467:         $credentials->initialize(&Authen::Krb5::parse_name($user.'@'
                   8468:                                                             .$contentpwd));
                   8469:         my $krbreturn;
                   8470:         if (exists(&Authen::Krb5::get_init_creds_password)) {
                   8471:             $krbreturn =
                   8472:                 &Authen::Krb5::get_init_creds_password($krbclient,$password,
                   8473:                                                           $krbservice);
                   8474:             $validated = (ref($krbreturn) eq 'Authen::Krb5::Creds');
                   8475:         } else {
                   8476:             $krbreturn  =
                   8477:                 &Authen::Krb5::get_in_tkt_with_password($krbclient,$krbserver,
                   8478:                                                          $password,$credentials);
                   8479:             $validated = ($krbreturn == 1);
                   8480:         }
                   8481:         if (!$validated) {
                   8482:             &logthis('krb5: '.$user.', '.$contentpwd.', '.
                   8483:                      &Authen::Krb5::error());
                   8484:         }
                   8485:     }
                   8486:     return $validated;
                   8487: }
1.220     foxr     8488: 
1.84      albertel 8489: sub addline {
                   8490:     my ($fname,$hostid,$ip,$newline)=@_;
                   8491:     my $contents;
                   8492:     my $found=0;
1.355     albertel 8493:     my $expr='^'.quotemeta($hostid).':'.quotemeta($ip).':';
1.134     albertel 8494:     my $sh;
1.84      albertel 8495:     if ($sh=IO::File->new("$fname.subscription")) {
                   8496: 	while (my $subline=<$sh>) {
                   8497: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
                   8498: 	}
                   8499: 	$sh->close();
                   8500:     }
                   8501:     $sh=IO::File->new(">$fname.subscription");
                   8502:     if ($contents) { print $sh $contents; }
                   8503:     if ($newline) { print $sh $newline; }
                   8504:     $sh->close();
                   8505:     return $found;
1.86      www      8506: }
                   8507: 
1.234     foxr     8508: sub get_chat {
1.324     raeburn  8509:     my ($cdom,$cname,$udom,$uname,$group)=@_;
1.310     albertel 8510: 
1.87      www      8511:     my @entries=();
1.324     raeburn  8512:     my $namespace = 'nohist_chatroom';
                   8513:     my $namespace_inroom = 'nohist_inchatroom';
1.335     albertel 8514:     if ($group ne '') {
1.324     raeburn  8515:         $namespace .= '_'.$group;
                   8516:         $namespace_inroom .= '_'.$group;
                   8517:     }
                   8518:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 8519: 				 &GDBM_READER());
                   8520:     if ($hashref) {
                   8521: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.311     albertel 8522: 	&untie_user_hash($hashref);
1.123     www      8523:     }
1.124     www      8524:     my @participants=();
1.134     albertel 8525:     my $cutoff=time-60;
1.324     raeburn  8526:     $hashref = &tie_user_hash($cdom, $cname, $namespace_inroom,
1.310     albertel 8527: 			      &GDBM_WRCREAT());
                   8528:     if ($hashref) {
                   8529:         $hashref->{$uname.':'.$udom}=time;
                   8530:         foreach my $user (sort(keys(%$hashref))) {
                   8531: 	    if ($hashref->{$user}>$cutoff) {
                   8532: 		push(@participants, 'active_participant:'.$user);
1.123     www      8533:             }
                   8534:         }
1.311     albertel 8535:         &untie_user_hash($hashref);
1.86      www      8536:     }
1.124     www      8537:     return (@participants,@entries);
1.86      www      8538: }
                   8539: 
1.234     foxr     8540: sub chat_add {
1.324     raeburn  8541:     my ($cdom,$cname,$newchat,$group)=@_;
1.88      albertel 8542:     my @entries=();
1.142     www      8543:     my $time=time;
1.324     raeburn  8544:     my $namespace = 'nohist_chatroom';
                   8545:     my $logfile = 'chatroom.log';
1.335     albertel 8546:     if ($group ne '') {
1.324     raeburn  8547:         $namespace .= '_'.$group;
                   8548:         $logfile = 'chatroom_'.$group.'.log';
                   8549:     }
                   8550:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 8551: 				 &GDBM_WRCREAT());
                   8552:     if ($hashref) {
                   8553: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.88      albertel 8554: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
                   8555: 	my ($thentime,$idnum)=split(/\_/,$lastid);
                   8556: 	my $newid=$time.'_000000';
                   8557: 	if ($thentime==$time) {
                   8558: 	    $idnum=~s/^0+//;
                   8559: 	    $idnum++;
                   8560: 	    $idnum=substr('000000'.$idnum,-6,6);
                   8561: 	    $newid=$time.'_'.$idnum;
                   8562: 	}
1.310     albertel 8563: 	$hashref->{$newid}=$newchat;
1.88      albertel 8564: 	my $expired=$time-3600;
1.310     albertel 8565: 	foreach my $comment (keys(%$hashref)) {
                   8566: 	    my ($thistime) = ($comment=~/(\d+)\_/);
1.88      albertel 8567: 	    if ($thistime<$expired) {
1.310     albertel 8568: 		delete $hashref->{$comment};
1.88      albertel 8569: 	    }
                   8570: 	}
1.310     albertel 8571: 	{
                   8572: 	    my $proname=&propath($cdom,$cname);
1.324     raeburn  8573: 	    if (open(CHATLOG,">>$proname/$logfile")) { 
1.310     albertel 8574: 		print CHATLOG ("$time:".&unescape($newchat)."\n");
                   8575: 	    }
                   8576: 	    close(CHATLOG);
1.142     www      8577: 	}
1.311     albertel 8578: 	&untie_user_hash($hashref);
1.86      www      8579:     }
1.84      albertel 8580: }
                   8581: 
                   8582: sub unsub {
                   8583:     my ($fname,$clientip)=@_;
                   8584:     my $result;
1.188     foxr     8585:     my $unsubs = 0;		# Number of successful unsubscribes:
                   8586: 
                   8587: 
                   8588:     # An old way subscriptions were handled was to have a 
                   8589:     # subscription marker file:
                   8590: 
                   8591:     Debug("Attempting unlink of $fname.$clientname");
1.161     foxr     8592:     if (unlink("$fname.$clientname")) {
1.188     foxr     8593: 	$unsubs++;		# Successful unsub via marker file.
                   8594:     } 
                   8595: 
                   8596:     # The more modern way to do it is to have a subscription list
                   8597:     # file:
                   8598: 
1.84      albertel 8599:     if (-e "$fname.subscription") {
1.161     foxr     8600: 	my $found=&addline($fname,$clientname,$clientip,'');
1.188     foxr     8601: 	if ($found) { 
                   8602: 	    $unsubs++;
                   8603: 	}
                   8604:     } 
                   8605: 
                   8606:     #  If either or both of these mechanisms succeeded in unsubscribing a 
                   8607:     #  resource we can return ok:
                   8608: 
                   8609:     if($unsubs) {
                   8610: 	$result = "ok\n";
1.84      albertel 8611:     } else {
1.188     foxr     8612: 	$result = "not_subscribed\n";
1.84      albertel 8613:     }
1.188     foxr     8614: 
1.84      albertel 8615:     return $result;
                   8616: }
                   8617: 
1.101     www      8618: sub currentversion {
                   8619:     my $fname=shift;
                   8620:     my $version=-1;
                   8621:     my $ulsdir='';
                   8622:     if ($fname=~/^(.+)\/[^\/]+$/) {
                   8623:        $ulsdir=$1;
                   8624:     }
1.114     albertel 8625:     my ($fnamere1,$fnamere2);
                   8626:     # remove version if already specified
1.101     www      8627:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114     albertel 8628:     # get the bits that go before and after the version number
                   8629:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
                   8630: 	$fnamere1=$1;
                   8631: 	$fnamere2='.'.$2;
                   8632:     }
1.101     www      8633:     if (-e $fname) { $version=1; }
                   8634:     if (-e $ulsdir) {
1.134     albertel 8635: 	if(-d $ulsdir) {
                   8636: 	    if (opendir(LSDIR,$ulsdir)) {
                   8637: 		my $ulsfn;
                   8638: 		while ($ulsfn=readdir(LSDIR)) {
1.101     www      8639: # see if this is a regular file (ignore links produced earlier)
1.134     albertel 8640: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
                   8641: 		    unless (-l $thisfile) {
1.160     www      8642: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134     albertel 8643: 			    if ($1>$version) { $version=$1; }
                   8644: 			}
                   8645: 		    }
                   8646: 		}
                   8647: 		closedir(LSDIR);
                   8648: 		$version++;
                   8649: 	    }
                   8650: 	}
                   8651:     }
                   8652:     return $version;
1.101     www      8653: }
                   8654: 
                   8655: sub thisversion {
                   8656:     my $fname=shift;
                   8657:     my $version=-1;
                   8658:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
                   8659: 	$version=$1;
                   8660:     }
                   8661:     return $version;
                   8662: }
                   8663: 
1.84      albertel 8664: sub subscribe {
                   8665:     my ($userinput,$clientip)=@_;
                   8666:     my $result;
1.293     albertel 8667:     my ($cmd,$fname)=split(/:/,$userinput,2);
1.84      albertel 8668:     my $ownership=&ishome($fname);
                   8669:     if ($ownership eq 'owner') {
1.101     www      8670: # explitly asking for the current version?
                   8671:         unless (-e $fname) {
                   8672:             my $currentversion=&currentversion($fname);
                   8673: 	    if (&thisversion($fname)==$currentversion) {
                   8674:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
                   8675: 		    my $root=$1;
                   8676:                     my $extension=$2;
                   8677:                     symlink($root.'.'.$extension,
                   8678:                             $root.'.'.$currentversion.'.'.$extension);
1.102     www      8679:                     unless ($extension=~/\.meta$/) {
                   8680:                        symlink($root.'.'.$extension.'.meta',
                   8681:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
                   8682: 		    }
1.101     www      8683:                 }
                   8684:             }
                   8685:         }
1.84      albertel 8686: 	if (-e $fname) {
                   8687: 	    if (-d $fname) {
                   8688: 		$result="directory\n";
                   8689: 	    } else {
1.161     foxr     8690: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134     albertel 8691: 		my $now=time;
1.161     foxr     8692: 		my $found=&addline($fname,$clientname,$clientip,
                   8693: 				   "$clientname:$clientip:$now\n");
1.84      albertel 8694: 		if ($found) { $result="$fname\n"; }
                   8695: 		# if they were subscribed to only meta data, delete that
                   8696:                 # subscription, when you subscribe to a file you also get
                   8697:                 # the metadata
                   8698: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
                   8699: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
1.476     raeburn  8700:                 my $protocol = $Apache::lonnet::protocol{$perlvar{'lonHostID'}};
                   8701:                 $protocol = 'http' if ($protocol ne 'https');
                   8702: 		$fname=$protocol.'://'.&Apache::lonnet::hostname($perlvar{'lonHostID'})."/".$fname;
1.84      albertel 8703: 		$result="$fname\n";
                   8704: 	    }
                   8705: 	} else {
                   8706: 	    $result="not_found\n";
                   8707: 	}
                   8708:     } else {
                   8709: 	$result="rejected\n";
                   8710:     }
                   8711:     return $result;
                   8712: }
1.287     foxr     8713: #  Change the passwd of a unix user.  The caller must have
                   8714: #  first verified that the user is a loncapa user.
                   8715: #
                   8716: # Parameters:
                   8717: #    user      - Unix user name to change.
                   8718: #    pass      - New password for the user.
                   8719: # Returns:
                   8720: #    ok    - if success
                   8721: #    other - Some meaningfule error message string.
                   8722: # NOTE:
                   8723: #    invokes a setuid script to change the passwd.
                   8724: sub change_unix_password {
                   8725:     my ($user, $pass) = @_;
                   8726: 
                   8727:     &Debug("change_unix_password");
                   8728:     my $execdir=$perlvar{'lonDaemons'};
                   8729:     &Debug("Opening lcpasswd pipeline");
                   8730:     my $pf = IO::File->new("|$execdir/lcpasswd > "
                   8731: 			   ."$perlvar{'lonDaemons'}"
                   8732: 			   ."/logs/lcpasswd.log");
                   8733:     print $pf "$user\n$pass\n$pass\n";
                   8734:     close $pf;
                   8735:     my $err = $?;
                   8736:     return ($err < @passwderrors) ? $passwderrors[$err] : 
                   8737: 	"pwchange_falure - unknown error";
                   8738: 
                   8739:     
                   8740: }
                   8741: 
1.91      albertel 8742: 
                   8743: sub make_passwd_file {
1.518     raeburn  8744:     my ($uname,$udom,$umode,$npass,$passfilename,$action)=@_;
1.390     raeburn  8745:     my $result="ok";
1.91      albertel 8746:     if ($umode eq 'krb4' or $umode eq 'krb5') {
                   8747: 	{
                   8748: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8749: 	    if ($pf) {
                   8750: 		print $pf "$umode:$npass\n";
1.518     raeburn  8751:                 &update_passwd_history($uname,$udom,$umode,$action);
1.261     foxr     8752: 	    } else {
                   8753: 		$result = "pass_file_failed_error";
                   8754: 	    }
1.91      albertel 8755: 	}
                   8756:     } elsif ($umode eq 'internal') {
1.518     raeburn  8757:         my $ncpass = &hash_passwd($udom,$npass);
1.91      albertel 8758: 	{
                   8759: 	    &Debug("Creating internal auth");
                   8760: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8761: 	    if($pf) {
1.518     raeburn  8762: 		print $pf "internal:$ncpass\n";
                   8763:                 &update_passwd_history($uname,$udom,$umode,$action); 
1.261     foxr     8764: 	    } else {
                   8765: 		$result = "pass_file_failed_error";
                   8766: 	    }
1.91      albertel 8767: 	}
                   8768:     } elsif ($umode eq 'localauth') {
                   8769: 	{
                   8770: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8771: 	    if($pf) {
                   8772: 		print $pf "localauth:$npass\n";
1.524     raeburn  8773:                 &update_passwd_history($uname,$udom,$umode,$action);
1.261     foxr     8774: 	    } else {
                   8775: 		$result = "pass_file_failed_error";
                   8776: 	    }
1.91      albertel 8777: 	}
                   8778:     } elsif ($umode eq 'unix') {
1.502     raeburn  8779: 	&logthis(">>>Attempt to create unix account blocked -- unix auth not available for new users.");
                   8780: 	$result="no_new_unix_accounts";
1.91      albertel 8781:     } elsif ($umode eq 'none') {
                   8782: 	{
1.223     foxr     8783: 	    my $pf = IO::File->new("> $passfilename");
1.261     foxr     8784: 	    if($pf) {
                   8785: 		print $pf "none:\n";
                   8786: 	    } else {
                   8787: 		$result = "pass_file_failed_error";
                   8788: 	    }
1.91      albertel 8789: 	}
1.543     raeburn  8790:     } elsif ($umode eq 'lti') {
                   8791:         my $pf = IO::File->new(">$passfilename");
                   8792:         if($pf) {
                   8793:             print $pf "lti:\n";
                   8794:             &update_passwd_history($uname,$udom,$umode,$action);
                   8795:         } else {
                   8796:             $result = "pass_file_failed_error";
                   8797:         }
1.91      albertel 8798:     } else {
1.390     raeburn  8799: 	$result="auth_mode_error";
1.91      albertel 8800:     }
                   8801:     return $result;
1.121     albertel 8802: }
                   8803: 
1.265     albertel 8804: sub convert_photo {
                   8805:     my ($start,$dest)=@_;
                   8806:     system("convert $start $dest");
                   8807: }
                   8808: 
1.121     albertel 8809: sub sethost {
                   8810:     my ($remotereq) = @_;
                   8811:     my (undef,$hostid)=split(/:/,$remotereq);
1.322     albertel 8812:     # ignore sethost if we are already correct
                   8813:     if ($hostid eq $currenthostid) {
                   8814: 	return 'ok';
                   8815:     }
                   8816: 
1.121     albertel 8817:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
1.368     albertel 8818:     if (&Apache::lonnet::get_host_ip($perlvar{'lonHostID'}) 
                   8819: 	eq &Apache::lonnet::get_host_ip($hostid)) {
1.200     matthew  8820: 	$currenthostid  =$hostid;
1.369     albertel 8821: 	$currentdomainid=&Apache::lonnet::host_domain($hostid);
1.556     raeburn  8822:         &set_client_info();
1.443     www      8823: #	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
1.121     albertel 8824:     } else {
                   8825: 	&logthis("Requested host id $hostid not an alias of ".
                   8826: 		 $perlvar{'lonHostID'}." refusing connection");
                   8827: 	return 'unable_to_set';
                   8828:     }
                   8829:     return 'ok';
                   8830: }
                   8831: 
                   8832: sub version {
                   8833:     my ($userinput)=@_;
                   8834:     $remoteVERSION=(split(/:/,$userinput))[1];
                   8835:     return "version:$VERSION";
1.127     albertel 8836: }
1.178     foxr     8837: 
1.447     raeburn  8838: sub get_usersession_config {
                   8839:     my ($dom,$name) = @_;
                   8840:     my ($usersessionconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8841:     if (defined($cached)) {
                   8842:         return $usersessionconf;
                   8843:     } else {
                   8844:         my %domconfig = &Apache::lonnet::get_dom('configuration',['usersessions'],$dom);
1.525     raeburn  8845:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'usersessions'},3600);
                   8846:         return $domconfig{'usersessions'};
1.447     raeburn  8847:     }
                   8848:     return;
                   8849: }
1.200     matthew  8850: 
1.534     raeburn  8851: sub get_usersearch_config {
                   8852:     my ($dom,$name) = @_;
                   8853:     my ($usersearchconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8854:     if (defined($cached)) {
                   8855:         return $usersearchconf;
                   8856:     } else {
                   8857:         my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$dom);
                   8858:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'directorysrch'},600);
                   8859:         return $domconfig{'directorysrch'};
                   8860:     }
                   8861:     return;
                   8862: }
                   8863: 
1.525     raeburn  8864: sub get_prohibited {
                   8865:     my ($dom) = @_;
                   8866:     my $name = 'trust';
                   8867:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8868:     unless (defined($cached)) {
                   8869:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$dom);
                   8870:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'trust'},3600);
                   8871:         $trustconfig = $domconfig{'trust'};
                   8872:     }
                   8873:     my %prohibited;
                   8874:     if (ref($trustconfig)) {
                   8875:         foreach my $prefix (keys(%{$trustconfig})) {
                   8876:             if (ref($trustconfig->{$prefix}) eq 'HASH') {
                   8877:                 my $reject;
                   8878:                 if (ref($trustconfig->{$prefix}->{'exc'}) eq 'ARRAY') {
                   8879:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'exc'}})) {
                   8880:                         $reject = 1;
                   8881:                     }
                   8882:                 }
                   8883:                 if (ref($trustconfig->{$prefix}->{'inc'}) eq 'ARRAY') {
                   8884:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'inc'}})) {
                   8885:                         $reject = 0;
                   8886:                     } else {
                   8887:                         $reject = 1;
                   8888:                     }
                   8889:                 }
                   8890:                 if ($reject) {
                   8891:                     $prohibited{$prefix} = 1;
                   8892:                 }
                   8893:             }
                   8894:         }
                   8895:     }
                   8896:     return %prohibited;
                   8897: }
1.450     raeburn  8898: 
1.556     raeburn  8899: sub get_remote_hostable {
                   8900:     my ($dom) = @_;
                   8901:     my $result;
                   8902:     if ($clientintdom) {
                   8903:         $result = 1;
                   8904:         my $remsessconf = &get_usersession_config($dom,'remotesession');
                   8905:         if (ref($remsessconf) eq 'HASH') {
                   8906:             if (ref($remsessconf->{'remote'}) eq 'HASH') {
                   8907:                 if (ref($remsessconf->{'remote'}->{'excludedomain'}) eq 'ARRAY') {
                   8908:                     if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'excludedomain'}})) {
                   8909:                         $result = 0;
                   8910:                     }
                   8911:                 }
                   8912:                 if (ref($remsessconf->{'remote'}->{'includedomain'}) eq 'ARRAY') {
                   8913:                     if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'includedomain'}})) {
                   8914:                         $result = 1;
                   8915:                     } else {
                   8916:                         $result = 0;
                   8917:                     }
                   8918:                 }
                   8919:             }
                   8920:         }
                   8921:     }
                   8922:     return $result;
                   8923: }
                   8924: 
1.471     raeburn  8925: sub distro_and_arch {
                   8926:     return $dist.':'.$arch;
                   8927: }
                   8928: 
1.61      harris41 8929: # ----------------------------------- POD (plain old documentation, CPAN style)
                   8930: 
                   8931: =head1 NAME
                   8932: 
                   8933: lond - "LON Daemon" Server (port "LOND" 5663)
                   8934: 
                   8935: =head1 SYNOPSIS
                   8936: 
1.74      harris41 8937: Usage: B<lond>
                   8938: 
                   8939: Should only be run as user=www.  This is a command-line script which
                   8940: is invoked by B<loncron>.  There is no expectation that a typical user
                   8941: will manually start B<lond> from the command-line.  (In other words,
                   8942: DO NOT START B<lond> YOURSELF.)
1.61      harris41 8943: 
                   8944: =head1 DESCRIPTION
                   8945: 
1.74      harris41 8946: There are two characteristics associated with the running of B<lond>,
                   8947: PROCESS MANAGEMENT (starting, stopping, handling child processes)
                   8948: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
                   8949: subscriptions, etc).  These are described in two large
                   8950: sections below.
                   8951: 
                   8952: B<PROCESS MANAGEMENT>
                   8953: 
1.61      harris41 8954: Preforker - server who forks first. Runs as a daemon. HUPs.
                   8955: Uses IDEA encryption
                   8956: 
1.74      harris41 8957: B<lond> forks off children processes that correspond to the other servers
                   8958: in the network.  Management of these processes can be done at the
                   8959: parent process level or the child process level.
                   8960: 
                   8961: B<logs/lond.log> is the location of log messages.
                   8962: 
                   8963: The process management is now explained in terms of linux shell commands,
                   8964: subroutines internal to this code, and signal assignments:
                   8965: 
                   8966: =over 4
                   8967: 
                   8968: =item *
                   8969: 
                   8970: PID is stored in B<logs/lond.pid>
                   8971: 
                   8972: This is the process id number of the parent B<lond> process.
                   8973: 
                   8974: =item *
                   8975: 
                   8976: SIGTERM and SIGINT
                   8977: 
                   8978: Parent signal assignment:
                   8979:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   8980: 
                   8981: Child signal assignment:
                   8982:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
                   8983: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
                   8984:  to restart a new child.)
                   8985: 
                   8986: Command-line invocations:
                   8987:  B<kill> B<-s> SIGTERM I<PID>
                   8988:  B<kill> B<-s> SIGINT I<PID>
                   8989: 
                   8990: Subroutine B<HUNTSMAN>:
                   8991:  This is only invoked for the B<lond> parent I<PID>.
                   8992: This kills all the children, and then the parent.
                   8993: The B<lonc.pid> file is cleared.
                   8994: 
                   8995: =item *
                   8996: 
                   8997: SIGHUP
                   8998: 
                   8999: Current bug:
                   9000:  This signal can only be processed the first time
                   9001: on the parent process.  Subsequent SIGHUP signals
                   9002: have no effect.
                   9003: 
                   9004: Parent signal assignment:
                   9005:  $SIG{HUP}  = \&HUPSMAN;
                   9006: 
                   9007: Child signal assignment:
                   9008:  none (nothing happens)
                   9009: 
                   9010: Command-line invocations:
                   9011:  B<kill> B<-s> SIGHUP I<PID>
                   9012: 
                   9013: Subroutine B<HUPSMAN>:
                   9014:  This is only invoked for the B<lond> parent I<PID>,
                   9015: This kills all the children, and then the parent.
                   9016: The B<lond.pid> file is cleared.
                   9017: 
                   9018: =item *
                   9019: 
                   9020: SIGUSR1
                   9021: 
                   9022: Parent signal assignment:
                   9023:  $SIG{USR1} = \&USRMAN;
                   9024: 
                   9025: Child signal assignment:
                   9026:  $SIG{USR1}= \&logstatus;
                   9027: 
                   9028: Command-line invocations:
                   9029:  B<kill> B<-s> SIGUSR1 I<PID>
                   9030: 
                   9031: Subroutine B<USRMAN>:
                   9032:  When invoked for the B<lond> parent I<PID>,
                   9033: SIGUSR1 is sent to all the children, and the status of
                   9034: each connection is logged.
1.144     foxr     9035: 
                   9036: =item *
                   9037: 
                   9038: SIGUSR2
                   9039: 
                   9040: Parent Signal assignment:
                   9041:     $SIG{USR2} = \&UpdateHosts
                   9042: 
                   9043: Child signal assignment:
                   9044:     NONE
                   9045: 
1.74      harris41 9046: 
                   9047: =item *
                   9048: 
                   9049: SIGCHLD
                   9050: 
                   9051: Parent signal assignment:
                   9052:  $SIG{CHLD} = \&REAPER;
                   9053: 
                   9054: Child signal assignment:
                   9055:  none
                   9056: 
                   9057: Command-line invocations:
                   9058:  B<kill> B<-s> SIGCHLD I<PID>
                   9059: 
                   9060: Subroutine B<REAPER>:
                   9061:  This is only invoked for the B<lond> parent I<PID>.
                   9062: Information pertaining to the child is removed.
                   9063: The socket port is cleaned up.
                   9064: 
                   9065: =back
                   9066: 
                   9067: B<SERVER-SIDE ACTIVITIES>
                   9068: 
                   9069: Server-side information can be accepted in an encrypted or non-encrypted
                   9070: method.
                   9071: 
                   9072: =over 4
                   9073: 
                   9074: =item ping
                   9075: 
                   9076: Query a client in the hosts.tab table; "Are you there?"
                   9077: 
                   9078: =item pong
                   9079: 
                   9080: Respond to a ping query.
                   9081: 
                   9082: =item ekey
                   9083: 
                   9084: Read in encrypted key, make cipher.  Respond with a buildkey.
                   9085: 
                   9086: =item load
                   9087: 
                   9088: Respond with CPU load based on a computation upon /proc/loadavg.
                   9089: 
                   9090: =item currentauth
                   9091: 
                   9092: Reply with current authentication information (only over an
                   9093: encrypted channel).
                   9094: 
                   9095: =item auth
                   9096: 
                   9097: Only over an encrypted channel, reply as to whether a user's
                   9098: authentication information can be validated.
                   9099: 
                   9100: =item passwd
                   9101: 
                   9102: Allow for a password to be set.
                   9103: 
                   9104: =item makeuser
                   9105: 
                   9106: Make a user.
                   9107: 
1.517     raeburn  9108: =item changeuserauth
1.74      harris41 9109: 
                   9110: Allow for authentication mechanism and password to be changed.
                   9111: 
                   9112: =item home
1.61      harris41 9113: 
1.74      harris41 9114: Respond to a question "are you the home for a given user?"
                   9115: 
                   9116: =item update
                   9117: 
                   9118: Update contents of a subscribed resource.
                   9119: 
                   9120: =item unsubscribe
                   9121: 
                   9122: The server is unsubscribing from a resource.
                   9123: 
                   9124: =item subscribe
                   9125: 
                   9126: The server is subscribing to a resource.
                   9127: 
                   9128: =item log
                   9129: 
                   9130: Place in B<logs/lond.log>
                   9131: 
                   9132: =item put
                   9133: 
                   9134: stores hash in namespace
                   9135: 
1.496     raeburn  9136: =item rolesput
1.74      harris41 9137: 
                   9138: put a role into a user's environment
                   9139: 
                   9140: =item get
                   9141: 
                   9142: returns hash with keys from array
                   9143: reference filled in from namespace
                   9144: 
                   9145: =item eget
                   9146: 
                   9147: returns hash with keys from array
                   9148: reference filled in from namesp (encrypts the return communication)
                   9149: 
                   9150: =item rolesget
                   9151: 
                   9152: get a role from a user's environment
                   9153: 
                   9154: =item del
                   9155: 
                   9156: deletes keys out of array from namespace
                   9157: 
                   9158: =item keys
                   9159: 
                   9160: returns namespace keys
                   9161: 
                   9162: =item dump
                   9163: 
                   9164: dumps the complete (or key matching regexp) namespace into a hash
                   9165: 
                   9166: =item store
                   9167: 
                   9168: stores hash permanently
                   9169: for this url; hashref needs to be given and should be a \%hashname; the
                   9170: remaining args aren't required and if they aren't passed or are '' they will
                   9171: be derived from the ENV
                   9172: 
                   9173: =item restore
                   9174: 
                   9175: returns a hash for a given url
                   9176: 
                   9177: =item querysend
                   9178: 
                   9179: Tells client about the lonsql process that has been launched in response
                   9180: to a sent query.
                   9181: 
                   9182: =item queryreply
                   9183: 
                   9184: Accept information from lonsql and make appropriate storage in temporary
                   9185: file space.
                   9186: 
                   9187: =item idput
                   9188: 
                   9189: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
                   9190: for each student, defined perhaps by the institutional Registrar.)
                   9191: 
                   9192: =item idget
                   9193: 
                   9194: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
                   9195: for each student, defined perhaps by the institutional Registrar.)
                   9196: 
1.517     raeburn  9197: =item iddel
                   9198: 
                   9199: Deletes one or more ids in a domain's id database.
                   9200: 
1.74      harris41 9201: =item tmpput
                   9202: 
                   9203: Accept and store information in temporary space.
                   9204: 
                   9205: =item tmpget
                   9206: 
                   9207: Send along temporarily stored information.
                   9208: 
                   9209: =item ls
                   9210: 
                   9211: List part of a user's directory.
                   9212: 
1.135     foxr     9213: =item pushtable
                   9214: 
                   9215: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
                   9216: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
                   9217: must be restored manually in case of a problem with the new table file.
                   9218: pushtable requires that the request be encrypted and validated via
                   9219: ValidateManager.  The form of the command is:
                   9220: enc:pushtable tablename <tablecontents> \n
                   9221: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
                   9222: cleartext newline.
                   9223: 
1.74      harris41 9224: =item Hanging up (exit or init)
                   9225: 
                   9226: What to do when a client tells the server that they (the client)
                   9227: are leaving the network.
                   9228: 
                   9229: =item unknown command
                   9230: 
                   9231: If B<lond> is sent an unknown command (not in the list above),
                   9232: it replys to the client "unknown_cmd".
1.135     foxr     9233: 
1.74      harris41 9234: 
                   9235: =item UNKNOWN CLIENT
                   9236: 
                   9237: If the anti-spoofing algorithm cannot verify the client,
                   9238: the client is rejected (with a "refused" message sent
                   9239: to the client, and the connection is closed.
                   9240: 
                   9241: =back
1.61      harris41 9242: 
                   9243: =head1 PREREQUISITES
                   9244: 
                   9245: IO::Socket
                   9246: IO::File
                   9247: Apache::File
                   9248: POSIX
                   9249: Crypt::IDEA
                   9250: GDBM_File
                   9251: Authen::Krb4
1.91      albertel 9252: Authen::Krb5
1.61      harris41 9253: 
                   9254: =head1 COREQUISITES
                   9255: 
1.490     droeschl 9256: none
                   9257: 
1.61      harris41 9258: =head1 OSNAMES
                   9259: 
                   9260: linux
                   9261: 
                   9262: =head1 SCRIPT CATEGORIES
                   9263: 
                   9264: Server/Process
                   9265: 
                   9266: =cut
1.409     foxr     9267: 
                   9268: 
                   9269: =pod
                   9270: 
                   9271: =head1 LOG MESSAGES
                   9272: 
                   9273: The messages below can be emitted in the lond log.  This log is located
                   9274: in ~httpd/perl/logs/lond.log  Many log messages have HTML encapsulation
                   9275: to provide coloring if examined from inside a web page. Some do not.
                   9276: Where color is used, the colors are; Red for sometihhng to get excited
                   9277: about and to follow up on. Yellow for something to keep an eye on to
                   9278: be sure it does not get worse, Green,and Blue for informational items.
                   9279: 
                   9280: In the discussions below, sometimes reference is made to ~httpd
                   9281: when describing file locations.  There isn't really an httpd 
                   9282: user, however there is an httpd directory that gets installed in the
                   9283: place that user home directories go.  On linux, this is usually
                   9284: (always?) /home/httpd.
                   9285: 
                   9286: 
                   9287: Some messages are colorless.  These are usually (not always)
                   9288: Green/Blue color level messages.
                   9289: 
                   9290: =over 2
                   9291: 
                   9292: =item (Red)  LocalConnection rejecting non local: <ip> ne 127.0.0.1
                   9293: 
                   9294: A local connection negotiation was attempted by
                   9295: a host whose IP address was not 127.0.0.1.
                   9296: The socket is closed and the child will exit.
                   9297: lond has three ways to establish an encyrption
                   9298: key with a client:
                   9299: 
                   9300: =over 2
                   9301: 
                   9302: =item local 
                   9303: 
                   9304: The key is written and read from a file.
                   9305: This is only valid for connections from localhost.
                   9306: 
                   9307: =item insecure 
                   9308: 
                   9309: The key is generated by the server and
                   9310: transmitted to the client.
                   9311: 
                   9312: =item  ssl (secure)
                   9313: 
                   9314: An ssl connection is negotiated with the client,
                   9315: the key is generated by the server and sent to the 
                   9316: client across this ssl connection before the
                   9317: ssl connectionis terminated and clear text
                   9318: transmission resumes.
                   9319: 
                   9320: =back
                   9321: 
                   9322: =item (Red) LocalConnection: caller is insane! init = <init> and type = <type>
                   9323: 
                   9324: The client is local but has not sent an initialization
                   9325: string that is the literal "init:local"  The connection
                   9326: is closed and the child exits.
                   9327: 
                   9328: =item Red CRITICAL Can't get key file <error>        
                   9329: 
                   9330: SSL key negotiation is being attempted but the call to
1.549     raeburn  9331: lonssl::KeyFile failed.  This usually means that the
1.409     foxr     9332: configuration file is not correctly defining or protecting
                   9333: the directories/files lonCertificateDirectory or
                   9334: lonnetPrivateKey
                   9335: <error> is a string that describes the reason that
                   9336: the key file could not be located.
                   9337: 
                   9338: =item (Red) CRITICAL  Can't get certificates <error>  
                   9339: 
                   9340: SSL key negotiation failed because we were not able to retrives our certificate
                   9341: or the CA's certificate in the call to lonssl::CertificateFile
                   9342: <error> is the textual reason this failed.  Usual reasons:
                   9343: 
                   9344: =over 2
1.490     droeschl 9345: 
1.409     foxr     9346: =item Apache config file for loncapa  incorrect:
1.490     droeschl 9347: 
1.409     foxr     9348: one of the variables 
                   9349: lonCertificateDirectory, lonnetCertificateAuthority, or lonnetCertificate
                   9350: undefined or incorrect
                   9351: 
                   9352: =item Permission error:
                   9353: 
                   9354: The directory pointed to by lonCertificateDirectory is not readable by lond
                   9355: 
                   9356: =item Permission error:
                   9357: 
                   9358: Files in the directory pointed to by lonCertificateDirectory are not readable by lond.
                   9359: 
                   9360: =item Installation error:                         
                   9361: 
                   9362: Either the certificate authority file or the certificate have not
                   9363: been installed in lonCertificateDirectory.
                   9364: 
                   9365: =item (Red) CRITICAL SSL Socket promotion failed:  <err> 
                   9366: 
                   9367: The promotion of the connection from plaintext to SSL failed
                   9368: <err> is the reason for the failure.  There are two
                   9369: system calls involved in the promotion (one of which failed), 
                   9370: a dup to produce
                   9371: a second fd on the raw socket over which the encrypted data
                   9372: will flow and IO::SOcket::SSL->new_from_fd which creates
                   9373: the SSL connection on the duped fd.
                   9374: 
                   9375: =item (Blue)   WARNING client did not respond to challenge 
                   9376: 
                   9377: This occurs on an insecure (non SSL) connection negotiation request.
                   9378: lond generates some number from the time, the PID and sends it to
                   9379: the client.  The client must respond by echoing this information back.
                   9380: If the client does not do so, that's a violation of the challenge
                   9381: protocols and the connection will be failed.
                   9382: 
                   9383: =item (Red) No manager table. Nobody can manage!!    
                   9384: 
                   9385: lond has the concept of privileged hosts that
                   9386: can perform remote management function such
                   9387: as update the hosts.tab.   The manager hosts
                   9388: are described in the 
                   9389: ~httpd/lonTabs/managers.tab file.
                   9390: this message is logged if this file is missing.
                   9391: 
                   9392: 
                   9393: =item (Green) Registering manager <dnsname> as <cluster_name> with <ipaddress>
                   9394: 
                   9395: Reports the successful parse and registration
                   9396: of a specific manager. 
                   9397: 
                   9398: =item Green existing host <clustername:dnsname>  
                   9399: 
                   9400: The manager host is already defined in the hosts.tab
                   9401: the information in that table, rather than the info in the
                   9402: manager table will be used to determine the manager's ip.
                   9403: 
                   9404: =item (Red) Unable to craete <filename>                 
                   9405: 
                   9406: lond has been asked to create new versions of an administrative
                   9407: file (by a manager).  When this is done, the new file is created
                   9408: in a temp file and then renamed into place so that there are always
                   9409: usable administrative files, even if the update fails.  This failure
                   9410: message means that the temp file could not be created.
                   9411: The update is abandoned, and the old file is available for use.
                   9412: 
                   9413: =item (Green) CopyFile from <oldname> to <newname> failed
                   9414: 
                   9415: In an update of administrative files, the copy of the existing file to a
                   9416: backup file failed.  The installation of the new file may still succeed,
                   9417: but there will not be a back up file to rever to (this should probably
                   9418: be yellow).
                   9419: 
                   9420: =item (Green) Pushfile: backed up <oldname> to <newname>
                   9421: 
                   9422: See above, the backup of the old administrative file succeeded.
                   9423: 
                   9424: =item (Red)  Pushfile: Unable to install <filename> <reason>
                   9425: 
                   9426: The new administrative file could not be installed.  In this case,
                   9427: the old administrative file is still in use.
                   9428: 
                   9429: =item (Green) Installed new < filename>.                      
                   9430: 
                   9431: The new administrative file was successfullly installed.                                               
                   9432: 
                   9433: =item (Red) Reinitializing lond pid=<pid>                    
                   9434: 
                   9435: The lonc child process <pid> will be sent a USR2 
                   9436: signal.
                   9437: 
                   9438: =item (Red) Reinitializing self                                    
                   9439: 
                   9440: We've been asked to re-read our administrative files,and
                   9441: are doing so.
                   9442: 
                   9443: =item (Yellow) error:Invalid process identifier <ident>  
                   9444: 
                   9445: A reinit command was received, but the target part of the 
                   9446: command was not valid.  It must be either
                   9447: 'lond' or 'lonc' but was <ident>
                   9448: 
                   9449: =item (Green) isValideditCommand checking: Command = <command> Key = <key> newline = <newline>
                   9450: 
                   9451: Checking to see if lond has been handed a valid edit
                   9452: command.  It is possible the edit command is not valid
                   9453: in that case there are no log messages to indicate that.
                   9454: 
                   9455: =item Result of password change for  <username> pwchange_success
                   9456: 
                   9457: The password for <username> was
                   9458: successfully changed.
                   9459: 
                   9460: =item Unable to open <user> passwd to change password
                   9461: 
                   9462: Could not rewrite the 
                   9463: internal password file for a user
                   9464: 
                   9465: =item Result of password change for <user> : <result>
1.490     droeschl 9466: 
1.409     foxr     9467: A unix password change for <user> was attempted 
                   9468: and the pipe returned <result>  
                   9469: 
                   9470: =item LWP GET: <message> for <fname> (<remoteurl>)
                   9471: 
                   9472: The lightweight process fetch for a resource failed
                   9473: with <message> the local filename that should
                   9474: have existed/been created was  <fname> the
                   9475: corresponding URI: <remoteurl>  This is emitted in several
                   9476: places.
                   9477: 
                   9478: =item Unable to move <transname> to <destname>     
                   9479: 
                   9480: From fetch_user_file_handler - the user file was replicated but could not
                   9481: be mv'd to its final location.
                   9482: 
                   9483: =item Looking for <domain> <username>              
                   9484: 
                   9485: From user_has_session_handler - This should be a Debug call instead
                   9486: it indicates lond is about to check whether the specified user has a 
                   9487: session active on the specified domain on the local host.
                   9488: 
                   9489: =item Client <ip> (<name>) hanging up: <input>     
                   9490: 
                   9491: lond has been asked to exit by its client.  The <ip> and <name> identify the
                   9492: client systemand <input> is the full exit command sent to the server.
                   9493: 
                   9494: =item Red CRITICAL: ABNORMAL EXIT. child <pid> for server <hostname> died through a crass with this error->[<message>].
1.490     droeschl 9495: 
1.409     foxr     9496: A lond child terminated.  NOte that this termination can also occur when the
                   9497: child receives the QUIT or DIE signals.  <pid> is the process id of the child,
                   9498: <hostname> the host lond is working for, and <message> the reason the child died
                   9499: to the best of our ability to get it (I would guess that any numeric value
                   9500: represents and errno value).  This is immediately followed by
                   9501: 
                   9502: =item  Famous last words: Catching exception - <log> 
                   9503: 
                   9504: Where log is some recent information about the state of the child.
                   9505: 
                   9506: =item Red CRITICAL: TIME OUT <pid>                     
                   9507: 
                   9508: Some timeout occured for server <pid>.  THis is normally a timeout on an LWP
                   9509: doing an HTTP::GET.
                   9510: 
                   9511: =item child <pid> died                              
                   9512: 
                   9513: The reaper caught a SIGCHILD for the lond child process <pid>
                   9514: This should be modified to also display the IP of the dying child
                   9515: $children{$pid}
                   9516: 
                   9517: =item Unknown child 0 died                           
                   9518: A child died but the wait for it returned a pid of zero which really should not
                   9519: ever happen. 
                   9520: 
                   9521: =item Child <which> - <pid> looks like we missed it's death 
                   9522: 
                   9523: When a sigchild is received, the reaper process checks all children to see if they are
                   9524: alive.  If children are dying quite quickly, the lack of signal queuing can mean
                   9525: that a signal hearalds the death of more than one child.  If so this message indicates
                   9526: which other one died. <which> is the ip of a dead child
                   9527: 
                   9528: =item Free socket: <shutdownretval>                
                   9529: 
                   9530: The HUNTSMAN sub was called due to a SIGINT in a child process.  The socket is being shutdown.
                   9531: for whatever reason, <shutdownretval> is printed but in fact shutdown() is not documented
                   9532: to return anything. This is followed by: 
                   9533: 
                   9534: =item Red CRITICAL: Shutting down                       
                   9535: 
                   9536: Just prior to exit.
                   9537: 
                   9538: =item Free socket: <shutdownretval>                 
                   9539: 
                   9540: The HUPSMAN sub was called due to a SIGHUP.  all children get killsed, and lond execs itself.
                   9541: This is followed by:
                   9542: 
                   9543: =item (Red) CRITICAL: Restarting                         
                   9544: 
                   9545: lond is about to exec itself to restart.
                   9546: 
                   9547: =item (Blue) Updating connections                        
                   9548: 
                   9549: (In response to a USR2).  All the children (except the one for localhost)
                   9550: are about to be killed, the hosts tab reread, and Apache reloaded via apachereload.
                   9551: 
                   9552: =item (Blue) UpdateHosts killing child <pid> for ip <ip>   
                   9553: 
                   9554: Due to USR2 as above.
                   9555: 
                   9556: =item (Green) keeping child for ip <ip> (pid = <pid>)    
                   9557: 
                   9558: In response to USR2 as above, the child indicated is not being restarted because
                   9559: it's assumed that we'll always need a child for the localhost.
                   9560: 
                   9561: 
                   9562: =item Going to check on the children                
                   9563: 
                   9564: Parent is about to check on the health of the child processes.
                   9565: Note that this is in response to a USR1 sent to the parent lond.
                   9566: there may be one or more of the next two messages:
                   9567: 
                   9568: =item <pid> is dead                                 
                   9569: 
                   9570: A child that we have in our child hash as alive has evidently died.
                   9571: 
                   9572: =item  Child <pid> did not respond                   
                   9573: 
                   9574: In the health check the child <pid> did not update/produce a pid_.txt
                   9575: file when sent it's USR1 signal.  That process is killed with a 9 signal, as it's
                   9576: assumed to be hung in some un-fixable way.
                   9577: 
                   9578: =item Finished checking children                   
1.490     droeschl 9579: 
1.409     foxr     9580: Master processs's USR1 processing is cojmplete.
                   9581: 
                   9582: =item (Red) CRITICAL: ------- Starting ------            
                   9583: 
                   9584: (There are more '-'s on either side).  Lond has forked itself off to 
                   9585: form a new session and is about to start actual initialization.
                   9586: 
                   9587: =item (Green) Attempting to start child (<client>)       
                   9588: 
                   9589: Started a new child process for <client>.  Client is IO::Socket object
                   9590: connected to the child.  This was as a result of a TCP/IP connection from a client.
                   9591: 
                   9592: =item Unable to determine who caller was, getpeername returned nothing
1.490     droeschl 9593: 
1.409     foxr     9594: In child process initialization.  either getpeername returned undef or
                   9595: a zero sized object was returned.  Processing continues, but in my opinion,
                   9596: this should be cause for the child to exit.
                   9597: 
                   9598: =item Unable to determine clientip                  
                   9599: 
                   9600: In child process initialization.  The peer address from getpeername was not defined.
                   9601: The client address is stored as "Unavailable" and processing continues.
                   9602: 
                   9603: =item (Yellow) INFO: Connection <ip> <name> connection type = <type>
1.490     droeschl 9604: 
1.409     foxr     9605: In child initialization.  A good connectionw as received from <ip>.
                   9606: 
                   9607: =over 2
                   9608: 
                   9609: =item <name> 
                   9610: 
                   9611: is the name of the client from hosts.tab.
                   9612: 
                   9613: =item <type> 
                   9614: 
                   9615: Is the connection type which is either 
                   9616: 
                   9617: =over 2
                   9618: 
                   9619: =item manager 
                   9620: 
                   9621: The connection is from a manager node, not in hosts.tab
                   9622: 
                   9623: =item client  
                   9624: 
                   9625: the connection is from a non-manager in the hosts.tab
                   9626: 
                   9627: =item both
                   9628: 
                   9629: The connection is from a manager in the hosts.tab.
                   9630: 
                   9631: =back
                   9632: 
                   9633: =back
                   9634: 
                   9635: =item (Blue) Certificates not installed -- trying insecure auth
                   9636: 
                   9637: One of the certificate file, key file or
                   9638: certificate authority file could not be found for a client attempting
                   9639: SSL connection intiation.  COnnection will be attemptied in in-secure mode.
                   9640: (this would be a system with an up to date lond that has not gotten a 
                   9641: certificate from us).
                   9642: 
                   9643: =item (Green)  Successful local authentication            
                   9644: 
                   9645: A local connection successfully negotiated the encryption key. 
                   9646: In this case the IDEA key is in a file (that is hopefully well protected).
                   9647: 
                   9648: =item (Green) Successful ssl authentication with <client>  
                   9649: 
                   9650: The client (<client> is the peer's name in hosts.tab), has successfully
                   9651: negotiated an SSL connection with this child process.
                   9652: 
                   9653: =item (Green) Successful insecure authentication with <client>
1.490     droeschl 9654: 
1.409     foxr     9655: 
                   9656: The client has successfully negotiated an  insecure connection withthe child process.
                   9657: 
                   9658: =item (Yellow) Attempted insecure connection disallowed    
                   9659: 
                   9660: The client attempted and failed to successfully negotiate a successful insecure
                   9661: connection.  This can happen either because the variable londAllowInsecure is false
                   9662: or undefined, or becuse the child did not successfully echo back the challenge
                   9663: string.
                   9664: 
                   9665: 
                   9666: =back
                   9667: 
1.441     raeburn  9668: =back
                   9669: 
1.409     foxr     9670: 
                   9671: =cut

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