Annotation of loncom/lond, revision 1.570

1.1       albertel    1: #!/usr/bin/perl
                      2: # The LearningOnline Network
                      3: # lond "LON Daemon" Server (port "LOND" 5663)
1.60      www         4: #
1.570   ! raeburn     5: # $Id: lond,v 1.569 2021/10/26 15:52:55 raeburn Exp $
1.60      www         6: #
                      7: # Copyright Michigan State University Board of Trustees
                      8: #
                      9: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                     10: #
                     11: # LON-CAPA is free software; you can redistribute it and/or modify
                     12: # it under the terms of the GNU General Public License as published by
1.167     foxr       13: # the Free Software Foundation; either version 2 of the License, or 
1.60      www        14: # (at your option) any later version.
                     15: #
                     16: # LON-CAPA is distributed in the hope that it will be useful,
                     17: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     18: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     19: # GNU General Public License for more details.
                     20: #
                     21: # You should have received a copy of the GNU General Public License
                     22: # along with LON-CAPA; if not, write to the Free Software
1.178     foxr       23: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
1.60      www        24: #
                     25: # /home/httpd/html/adm/gpl.txt
                     26: #
1.161     foxr       27: 
                     28: 
1.60      www        29: # http://www.lon-capa.org/
                     30: #
1.54      harris41   31: 
1.134     albertel   32: use strict;
1.80      harris41   33: use lib '/home/httpd/lib/perl/';
1.325     albertel   34: use LONCAPA;
1.80      harris41   35: use LONCAPA::Configuration;
1.490     droeschl   36: use LONCAPA::Lond;
1.80      harris41   37: 
1.532     raeburn    38: use Socket;
1.1       albertel   39: use IO::Socket;
                     40: use IO::File;
1.126     albertel   41: #use Apache::File;
1.1       albertel   42: use POSIX;
                     43: use Crypt::IDEA;
1.523     raeburn    44: use HTTP::Request;
1.347     raeburn    45: use Digest::MD5 qw(md5_hex);
1.3       www        46: use GDBM_File;
1.91      albertel   47: use Authen::Krb5;
1.49      albertel   48: use localauth;
1.193     raeburn    49: use localenroll;
1.265     albertel   50: use localstudentphoto;
1.143     foxr       51: use File::Copy;
1.292     albertel   52: use File::Find;
1.200     matthew    53: use LONCAPA::lonlocal;
                     54: use LONCAPA::lonssl;
1.221     albertel   55: use Fcntl qw(:flock);
1.383     raeburn    56: use Apache::lonnet;
1.472     raeburn    57: use Mail::Send;
1.518     raeburn    58: use Crypt::Eksblowfish::Bcrypt;
                     59: use Digest::SHA;
                     60: use Encode;
1.523     raeburn    61: use LONCAPA::LWPReq;
1.1       albertel   62: 
1.463     foxr       63: my $DEBUG = 0;		       # Non zero to enable debug log entries.
1.77      foxr       64: 
1.57      www        65: my $status='';
                     66: my $lastlog='';
                     67: 
1.570   ! raeburn    68: my $VERSION='$Revision: 1.569 $'; #' 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.570   ! raeburn  2039:                         if ($dist =~ /^(centos|rhes|fedora|scientific|oracle|rocky|alma)/) {
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.569     raeburn  5612:     my $numtries = 0;
                   5613:     my $execdir=$perlvar{'lonDaemons'};
                   5614:     if (($context eq 'resetpw') || ($context eq 'createaccount') ||
                   5615:         ($context eq 'sso') || ($context eq 'link') || ($context eq 'retry')) {
                   5616:         $id = &md5_hex(&md5_hex(time.{}.rand().$$.$tmpsnum));
                   5617:         while ((-e "$execdir/tmp/$id.tmp") && ($numtries <10)) {
                   5618:             undef($id);
                   5619:             $id = &md5_hex(&md5_hex(time.{}.rand().$$.$tmpsnum));
                   5620:             $numtries ++;
                   5621:         }
1.347     raeburn  5622:     } else {
                   5623:         $id = $$.'_'.$clientip.'_'.$tmpsnum;
                   5624:     }
1.238     foxr     5625:     $id=~s/\W/\_/g;
1.347     raeburn  5626:     $record=~s/\n//g;
1.569     raeburn  5627:     if (($id ne '') &&
                   5628:         ($store=IO::File->new(">$execdir/tmp/$id.tmp"))) {
1.347     raeburn  5629: 	print $store $record;
1.238     foxr     5630: 	close $store;
1.387     albertel 5631: 	&Reply($client, \$id, $userinput);
1.238     foxr     5632:     } else {
                   5633: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   5634: 		  "while attempting tmpput\n", $userinput);
                   5635:     }
                   5636:     return 1;
                   5637:   
                   5638: }
                   5639: &register_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
1.263     albertel 5640: 
1.238     foxr     5641: #   Processes the tmpget command.  This command returns the contents
                   5642: #  of a temporary resource file(?) created via tmpput.
                   5643: #
                   5644: # Paramters:
                   5645: #    $cmd      - Command that got us dispatched.
                   5646: #    $id       - Tail of the command, contain the id of the resource
                   5647: #                we want to fetch.
                   5648: #    $client   - socket open on the client.
                   5649: # Return:
                   5650: #    1         - Inidcating processing can continue.
                   5651: # Side effects:
                   5652: #   A reply is sent to the client.
                   5653: #
                   5654: sub tmp_get_handler {
                   5655:     my ($cmd, $id, $client) = @_;
                   5656: 
                   5657:     my $userinput = "$cmd:$id"; 
                   5658:     
                   5659: 
                   5660:     $id=~s/\W/\_/g;
                   5661:     my $store;
                   5662:     my $execdir=$perlvar{'lonDaemons'};
                   5663:     if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
                   5664: 	my $reply=<$store>;
1.387     albertel 5665: 	&Reply( $client, \$reply, $userinput);
1.238     foxr     5666: 	close $store;
                   5667:     } else {
                   5668: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   5669: 		  "while attempting tmpget\n", $userinput);
                   5670:     }
                   5671: 
                   5672:     return 1;
                   5673: }
                   5674: &register_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
1.263     albertel 5675: 
1.238     foxr     5676: #
                   5677: #  Process the tmpdel command.  This command deletes a temp resource
                   5678: #  created by the tmpput command.
                   5679: #
                   5680: # Parameters:
                   5681: #   $cmd      - Command that got us here.
                   5682: #   $id       - Id of the temporary resource created.
                   5683: #   $client   - socket open on the client process.
                   5684: #
                   5685: # Returns:
                   5686: #   1     - Indicating processing should continue.
                   5687: # Side Effects:
                   5688: #   A file is deleted
                   5689: #   A reply is sent to the client.
                   5690: sub tmp_del_handler {
                   5691:     my ($cmd, $id, $client) = @_;
                   5692:     
                   5693:     my $userinput= "$cmd:$id";
                   5694:     
                   5695:     chomp($id);
                   5696:     $id=~s/\W/\_/g;
                   5697:     my $execdir=$perlvar{'lonDaemons'};
                   5698:     if (unlink("$execdir/tmp/$id.tmp")) {
                   5699: 	&Reply($client, "ok\n", $userinput);
                   5700:     } else {
                   5701: 	&Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
                   5702: 		  "while attempting tmpdel\n", $userinput);
                   5703:     }
                   5704:     
                   5705:     return 1;
                   5706: 
                   5707: }
                   5708: &register_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
1.263     albertel 5709: 
1.238     foxr     5710: #
1.564     raeburn  5711: #  Process the updatebalcookie command.  This command updates a
                   5712: #  cookie in the lonBalancedir directory on a load balancer node.
                   5713: #
                   5714: # Parameters:
                   5715: #   $cmd      - Command that got us here.
                   5716: #   $tail     - Tail of the request (escaped cookie: escaped current entry)
                   5717: #
                   5718: #   $client   - socket open on the client process.
                   5719: #
                   5720: # Returns:
                   5721: #   1     - Indicating processing should continue.
                   5722: # Side Effects:
                   5723: #   A cookie file is updated from the lonBalancedir directory
                   5724: #   A reply is sent to the client.
                   5725: #
                   5726: sub update_balcookie_handler {
                   5727:     my ($cmd, $tail, $client) = @_;
                   5728: 
                   5729:     my $userinput= "$cmd:$tail";
                   5730:     chomp($tail);
                   5731:     my ($cookie,$lastentry) = map { &unescape($_) } (split(/:/,$tail));
                   5732: 
                   5733:     my $updatedone;
                   5734:     if ($cookie =~ /^$LONCAPA::match_domain\_$LONCAPA::match_username\_[a-f0-9]{32}$/) {
                   5735:         my $execdir=$perlvar{'lonBalanceDir'};
                   5736:         if (-e "$execdir/$cookie.id") {
                   5737:             my $doupdate;
                   5738:             if (open(my $fh,'<',"$execdir/$cookie.id")) {
                   5739:                 while (my $line = <$fh>) {
                   5740:                     chomp($line);
                   5741:                     if ($line eq $lastentry) {
                   5742:                         $doupdate = 1;
                   5743:                         last;
                   5744:                     }
                   5745:                 }
                   5746:                 close($fh);
                   5747:             }
                   5748:             if ($doupdate) {
                   5749:                 if (open(my $fh,'>',"$execdir/$cookie.id")) {
                   5750:                     print $fh $clientname;
                   5751:                     close($fh);
                   5752:                     $updatedone = 1;
                   5753:                 }
                   5754:             }
                   5755:         }
                   5756:     }
                   5757:     if ($updatedone) {
                   5758:         &Reply($client, "ok\n", $userinput);
                   5759:     } else {
                   5760:         &Failure( $client, "error: ".($!+0)."file update failed ".
                   5761:                   "while attempting updatebalcookie\n", $userinput);
                   5762:     }
                   5763:     return 1;
                   5764: }
                   5765: &register_handler("updatebalcookie", \&update_balcookie_handler, 0, 1, 0);
                   5766: 
                   5767: #
1.551     raeburn  5768: #  Process the delbalcookie command. This command deletes a balancer
1.564     raeburn  5769: #  cookie in the lonBalancedir directory on a load balancer node.
1.551     raeburn  5770: #
                   5771: # Parameters:
                   5772: #   $cmd      - Command that got us here.
                   5773: #   $cookie   - Cookie to be deleted.
                   5774: #   $client   - socket open on the client process.
                   5775: #
                   5776: # Returns:
                   5777: #   1     - Indicating processing should continue.
                   5778: # Side Effects:
                   5779: #   A cookie file is deleted from the lonBalancedir directory
                   5780: #   A reply is sent to the client.
                   5781: sub del_balcookie_handler {
                   5782:     my ($cmd, $cookie, $client) = @_;
                   5783: 
                   5784:     my $userinput= "$cmd:$cookie";
                   5785: 
                   5786:     chomp($cookie);
1.564     raeburn  5787:     $cookie = &unescape($cookie);
1.551     raeburn  5788:     my $deleted = '';
                   5789:     if ($cookie =~ /^$LONCAPA::match_domain\_$LONCAPA::match_username\_[a-f0-9]{32}$/) {
                   5790:         my $execdir=$perlvar{'lonBalanceDir'};
                   5791:         if (-e "$execdir/$cookie.id") {
                   5792:             if (open(my $fh,'<',"$execdir/$cookie.id")) {
                   5793:                 my $dodelete;
                   5794:                 while (my $line = <$fh>) {
                   5795:                     chomp($line);
                   5796:                     if ($line eq $clientname) {
                   5797:                         $dodelete = 1;
1.554     raeburn  5798:                         last;
1.551     raeburn  5799:                     }
                   5800:                 }
1.554     raeburn  5801:                 close($fh);
1.551     raeburn  5802:                 if ($dodelete) {
                   5803:                     if (unlink("$execdir/$cookie.id")) {
                   5804:                         $deleted = 1;
                   5805:                     }
                   5806:                 }
                   5807:             }
                   5808:         }
                   5809:     }
                   5810:     if ($deleted) {
                   5811:         &Reply($client, "ok\n", $userinput);
                   5812:     } else {
                   5813:         &Failure( $client, "error: ".($!+0)."Unlinking cookie file Failed ".
                   5814:                   "while attempting delbalcookie\n", $userinput);
                   5815:     }
                   5816:     return 1;
                   5817: }
                   5818: &register_handler("delbalcookie", \&del_balcookie_handler, 0, 1, 0);
                   5819: 
                   5820: #
1.246     foxr     5821: #   Processes the setannounce command.  This command
                   5822: #   creates a file named announce.txt in the top directory of
                   5823: #   the documentn root and sets its contents.  The announce.txt file is
                   5824: #   printed in its entirety at the LonCAPA login page.  Note:
                   5825: #   once the announcement.txt fileis created it cannot be deleted.
                   5826: #   However, setting the contents of the file to empty removes the
                   5827: #   announcement from the login page of loncapa so who cares.
                   5828: #
                   5829: # Parameters:
                   5830: #    $cmd          - The command that got us dispatched.
                   5831: #    $announcement - The text of the announcement.
                   5832: #    $client       - Socket open on the client process.
                   5833: # Retunrns:
                   5834: #   1             - Indicating request processing should continue
                   5835: # Side Effects:
                   5836: #   The file {DocRoot}/announcement.txt is created.
                   5837: #   A reply is sent to $client.
                   5838: #
                   5839: sub set_announce_handler {
                   5840:     my ($cmd, $announcement, $client) = @_;
                   5841:   
                   5842:     my $userinput    = "$cmd:$announcement";
                   5843: 
                   5844:     chomp($announcement);
                   5845:     $announcement=&unescape($announcement);
                   5846:     if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
                   5847: 				'/announcement.txt')) {
                   5848: 	print $store $announcement;
                   5849: 	close $store;
                   5850: 	&Reply($client, "ok\n", $userinput);
                   5851:     } else {
                   5852: 	&Failure($client, "error: ".($!+0)."\n", $userinput);
                   5853:     }
                   5854: 
                   5855:     return 1;
                   5856: }
                   5857: &register_handler("setannounce", \&set_announce_handler, 0, 1, 0);
1.263     albertel 5858: 
1.246     foxr     5859: #
                   5860: #  Return the version of the daemon.  This can be used to determine
                   5861: #  the compatibility of cross version installations or, alternatively to
                   5862: #  simply know who's out of date and who isn't.  Note that the version
                   5863: #  is returned concatenated with the tail.
                   5864: # Parameters:
                   5865: #   $cmd        - the request that dispatched to us.
                   5866: #   $tail       - Tail of the request (client's version?).
                   5867: #   $client     - Socket open on the client.
                   5868: #Returns:
                   5869: #   1 - continue processing requests.
                   5870: # Side Effects:
                   5871: #   Replies with version to $client.
                   5872: sub get_version_handler {
                   5873:     my ($cmd, $tail, $client) = @_;
                   5874: 
                   5875:     my $userinput  = $cmd.$tail;
                   5876:     
                   5877:     &Reply($client, &version($userinput)."\n", $userinput);
                   5878: 
                   5879: 
                   5880:     return 1;
                   5881: }
                   5882: &register_handler("version", \&get_version_handler, 0, 1, 0);
1.263     albertel 5883: 
1.246     foxr     5884: #  Set the current host and domain.  This is used to support
                   5885: #  multihomed systems.  Each IP of the system, or even separate daemons
                   5886: #  on the same IP can be treated as handling a separate lonCAPA virtual
                   5887: #  machine.  This command selects the virtual lonCAPA.  The client always
                   5888: #  knows the right one since it is lonc and it is selecting the domain/system
                   5889: #  from the hosts.tab file.
                   5890: # Parameters:
                   5891: #    $cmd      - Command that dispatched us.
                   5892: #    $tail     - Tail of the command (domain/host requested).
                   5893: #    $socket   - Socket open on the client.
                   5894: #
                   5895: # Returns:
                   5896: #     1   - Indicates the program should continue to process requests.
                   5897: # Side-effects:
                   5898: #     The default domain/system context is modified for this daemon.
                   5899: #     a reply is sent to the client.
                   5900: #
                   5901: sub set_virtual_host_handler {
                   5902:     my ($cmd, $tail, $socket) = @_;
                   5903:   
                   5904:     my $userinput  ="$cmd:$tail";
                   5905: 
                   5906:     &Reply($client, &sethost($userinput)."\n", $userinput);
                   5907: 
                   5908: 
                   5909:     return 1;
                   5910: }
1.247     albertel 5911: &register_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
1.246     foxr     5912: 
                   5913: #  Process a request to exit:
                   5914: #   - "bye" is sent to the client.
                   5915: #   - The client socket is shutdown and closed.
                   5916: #   - We indicate to the caller that we should exit.
                   5917: # Formal Parameters:
                   5918: #   $cmd                - The command that got us here.
                   5919: #   $tail               - Tail of the command (empty).
                   5920: #   $client             - Socket open on the tail.
                   5921: # Returns:
                   5922: #   0      - Indicating the program should exit!!
                   5923: #
                   5924: sub exit_handler {
                   5925:     my ($cmd, $tail, $client) = @_;
                   5926: 
                   5927:     my $userinput = "$cmd:$tail";
                   5928: 
                   5929:     &logthis("Client $clientip ($clientname) hanging up: $userinput");
                   5930:     &Reply($client, "bye\n", $userinput);
                   5931:     $client->shutdown(2);        # shutdown the socket forcibly.
                   5932:     $client->close();
                   5933: 
                   5934:     return 0;
                   5935: }
1.248     foxr     5936: &register_handler("exit", \&exit_handler, 0,1,1);
                   5937: &register_handler("init", \&exit_handler, 0,1,1);
                   5938: &register_handler("quit", \&exit_handler, 0,1,1);
                   5939: 
                   5940: #  Determine if auto-enrollment is enabled.
                   5941: #  Note that the original had what I believe to be a defect.
                   5942: #  The original returned 0 if the requestor was not a registerd client.
                   5943: #  It should return "refused".
                   5944: # Formal Parameters:
                   5945: #   $cmd       - The command that invoked us.
                   5946: #   $tail      - The tail of the command (Extra command parameters.
                   5947: #   $client    - The socket open on the client that issued the request.
                   5948: # Returns:
                   5949: #    1         - Indicating processing should continue.
                   5950: #
                   5951: sub enrollment_enabled_handler {
                   5952:     my ($cmd, $tail, $client) = @_;
                   5953:     my $userinput = $cmd.":".$tail; # For logging purposes.
                   5954: 
                   5955:     
1.337     albertel 5956:     my ($cdom) = split(/:/, $tail, 2);   # Domain we're asking about.
                   5957: 
1.248     foxr     5958:     my $outcome  = &localenroll::run($cdom);
1.387     albertel 5959:     &Reply($client, \$outcome, $userinput);
1.248     foxr     5960: 
                   5961:     return 1;
                   5962: }
                   5963: &register_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
                   5964: 
1.417     raeburn  5965: #
1.423     raeburn  5966: #   Validate an institutional code used for a LON-CAPA course.          
1.417     raeburn  5967: #
                   5968: # Formal Parameters:
                   5969: #   $cmd          - The command request that got us dispatched.
                   5970: #   $tail         - The tail of the command.  In this case,
                   5971: #                   this is a colon separated set of words that will be split
                   5972: #                   into:
1.424     raeburn  5973: #                        $dom      - The domain for which the check of 
                   5974: #                                    institutional course code will occur.
                   5975: #
                   5976: #                        $instcode - The institutional code for the course
                   5977: #                                    being requested, or validated for rights
                   5978: #                                    to request.
                   5979: #
                   5980: #                        $owner    - The course requestor (who will be the
                   5981: #                                    course owner, in the form username:domain
                   5982: #
1.417     raeburn  5983: #   $client       - Socket open on the client.
                   5984: # Returns:
                   5985: #    1           - Indicating processing should continue.
                   5986: #
                   5987: sub validate_instcode_handler {
                   5988:     my ($cmd, $tail, $client) = @_;
                   5989:     my $userinput = "$cmd:$tail";
1.423     raeburn  5990:     my ($dom,$instcode,$owner) = split(/:/, $tail);
1.422     raeburn  5991:     $instcode = &unescape($instcode);
                   5992:     $owner = &unescape($owner);
1.498     raeburn  5993:     my ($outcome,$description,$credits) = 
1.426     raeburn  5994:         &localenroll::validate_instcode($dom,$instcode,$owner);
1.498     raeburn  5995:     my $result = &escape($outcome).'&'.&escape($description).'&'.
                   5996:                  &escape($credits);
1.426     raeburn  5997:     &Reply($client, \$result, $userinput);
1.417     raeburn  5998: 
                   5999:     return 1;
                   6000: }
                   6001: &register_handler("autovalidateinstcode", \&validate_instcode_handler, 0, 1, 0);
                   6002: 
1.566     raeburn  6003: #
                   6004: #  Validate co-owner for cross-listed institutional code and
                   6005: #  institutional course code itself used for a LON-CAPA course.
                   6006: #
                   6007: # Formal Parameters:
                   6008: #   $cmd          - The command request that got us dispatched.
                   6009: #   $tail         - The tail of the command.  In this case,
                   6010: #                   this is a colon separated string containing:
                   6011: #      $dom            - Course's LON-CAPA domain
                   6012: #      $instcode       - Institutional course code for the course
                   6013: #      $inst_xlist     - Institutional course Id for the crosslisting
                   6014: #      $coowner        - Username of co-owner
                   6015: #      (values for all but $dom have been escaped). 
                   6016: #
                   6017: #   $client       - Socket open on the client.
                   6018: # Returns:
                   6019: #    1           - Indicating processing should continue.
                   6020: #
                   6021: sub validate_instcrosslist_handler  {
                   6022:     my ($cmd, $tail, $client) = @_;
                   6023:     my $userinput = "$cmd:$tail";
                   6024:     my ($dom,$instcode,$inst_xlist,$coowner) = split(/:/,$tail);
                   6025:     $instcode = &unescape($instcode);
                   6026:     $inst_xlist = &unescape($inst_xlist);
                   6027:     $coowner = &unescape($coowner);
                   6028:     my $outcome = &localenroll::validate_crosslist_access($dom,$instcode,
                   6029:                                                           $inst_xlist,$coowner);
                   6030:     &Reply($client, \$outcome, $userinput);
                   6031: 
                   6032:     return 1;
                   6033: }
                   6034: &register_handler("autovalidateinstcrosslist", \&validate_instcrosslist_handler, 0, 1, 0);
                   6035: 
1.248     foxr     6036: #   Get the official sections for which auto-enrollment is possible.
                   6037: #   Since the admin people won't know about 'unofficial sections' 
                   6038: #   we cannot auto-enroll on them.
                   6039: # Formal Parameters:
                   6040: #    $cmd     - The command request that got us dispatched here.
                   6041: #    $tail    - The remainder of the request.  In our case this
                   6042: #               will be split into:
                   6043: #               $coursecode   - The course name from the admin point of view.
                   6044: #               $cdom         - The course's domain(?).
                   6045: #    $client  - Socket open on the client.
                   6046: # Returns:
                   6047: #    1    - Indiciting processing should continue.
                   6048: #
                   6049: sub get_sections_handler {
                   6050:     my ($cmd, $tail, $client) = @_;
                   6051:     my $userinput = "$cmd:$tail";
                   6052: 
                   6053:     my ($coursecode, $cdom) = split(/:/, $tail);
                   6054:     my @secs = &localenroll::get_sections($coursecode,$cdom);
                   6055:     my $seclist = &escape(join(':',@secs));
                   6056: 
1.387     albertel 6057:     &Reply($client, \$seclist, $userinput);
1.248     foxr     6058:     
                   6059: 
                   6060:     return 1;
                   6061: }
                   6062: &register_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
                   6063: 
                   6064: #   Validate the owner of a new course section.  
                   6065: #
                   6066: # Formal Parameters:
                   6067: #   $cmd      - Command that got us dispatched.
                   6068: #   $tail     - the remainder of the command.  For us this consists of a
                   6069: #               colon separated string containing:
                   6070: #                  $inst    - Course Id from the institutions point of view.
                   6071: #                  $owner   - Proposed owner of the course.
                   6072: #                  $cdom    - Domain of the course (from the institutions
                   6073: #                             point of view?)..
                   6074: #   $client   - Socket open on the client.
                   6075: #
                   6076: # Returns:
                   6077: #   1        - Processing should continue.
                   6078: #
                   6079: sub validate_course_owner_handler {
                   6080:     my ($cmd, $tail, $client)  = @_;
                   6081:     my $userinput = "$cmd:$tail";
1.470     raeburn  6082:     my ($inst_course_id, $owner, $cdom, $coowners) = split(/:/, $tail);
                   6083:     
1.336     raeburn  6084:     $owner = &unescape($owner);
1.470     raeburn  6085:     $coowners = &unescape($coowners);
                   6086:     my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom,$coowners);
1.387     albertel 6087:     &Reply($client, \$outcome, $userinput);
1.248     foxr     6088: 
                   6089: 
                   6090: 
                   6091:     return 1;
                   6092: }
                   6093: &register_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
1.263     albertel 6094: 
1.248     foxr     6095: #
                   6096: #   Validate a course section in the official schedule of classes
                   6097: #   from the institutions point of view (part of autoenrollment).
                   6098: #
                   6099: # Formal Parameters:
                   6100: #   $cmd          - The command request that got us dispatched.
                   6101: #   $tail         - The tail of the command.  In this case,
                   6102: #                   this is a colon separated set of words that will be split
                   6103: #                   into:
                   6104: #                        $inst_course_id - The course/section id from the
                   6105: #                                          institutions point of view.
                   6106: #                        $cdom           - The domain from the institutions
                   6107: #                                          point of view.
                   6108: #   $client       - Socket open on the client.
                   6109: # Returns:
                   6110: #    1           - Indicating processing should continue.
                   6111: #
                   6112: sub validate_course_section_handler {
                   6113:     my ($cmd, $tail, $client) = @_;
                   6114:     my $userinput = "$cmd:$tail";
                   6115:     my ($inst_course_id, $cdom) = split(/:/, $tail);
                   6116: 
                   6117:     my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
1.387     albertel 6118:     &Reply($client, \$outcome, $userinput);
1.248     foxr     6119: 
                   6120: 
                   6121:     return 1;
                   6122: }
                   6123: &register_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
                   6124: 
                   6125: #
1.340     raeburn  6126: #   Validate course owner's access to enrollment data for specific class section. 
                   6127: #   
                   6128: #
                   6129: # Formal Parameters:
                   6130: #    $cmd     - The command request that got us dispatched.
                   6131: #    $tail    - The tail of the command.   In this case this is a colon separated
1.542     raeburn  6132: #               set of values that will be split into:
1.340     raeburn  6133: #               $inst_class  - Institutional code for the specific class section   
1.542     raeburn  6134: #               $ownerlist   - An escaped comma-separated list of username:domain 
                   6135: #                              of the course owner, and co-owner(s).
1.340     raeburn  6136: #               $cdom        - The domain of the course from the institution's
                   6137: #                              point of view.
                   6138: #    $client  - The socket open on the client.
                   6139: # Returns:
                   6140: #    1 - continue processing.
                   6141: #
                   6142: 
                   6143: sub validate_class_access_handler {
                   6144:     my ($cmd, $tail, $client) = @_;
                   6145:     my $userinput = "$cmd:$tail";
1.383     raeburn  6146:     my ($inst_class,$ownerlist,$cdom) = split(/:/, $tail);
1.392     raeburn  6147:     my $owners = &unescape($ownerlist);
1.341     albertel 6148:     my $outcome;
                   6149:     eval {
                   6150: 	local($SIG{__DIE__})='DEFAULT';
1.392     raeburn  6151: 	$outcome=&localenroll::check_section($inst_class,$owners,$cdom);
1.341     albertel 6152:     };
1.387     albertel 6153:     &Reply($client,\$outcome, $userinput);
1.340     raeburn  6154: 
                   6155:     return 1;
                   6156: }
                   6157: &register_handler("autovalidateclass_sec", \&validate_class_access_handler, 0, 1, 0);
                   6158: 
                   6159: #
1.567     raeburn  6160: #    Modify institutional sections (using customized &instsec_reformat()
                   6161: #    routine in localenroll.pm), to either clutter or declutter, for  
                   6162: #    purposes of ensuring an institutional course section (string) can
                   6163: #    be unambiguously separated into institutional course and section.
                   6164: #
                   6165: # Formal Parameters:
                   6166: #    $cmd     - The command request that got us dispatched.
                   6167: #    $tail    - The tail of the command.   In this case this is a colon separated
                   6168: #               set of values that will be split into:
                   6169: #               $cdom        - The LON-CAPA domain of the course.
                   6170: #               $action      - Either: clutter or declutter
                   6171: #                              clutter adds character(s) to eliminate ambiguity
                   6172: #                              declutter removes the added characters (e.g., for
                   6173: #                              display of the institutional course section string.
                   6174: #               $info        - A frozen hash in which keys are: 
                   6175: #                              LON-CAPA course number:Institutional course code
                   6176: #                              and values are a reference to an array of the
                   6177: #                              items to modify -- either institutional sections,
                   6178: #                              or institutional course sections (for crosslistings). 
                   6179: #    $client  - The socket open on the client.
                   6180: # Returns:
                   6181: #    1 - continue processing.
                   6182: #   
                   6183: 
                   6184: sub instsec_reformat_handler {
                   6185:     my ($cmd, $tail, $client) = @_;
                   6186:     my $userinput = "$cmd:$tail";
                   6187:     my ($cdom,$action,$info) = split(/:/,$tail);
                   6188:     my $instsecref = &Apache::lonnet::thaw_unescape($info);
                   6189:     my ($outcome,$result);
                   6190:     eval {
                   6191:         local($SIG{__DIE__})='DEFAULT';
                   6192:         $outcome=&localenroll::instsec_reformat($cdom,$action,$instsecref);
                   6193:         if ($outcome eq 'ok') {
                   6194:             if (ref($instsecref) eq 'HASH') {
                   6195:                 foreach my $key (keys(%{$instsecref})) {
                   6196:                     $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($instsecref->{$key}).'&';
                   6197:                 }
                   6198:                 $result =~ s/\&$//;
                   6199:             }
                   6200:         }
                   6201:     };
                   6202:     if (!$@) {
                   6203:         if ($outcome eq 'ok') {
                   6204:             &Reply( $client, \$result, $userinput);
                   6205:         } else {
                   6206:             &Reply($client,\$outcome, $userinput);
                   6207:         }
                   6208:     } else {
                   6209:         &Failure($client,"unknown_cmd\n",$userinput);
                   6210:     }
                   6211:     return 1;
                   6212: }
                   6213: &register_handler("autoinstsecreformat",\&instsec_reformat_handler, 0, 1, 0);
                   6214: 
                   6215: #
1.542     raeburn  6216: #   Validate course owner or co-owners(s) access to enrollment data for all sections
                   6217: #   and crosslistings for a particular course.
                   6218: #
                   6219: #
                   6220: # Formal Parameters:
                   6221: #    $cmd     - The command request that got us dispatched.
                   6222: #    $tail    - The tail of the command.   In this case this is a colon separated
                   6223: #               set of values that will be split into:
                   6224: #               $ownerlist   - An escaped comma-separated list of username:domain
                   6225: #                              of the course owner, and co-owner(s).
                   6226: #               $cdom        - The domain of the course from the institution's
                   6227: #                              point of view.
                   6228: #               $classes     - Frozen hash of institutional course sections and
                   6229: #                              crosslistings.
                   6230: #    $client  - The socket open on the client.
                   6231: # Returns:
                   6232: #    1 - continue processing.
                   6233: #
                   6234: 
                   6235: sub validate_classes_handler {
                   6236:     my ($cmd, $tail, $client) = @_;
                   6237:     my $userinput = "$cmd:$tail";
                   6238:     my ($ownerlist,$cdom,$classes) = split(/:/, $tail);
                   6239:     my $classesref = &Apache::lonnet::thaw_unescape($classes);
                   6240:     my $owners = &unescape($ownerlist);
                   6241:     my $result;
                   6242:     eval {
                   6243:         local($SIG{__DIE__})='DEFAULT';
                   6244:         my %validations;
                   6245:         my $response = &localenroll::check_instclasses($owners,$cdom,$classesref,
                   6246:                                                        \%validations);
                   6247:         if ($response eq 'ok') {
                   6248:             foreach my $key (keys(%validations)) {
                   6249:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
                   6250:             }
                   6251:             $result =~ s/\&$//;
                   6252:         } else {
                   6253:             $result = 'error';
                   6254:         }
                   6255:     };
                   6256:     if (!$@) {
                   6257:         &Reply($client, \$result, $userinput);
                   6258:     } else {
                   6259:         &Failure($client,"unknown_cmd\n",$userinput);
                   6260:     }
                   6261:     return 1;
                   6262: }
                   6263: &register_handler("autovalidateinstclasses", \&validate_classes_handler, 0, 1, 0);
                   6264: 
                   6265: #
1.340     raeburn  6266: #   Create a password for a new LON-CAPA user added by auto-enrollment.
                   6267: #   Only used for case where authentication method for new user is localauth
1.248     foxr     6268: #
                   6269: # Formal Parameters:
                   6270: #    $cmd     - The command request that got us dispatched.
                   6271: #    $tail    - The tail of the command.   In this case this is a colon separated
                   6272: #               set of words that will be split into:
1.340     raeburn  6273: #               $authparam - An authentication parameter (localauth parameter).
1.248     foxr     6274: #               $cdom      - The domain of the course from the institution's
                   6275: #                            point of view.
                   6276: #    $client  - The socket open on the client.
                   6277: # Returns:
                   6278: #    1 - continue processing.
                   6279: #
                   6280: sub create_auto_enroll_password_handler {
                   6281:     my ($cmd, $tail, $client) = @_;
                   6282:     my $userinput = "$cmd:$tail";
                   6283: 
                   6284:     my ($authparam, $cdom) = split(/:/, $userinput);
                   6285: 
                   6286:     my ($create_passwd,$authchk);
                   6287:     ($authparam,
                   6288:      $create_passwd,
                   6289:      $authchk) = &localenroll::create_password($authparam,$cdom);
                   6290: 
                   6291:     &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
                   6292: 	   $userinput);
                   6293: 
                   6294: 
                   6295:     return 1;
                   6296: }
                   6297: &register_handler("autocreatepassword", \&create_auto_enroll_password_handler, 
                   6298: 		  0, 1, 0);
                   6299: 
1.522     raeburn  6300: sub auto_export_grades_handler {
                   6301:     my ($cmd, $tail, $client) = @_;
                   6302:     my $userinput = "$cmd:$tail";
                   6303:     my ($cdom,$cnum,$info,$data) = split(/:/,$tail);
                   6304:     my $inforef = &Apache::lonnet::thaw_unescape($info);
                   6305:     my $dataref = &Apache::lonnet::thaw_unescape($data);
                   6306:     my ($outcome,$result);;
                   6307:     eval {
                   6308:         local($SIG{__DIE__})='DEFAULT';
                   6309:         my %rtnhash;
                   6310:         $outcome=&localenroll::export_grades($cdom,$cnum,$inforef,$dataref,\%rtnhash);
                   6311:         if ($outcome eq 'ok') {
                   6312:             foreach my $key (keys(%rtnhash)) {
                   6313:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
                   6314:             }
                   6315:             $result =~ s/\&$//;
                   6316:         }
                   6317:     };
                   6318:     if (!$@) {
                   6319:         if ($outcome eq 'ok') {
                   6320:             if ($cipher) {
                   6321:                 my $cmdlength=length($result);
                   6322:                 $result.="         ";
                   6323:                 my $encresult='';
                   6324:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   6325:                     $encresult.= unpack("H16",
                   6326:                                         $cipher->encrypt(substr($result,
                   6327:                                                                 $encidx,
                   6328:                                                                 8)));
                   6329:                 }
                   6330:                 &Reply( $client, "enc:$cmdlength:$encresult\n", $userinput);
                   6331:             } else {
                   6332:                 &Failure( $client, "error:no_key\n", $userinput);
                   6333:             }
                   6334:         } else {
                   6335:             &Reply($client, "$outcome\n", $userinput);
                   6336:         }
                   6337:     } else {
                   6338:         &Failure($client,"export_error\n",$userinput);
                   6339:     }
                   6340:     return 1;
                   6341: }
                   6342: &register_handler("autoexportgrades", \&auto_export_grades_handler,
1.536     raeburn  6343:                   1, 1, 0);
1.522     raeburn  6344: 
1.248     foxr     6345: #   Retrieve and remove temporary files created by/during autoenrollment.
                   6346: #
                   6347: # Formal Parameters:
                   6348: #    $cmd      - The command that got us dispatched.
                   6349: #    $tail     - The tail of the command.  In our case this is a colon 
                   6350: #                separated list that will be split into:
1.526     raeburn  6351: #                $filename - The name of the file to retrieve.
1.248     foxr     6352: #                            The filename is given as a path relative to
                   6353: #                            the LonCAPA temp file directory.
                   6354: #    $client   - Socket open on the client.
                   6355: #
                   6356: # Returns:
                   6357: #   1     - Continue processing.
                   6358: sub retrieve_auto_file_handler {
                   6359:     my ($cmd, $tail, $client)    = @_;
                   6360:     my $userinput                = "cmd:$tail";
                   6361: 
                   6362:     my ($filename)   = split(/:/, $tail);
                   6363: 
                   6364:     my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
1.521     raeburn  6365: 
                   6366:     if ($filename =~m{/\.\./}) {
                   6367:         &Failure($client, "refused\n", $userinput);
1.526     raeburn  6368:     } elsif ($filename !~ /^$LONCAPA::match_domain\_$LONCAPA::match_courseid\_.+_classlist\.xml$/) {
                   6369:         &Failure($client, "refused\n", $userinput);
1.521     raeburn  6370:     } elsif ( (-e $source) && ($filename ne '') ) {
1.248     foxr     6371: 	my $reply = '';
                   6372: 	if (open(my $fh,$source)) {
                   6373: 	    while (<$fh>) {
                   6374: 		chomp($_);
                   6375: 		$_ =~ s/^\s+//g;
                   6376: 		$_ =~ s/\s+$//g;
                   6377: 		$reply .= $_;
                   6378: 	    }
                   6379: 	    close($fh);
                   6380: 	    &Reply($client, &escape($reply)."\n", $userinput);
                   6381: 
                   6382: #   Does this have to be uncommented??!?  (RF).
                   6383: #
                   6384: #                                unlink($source);
                   6385: 	} else {
                   6386: 	    &Failure($client, "error\n", $userinput);
                   6387: 	}
                   6388:     } else {
                   6389: 	&Failure($client, "error\n", $userinput);
                   6390:     }
                   6391:     
                   6392: 
                   6393:     return 1;
                   6394: }
                   6395: &register_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
                   6396: 
1.423     raeburn  6397: sub crsreq_checks_handler {
                   6398:     my ($cmd, $tail, $client) = @_;
                   6399:     my $userinput = "$cmd:$tail";
                   6400:     my $dom = $tail;
                   6401:     my $result;
1.519     raeburn  6402:     my @reqtypes = ('official','unofficial','community','textbook','placement');
1.423     raeburn  6403:     eval {
                   6404:         local($SIG{__DIE__})='DEFAULT';
                   6405:         my %validations;
1.424     raeburn  6406:         my $response = &localenroll::crsreq_checks($dom,\@reqtypes,
                   6407:                                                    \%validations);
1.423     raeburn  6408:         if ($response eq 'ok') { 
                   6409:             foreach my $key (keys(%validations)) {
                   6410:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
                   6411:             }
                   6412:             $result =~ s/\&$//;
                   6413:         } else {
                   6414:             $result = 'error';
                   6415:         }
                   6416:     };
                   6417:     if (!$@) {
                   6418:         &Reply($client, \$result, $userinput);
                   6419:     } else {
                   6420:         &Failure($client,"unknown_cmd\n",$userinput);
                   6421:     }
                   6422:     return 1;
                   6423: }
                   6424: &register_handler("autocrsreqchecks", \&crsreq_checks_handler, 0, 1, 0);
                   6425: 
                   6426: sub validate_crsreq_handler {
                   6427:     my ($cmd, $tail, $client) = @_;
                   6428:     my $userinput = "$cmd:$tail";
1.508     raeburn  6429:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$customdata) = split(/:/, $tail);
1.423     raeburn  6430:     $instcode = &unescape($instcode);
                   6431:     $owner = &unescape($owner);
                   6432:     $crstype = &unescape($crstype);
                   6433:     $inststatuslist = &unescape($inststatuslist);
                   6434:     $instcode = &unescape($instcode);
                   6435:     $instseclist = &unescape($instseclist);
1.508     raeburn  6436:     my $custominfo = &Apache::lonnet::thaw_unescape($customdata);
1.423     raeburn  6437:     my $outcome;
                   6438:     eval {
                   6439:         local($SIG{__DIE__})='DEFAULT';
                   6440:         $outcome = &localenroll::validate_crsreq($dom,$owner,$crstype,
                   6441:                                                  $inststatuslist,$instcode,
1.508     raeburn  6442:                                                  $instseclist,$custominfo);
1.423     raeburn  6443:     };
                   6444:     if (!$@) {
                   6445:         &Reply($client, \$outcome, $userinput);
                   6446:     } else {
                   6447:         &Failure($client,"unknown_cmd\n",$userinput);
                   6448:     }
                   6449:     return 1;
                   6450: }
                   6451: &register_handler("autocrsreqvalidation", \&validate_crsreq_handler, 0, 1, 0);
                   6452: 
1.506     raeburn  6453: sub crsreq_update_handler {
                   6454:     my ($cmd, $tail, $client) = @_;
                   6455:     my $userinput = "$cmd:$tail";
1.509     raeburn  6456:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,$code,
                   6457:         $accessstart,$accessend,$infohashref) =
1.506     raeburn  6458:         split(/:/, $tail);
                   6459:     $crstype = &unescape($crstype);
                   6460:     $action = &unescape($action);
                   6461:     $ownername = &unescape($ownername);
                   6462:     $ownerdomain = &unescape($ownerdomain);
                   6463:     $fullname = &unescape($fullname);
                   6464:     $title = &unescape($title);
                   6465:     $code = &unescape($code);
1.509     raeburn  6466:     $accessstart = &unescape($accessstart);
                   6467:     $accessend = &unescape($accessend);
1.506     raeburn  6468:     my $incoming = &Apache::lonnet::thaw_unescape($infohashref);
                   6469:     my ($result,$outcome);
                   6470:     eval {
                   6471:         local($SIG{__DIE__})='DEFAULT';
                   6472:         my %rtnhash;
                   6473:         $outcome = &localenroll::crsreq_updates($cdom,$cnum,$crstype,$action,
                   6474:                                                 $ownername,$ownerdomain,$fullname,
1.509     raeburn  6475:                                                 $title,$code,$accessstart,$accessend,
                   6476:                                                 $incoming,\%rtnhash);
1.506     raeburn  6477:         if ($outcome eq 'ok') {
1.515     raeburn  6478:             my @posskeys = qw(createdweb createdmsg createdcustomized createdactions queuedweb queuedmsg formitems reviewweb validationjs onload javascript);
1.506     raeburn  6479:             foreach my $key (keys(%rtnhash)) {
                   6480:                 if (grep(/^\Q$key\E/,@posskeys)) {
                   6481:                     $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
                   6482:                 }
                   6483:             }
                   6484:             $result =~ s/\&$//;
                   6485:         }
                   6486:     };
                   6487:     if (!$@) {
                   6488:         if ($outcome eq 'ok') {
                   6489:             &Reply($client, \$result, $userinput);
                   6490:         } else {
                   6491:             &Reply($client, "format_error\n", $userinput);
                   6492:         }
                   6493:     } else {
                   6494:         &Failure($client,"unknown_cmd\n",$userinput);
                   6495:     }
                   6496:     return 1;
                   6497: }
                   6498: &register_handler("autocrsrequpdate", \&crsreq_update_handler, 0, 1, 0);
                   6499: 
1.248     foxr     6500: #
                   6501: #   Read and retrieve institutional code format (for support form).
                   6502: # Formal Parameters:
                   6503: #    $cmd        - Command that dispatched us.
                   6504: #    $tail       - Tail of the command.  In this case it conatins 
                   6505: #                  the course domain and the coursename.
                   6506: #    $client     - Socket open on the client.
                   6507: # Returns:
                   6508: #    1     - Continue processing.
                   6509: #
                   6510: sub get_institutional_code_format_handler {
                   6511:     my ($cmd, $tail, $client)   = @_;
                   6512:     my $userinput               = "$cmd:$tail";
                   6513: 
                   6514:     my $reply;
                   6515:     my($cdom,$course) = split(/:/,$tail);
                   6516:     my @pairs = split/\&/,$course;
                   6517:     my %instcodes = ();
                   6518:     my %codes = ();
                   6519:     my @codetitles = ();
                   6520:     my %cat_titles = ();
                   6521:     my %cat_order = ();
                   6522:     foreach (@pairs) {
                   6523: 	my ($key,$value) = split/=/,$_;
                   6524: 	$instcodes{&unescape($key)} = &unescape($value);
                   6525:     }
                   6526:     my $formatreply = &localenroll::instcode_format($cdom,
                   6527: 						    \%instcodes,
                   6528: 						    \%codes,
                   6529: 						    \@codetitles,
                   6530: 						    \%cat_titles,
                   6531: 						    \%cat_order);
                   6532:     if ($formatreply eq 'ok') {
1.365     albertel 6533: 	my $codes_str = &Apache::lonnet::hash2str(%codes);
                   6534: 	my $codetitles_str = &Apache::lonnet::array2str(@codetitles);
                   6535: 	my $cat_titles_str = &Apache::lonnet::hash2str(%cat_titles);
                   6536: 	my $cat_order_str = &Apache::lonnet::hash2str(%cat_order);
1.248     foxr     6537: 	&Reply($client,
                   6538: 	       $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
                   6539: 	       .$cat_order_str."\n",
                   6540: 	       $userinput);
                   6541:     } else {
                   6542: 	# this else branch added by RF since if not ok, lonc will
                   6543: 	# hang waiting on reply until timeout.
                   6544: 	#
                   6545: 	&Reply($client, "format_error\n", $userinput);
                   6546:     }
                   6547:     
                   6548:     return 1;
                   6549: }
1.265     albertel 6550: &register_handler("autoinstcodeformat",
                   6551: 		  \&get_institutional_code_format_handler,0,1,0);
1.246     foxr     6552: 
1.345     raeburn  6553: sub get_institutional_defaults_handler {
                   6554:     my ($cmd, $tail, $client)   = @_;
                   6555:     my $userinput               = "$cmd:$tail";
                   6556: 
                   6557:     my $dom = $tail;
                   6558:     my %defaults_hash;
                   6559:     my @code_order;
                   6560:     my $outcome;
                   6561:     eval {
                   6562:         local($SIG{__DIE__})='DEFAULT';
                   6563:         $outcome = &localenroll::instcode_defaults($dom,\%defaults_hash,
                   6564:                                                    \@code_order);
                   6565:     };
                   6566:     if (!$@) {
                   6567:         if ($outcome eq 'ok') {
                   6568:             my $result='';
                   6569:             while (my ($key,$value) = each(%defaults_hash)) {
                   6570:                 $result.=&escape($key).'='.&escape($value).'&';
                   6571:             }
                   6572:             $result .= 'code_order='.&escape(join('&',@code_order));
1.387     albertel 6573:             &Reply($client,\$result,$userinput);
1.345     raeburn  6574:         } else {
                   6575:             &Reply($client,"error\n", $userinput);
                   6576:         }
                   6577:     } else {
                   6578:         &Failure($client,"unknown_cmd\n",$userinput);
                   6579:     }
                   6580: }
                   6581: &register_handler("autoinstcodedefaults",
                   6582:                   \&get_institutional_defaults_handler,0,1,0);
                   6583: 
1.416     raeburn  6584: sub get_possible_instcodes_handler {
                   6585:     my ($cmd, $tail, $client)   = @_;
                   6586:     my $userinput               = "$cmd:$tail";
                   6587: 
                   6588:     my $reply;
                   6589:     my $cdom = $tail;
1.417     raeburn  6590:     my (@codetitles,%cat_titles,%cat_order,@code_order);
1.416     raeburn  6591:     my $formatreply = &localenroll::possible_instcodes($cdom,
                   6592:                                                        \@codetitles,
                   6593:                                                        \%cat_titles,
1.417     raeburn  6594:                                                        \%cat_order,
                   6595:                                                        \@code_order);
1.416     raeburn  6596:     if ($formatreply eq 'ok') {
                   6597:         my $result = join('&',map {&escape($_);} (@codetitles)).':';
1.417     raeburn  6598:         $result .= join('&',map {&escape($_);} (@code_order)).':';
1.416     raeburn  6599:         foreach my $key (keys(%cat_titles)) {
                   6600:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_titles{$key}).'&';
                   6601:         }
                   6602:         $result =~ s/\&$//;
                   6603:         $result .= ':';
                   6604:         foreach my $key (keys(%cat_order)) {
                   6605:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_order{$key}).'&';
                   6606:         }
                   6607:         $result =~ s/\&$//;
                   6608:         &Reply($client,\$result,$userinput);
                   6609:     } else {
                   6610:         &Reply($client, "format_error\n", $userinput);
                   6611:     }
                   6612:     return 1;
                   6613: }
                   6614: &register_handler("autopossibleinstcodes",
                   6615:                   \&get_possible_instcodes_handler,0,1,0);
                   6616: 
1.381     raeburn  6617: sub get_institutional_user_rules {
                   6618:     my ($cmd, $tail, $client)   = @_;
                   6619:     my $userinput               = "$cmd:$tail";
                   6620:     my $dom = &unescape($tail);
                   6621:     my (%rules_hash,@rules_order);
                   6622:     my $outcome;
                   6623:     eval {
                   6624:         local($SIG{__DIE__})='DEFAULT';
                   6625:         $outcome = &localenroll::username_rules($dom,\%rules_hash,\@rules_order);
                   6626:     };
                   6627:     if (!$@) {
                   6628:         if ($outcome eq 'ok') {
                   6629:             my $result;
                   6630:             foreach my $key (keys(%rules_hash)) {
                   6631:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6632:             }
                   6633:             $result =~ s/\&$//;
                   6634:             $result .= ':';
                   6635:             if (@rules_order > 0) {
                   6636:                 foreach my $item (@rules_order) {
                   6637:                     $result .= &escape($item).'&';
                   6638:                 }
                   6639:             }
                   6640:             $result =~ s/\&$//;
1.387     albertel 6641:             &Reply($client,\$result,$userinput);
1.381     raeburn  6642:         } else {
                   6643:             &Reply($client,"error\n", $userinput);
                   6644:         }
                   6645:     } else {
                   6646:         &Failure($client,"unknown_cmd\n",$userinput);
                   6647:     }
                   6648: }
                   6649: &register_handler("instuserrules",\&get_institutional_user_rules,0,1,0);
                   6650: 
1.389     raeburn  6651: sub get_institutional_id_rules {
                   6652:     my ($cmd, $tail, $client)   = @_;
                   6653:     my $userinput               = "$cmd:$tail";
                   6654:     my $dom = &unescape($tail);
                   6655:     my (%rules_hash,@rules_order);
                   6656:     my $outcome;
                   6657:     eval {
                   6658:         local($SIG{__DIE__})='DEFAULT';
                   6659:         $outcome = &localenroll::id_rules($dom,\%rules_hash,\@rules_order);
                   6660:     };
                   6661:     if (!$@) {
                   6662:         if ($outcome eq 'ok') {
                   6663:             my $result;
                   6664:             foreach my $key (keys(%rules_hash)) {
                   6665:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6666:             }
                   6667:             $result =~ s/\&$//;
                   6668:             $result .= ':';
                   6669:             if (@rules_order > 0) {
                   6670:                 foreach my $item (@rules_order) {
                   6671:                     $result .= &escape($item).'&';
                   6672:                 }
                   6673:             }
                   6674:             $result =~ s/\&$//;
                   6675:             &Reply($client,\$result,$userinput);
                   6676:         } else {
                   6677:             &Reply($client,"error\n", $userinput);
                   6678:         }
                   6679:     } else {
                   6680:         &Failure($client,"unknown_cmd\n",$userinput);
                   6681:     }
                   6682: }
                   6683: &register_handler("instidrules",\&get_institutional_id_rules,0,1,0);
                   6684: 
1.397     raeburn  6685: sub get_institutional_selfcreate_rules {
1.396     raeburn  6686:     my ($cmd, $tail, $client)   = @_;
                   6687:     my $userinput               = "$cmd:$tail";
                   6688:     my $dom = &unescape($tail);
                   6689:     my (%rules_hash,@rules_order);
                   6690:     my $outcome;
                   6691:     eval {
                   6692:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  6693:         $outcome = &localenroll::selfcreate_rules($dom,\%rules_hash,\@rules_order);
1.396     raeburn  6694:     };
                   6695:     if (!$@) {
                   6696:         if ($outcome eq 'ok') {
                   6697:             my $result;
                   6698:             foreach my $key (keys(%rules_hash)) {
                   6699:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6700:             }
                   6701:             $result =~ s/\&$//;
                   6702:             $result .= ':';
                   6703:             if (@rules_order > 0) {
                   6704:                 foreach my $item (@rules_order) {
                   6705:                     $result .= &escape($item).'&';
                   6706:                 }
                   6707:             }
                   6708:             $result =~ s/\&$//;
                   6709:             &Reply($client,\$result,$userinput);
                   6710:         } else {
                   6711:             &Reply($client,"error\n", $userinput);
                   6712:         }
                   6713:     } else {
                   6714:         &Failure($client,"unknown_cmd\n",$userinput);
                   6715:     }
                   6716: }
1.397     raeburn  6717: &register_handler("instemailrules",\&get_institutional_selfcreate_rules,0,1,0);
1.396     raeburn  6718: 
1.381     raeburn  6719: 
                   6720: sub institutional_username_check {
                   6721:     my ($cmd, $tail, $client)   = @_;
                   6722:     my $userinput               = "$cmd:$tail";
                   6723:     my %rulecheck;
                   6724:     my $outcome;
                   6725:     my ($udom,$uname,@rules) = split(/:/,$tail);
                   6726:     $udom = &unescape($udom);
                   6727:     $uname = &unescape($uname);
                   6728:     @rules = map {&unescape($_);} (@rules);
                   6729:     eval {
                   6730:         local($SIG{__DIE__})='DEFAULT';
                   6731:         $outcome = &localenroll::username_check($udom,$uname,\@rules,\%rulecheck);
                   6732:     };
                   6733:     if (!$@) {
                   6734:         if ($outcome eq 'ok') {
                   6735:             my $result='';
                   6736:             foreach my $key (keys(%rulecheck)) {
                   6737:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6738:             }
1.387     albertel 6739:             &Reply($client,\$result,$userinput);
1.381     raeburn  6740:         } else {
                   6741:             &Reply($client,"error\n", $userinput);
                   6742:         }
                   6743:     } else {
                   6744:         &Failure($client,"unknown_cmd\n",$userinput);
                   6745:     }
                   6746: }
                   6747: &register_handler("instrulecheck",\&institutional_username_check,0,1,0);
                   6748: 
1.389     raeburn  6749: sub institutional_id_check {
                   6750:     my ($cmd, $tail, $client)   = @_;
                   6751:     my $userinput               = "$cmd:$tail";
                   6752:     my %rulecheck;
                   6753:     my $outcome;
                   6754:     my ($udom,$id,@rules) = split(/:/,$tail);
                   6755:     $udom = &unescape($udom);
                   6756:     $id = &unescape($id);
                   6757:     @rules = map {&unescape($_);} (@rules);
                   6758:     eval {
                   6759:         local($SIG{__DIE__})='DEFAULT';
                   6760:         $outcome = &localenroll::id_check($udom,$id,\@rules,\%rulecheck);
                   6761:     };
                   6762:     if (!$@) {
                   6763:         if ($outcome eq 'ok') {
                   6764:             my $result='';
                   6765:             foreach my $key (keys(%rulecheck)) {
                   6766:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6767:             }
                   6768:             &Reply($client,\$result,$userinput);
                   6769:         } else {
                   6770:             &Reply($client,"error\n", $userinput);
                   6771:         }
                   6772:     } else {
                   6773:         &Failure($client,"unknown_cmd\n",$userinput);
                   6774:     }
                   6775: }
                   6776: &register_handler("instidrulecheck",\&institutional_id_check,0,1,0);
1.345     raeburn  6777: 
1.397     raeburn  6778: sub institutional_selfcreate_check {
1.396     raeburn  6779:     my ($cmd, $tail, $client)   = @_;
                   6780:     my $userinput               = "$cmd:$tail";
                   6781:     my %rulecheck;
                   6782:     my $outcome;
                   6783:     my ($udom,$email,@rules) = split(/:/,$tail);
                   6784:     $udom = &unescape($udom);
                   6785:     $email = &unescape($email);
                   6786:     @rules = map {&unescape($_);} (@rules);
                   6787:     eval {
                   6788:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  6789:         $outcome = &localenroll::selfcreate_check($udom,$email,\@rules,\%rulecheck);
1.396     raeburn  6790:     };
                   6791:     if (!$@) {
                   6792:         if ($outcome eq 'ok') {
                   6793:             my $result='';
                   6794:             foreach my $key (keys(%rulecheck)) {
                   6795:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6796:             }
                   6797:             &Reply($client,\$result,$userinput);
                   6798:         } else {
                   6799:             &Reply($client,"error\n", $userinput);
                   6800:         }
                   6801:     } else {
                   6802:         &Failure($client,"unknown_cmd\n",$userinput);
                   6803:     }
                   6804: }
1.397     raeburn  6805: &register_handler("instselfcreatecheck",\&institutional_selfcreate_check,0,1,0);
1.396     raeburn  6806: 
1.317     raeburn  6807: # Get domain specific conditions for import of student photographs to a course
                   6808: #
                   6809: # Retrieves information from photo_permission subroutine in localenroll.
                   6810: # Returns outcome (ok) if no processing errors, and whether course owner is 
                   6811: # required to accept conditions of use (yes/no).
                   6812: #
                   6813: #    
                   6814: sub photo_permission_handler {
                   6815:     my ($cmd, $tail, $client)   = @_;
                   6816:     my $userinput               = "$cmd:$tail";
                   6817:     my $cdom = $tail;
                   6818:     my ($perm_reqd,$conditions);
1.320     albertel 6819:     my $outcome;
                   6820:     eval {
                   6821: 	local($SIG{__DIE__})='DEFAULT';
                   6822: 	$outcome = &localenroll::photo_permission($cdom,\$perm_reqd,
                   6823: 						  \$conditions);
                   6824:     };
                   6825:     if (!$@) {
                   6826: 	&Reply($client, &escape($outcome.':'.$perm_reqd.':'. $conditions)."\n",
                   6827: 	       $userinput);
                   6828:     } else {
                   6829: 	&Failure($client,"unknown_cmd\n",$userinput);
                   6830:     }
                   6831:     return 1;
1.317     raeburn  6832: }
                   6833: &register_handler("autophotopermission",\&photo_permission_handler,0,1,0);
                   6834: 
                   6835: #
                   6836: # Checks if student photo is available for a user in the domain, in the user's
                   6837: # directory (in /userfiles/internal/studentphoto.jpg).
                   6838: # Uses localstudentphoto:fetch() to ensure there is an up to date copy of
                   6839: # the student's photo.   
                   6840: 
                   6841: sub photo_check_handler {
                   6842:     my ($cmd, $tail, $client)   = @_;
                   6843:     my $userinput               = "$cmd:$tail";
                   6844:     my ($udom,$uname,$pid) = split(/:/,$tail);
                   6845:     $udom = &unescape($udom);
                   6846:     $uname = &unescape($uname);
                   6847:     $pid = &unescape($pid);
                   6848:     my $path=&propath($udom,$uname).'/userfiles/internal/';
                   6849:     if (!-e $path) {
                   6850:         &mkpath($path);
                   6851:     }
                   6852:     my $response;
                   6853:     my $result = &localstudentphoto::fetch($udom,$uname,$pid,\$response);
                   6854:     $result .= ':'.$response;
                   6855:     &Reply($client, &escape($result)."\n",$userinput);
1.320     albertel 6856:     return 1;
1.317     raeburn  6857: }
                   6858: &register_handler("autophotocheck",\&photo_check_handler,0,1,0);
                   6859: 
                   6860: #
                   6861: # Retrieve information from localenroll about whether to provide a button     
                   6862: # for users who have enbled import of student photos to initiate an 
                   6863: # update of photo files for registered students. Also include 
                   6864: # comment to display alongside button.  
                   6865: 
                   6866: sub photo_choice_handler {
                   6867:     my ($cmd, $tail, $client) = @_;
                   6868:     my $userinput             = "$cmd:$tail";
                   6869:     my $cdom                  = &unescape($tail);
1.320     albertel 6870:     my ($update,$comment);
                   6871:     eval {
                   6872: 	local($SIG{__DIE__})='DEFAULT';
                   6873: 	($update,$comment)    = &localenroll::manager_photo_update($cdom);
                   6874:     };
                   6875:     if (!$@) {
                   6876: 	&Reply($client,&escape($update).':'.&escape($comment)."\n",$userinput);
                   6877:     } else {
                   6878: 	&Failure($client,"unknown_cmd\n",$userinput);
                   6879:     }
                   6880:     return 1;
1.317     raeburn  6881: }
                   6882: &register_handler("autophotochoice",\&photo_choice_handler,0,1,0);
                   6883: 
1.265     albertel 6884: #
                   6885: # Gets a student's photo to exist (in the correct image type) in the user's 
                   6886: # directory.
                   6887: # Formal Parameters:
                   6888: #    $cmd     - The command request that got us dispatched.
                   6889: #    $tail    - A colon separated set of words that will be split into:
                   6890: #               $domain - student's domain
                   6891: #               $uname  - student username
                   6892: #               $type   - image type desired
                   6893: #    $client  - The socket open on the client.
                   6894: # Returns:
                   6895: #    1 - continue processing.
1.317     raeburn  6896: 
1.265     albertel 6897: sub student_photo_handler {
                   6898:     my ($cmd, $tail, $client) = @_;
1.317     raeburn  6899:     my ($domain,$uname,$ext,$type) = split(/:/, $tail);
1.265     albertel 6900: 
1.317     raeburn  6901:     my $path=&propath($domain,$uname). '/userfiles/internal/';
                   6902:     my $filename = 'studentphoto.'.$ext;
                   6903:     if ($type eq 'thumbnail') {
                   6904:         $filename = 'studentphoto_tn.'.$ext;
                   6905:     }
                   6906:     if (-e $path.$filename) {
1.265     albertel 6907: 	&Reply($client,"ok\n","$cmd:$tail");
                   6908: 	return 1;
                   6909:     }
                   6910:     &mkpath($path);
1.317     raeburn  6911:     my $file;
                   6912:     if ($type eq 'thumbnail') {
1.320     albertel 6913: 	eval {
                   6914: 	    local($SIG{__DIE__})='DEFAULT';
                   6915: 	    $file=&localstudentphoto::fetch_thumbnail($domain,$uname);
                   6916: 	};
1.317     raeburn  6917:     } else {
                   6918:         $file=&localstudentphoto::fetch($domain,$uname);
                   6919:     }
1.265     albertel 6920:     if (!$file) {
                   6921: 	&Failure($client,"unavailable\n","$cmd:$tail");
                   6922: 	return 1;
                   6923:     }
1.317     raeburn  6924:     if (!-e $path.$filename) { &convert_photo($file,$path.$filename); }
                   6925:     if (-e $path.$filename) {
1.265     albertel 6926: 	&Reply($client,"ok\n","$cmd:$tail");
                   6927: 	return 1;
                   6928:     }
                   6929:     &Failure($client,"unable_to_convert\n","$cmd:$tail");
                   6930:     return 1;
                   6931: }
                   6932: &register_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
1.246     foxr     6933: 
1.361     raeburn  6934: sub inst_usertypes_handler {
                   6935:     my ($cmd, $domain, $client) = @_;
                   6936:     my $res;
                   6937:     my $userinput = $cmd.":".$domain; # For logging purposes.
1.370     albertel 6938:     my (%typeshash,@order,$result);
                   6939:     eval {
                   6940: 	local($SIG{__DIE__})='DEFAULT';
                   6941: 	$result=&localenroll::inst_usertypes($domain,\%typeshash,\@order);
                   6942:     };
                   6943:     if ($result eq 'ok') {
1.361     raeburn  6944:         if (keys(%typeshash) > 0) {
                   6945:             foreach my $key (keys(%typeshash)) {
                   6946:                 $res.=&escape($key).'='.&escape($typeshash{$key}).'&';
                   6947:             }
                   6948:         }
                   6949:         $res=~s/\&$//;
                   6950:         $res .= ':';
                   6951:         if (@order > 0) {
                   6952:             foreach my $item (@order) {
                   6953:                 $res .= &escape($item).'&';
                   6954:             }
                   6955:         }
                   6956:         $res=~s/\&$//;
                   6957:     }
1.387     albertel 6958:     &Reply($client, \$res, $userinput);
1.361     raeburn  6959:     return 1;
                   6960: }
                   6961: &register_handler("inst_usertypes", \&inst_usertypes_handler, 0, 1, 0);
                   6962: 
1.264     albertel 6963: # mkpath makes all directories for a file, expects an absolute path with a
                   6964: # file or a trailing / if just a dir is passed
                   6965: # returns 1 on success 0 on failure
                   6966: sub mkpath {
                   6967:     my ($file)=@_;
                   6968:     my @parts=split(/\//,$file,-1);
                   6969:     my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
                   6970:     for (my $i=3;$i<= ($#parts-1);$i++) {
1.265     albertel 6971: 	$now.='/'.$parts[$i]; 
1.264     albertel 6972: 	if (!-e $now) {
                   6973: 	    if  (!mkdir($now,0770)) { return 0; }
                   6974: 	}
                   6975:     }
                   6976:     return 1;
                   6977: }
                   6978: 
1.207     foxr     6979: #---------------------------------------------------------------
                   6980: #
                   6981: #   Getting, decoding and dispatching requests:
                   6982: #
                   6983: #
                   6984: #   Get a Request:
                   6985: #   Gets a Request message from the client.  The transaction
                   6986: #   is defined as a 'line' of text.  We remove the new line
                   6987: #   from the text line.  
1.226     foxr     6988: #
1.211     albertel 6989: sub get_request {
1.207     foxr     6990:     my $input = <$client>;
                   6991:     chomp($input);
1.226     foxr     6992: 
1.234     foxr     6993:     &Debug("get_request: Request = $input\n");
1.207     foxr     6994: 
                   6995:     &status('Processing '.$clientname.':'.$input);
                   6996: 
                   6997:     return $input;
                   6998: }
1.212     foxr     6999: #---------------------------------------------------------------
                   7000: #
                   7001: #  Process a request.  This sub should shrink as each action
                   7002: #  gets farmed out into a separat sub that is registered 
                   7003: #  with the dispatch hash.  
                   7004: #
                   7005: # Parameters:
                   7006: #    user_input   - The request received from the client (lonc).
1.525     raeburn  7007: #
1.212     foxr     7008: # Returns:
                   7009: #    true to keep processing, false if caller should exit.
                   7010: #
                   7011: sub process_request {
1.525     raeburn  7012:     my ($userinput) = @_; # Easier for now to break style than to
                   7013:                           # fix all the userinput -> user_input.
1.212     foxr     7014:     my $wasenc    = 0;		# True if request was encrypted.
                   7015: # ------------------------------------------------------------ See if encrypted
1.322     albertel 7016:     # for command
                   7017:     # sethost:<server>
                   7018:     # <command>:<args>
                   7019:     #   we just send it to the processor
                   7020:     # for
                   7021:     # sethost:<server>:<command>:<args>
                   7022:     #  we do the implict set host and then do the command
                   7023:     if ($userinput =~ /^sethost:/) {
                   7024: 	(my $cmd,my $newid,$userinput) = split(':',$userinput,3);
                   7025: 	if (defined($userinput)) {
                   7026: 	    &sethost("$cmd:$newid");
                   7027: 	} else {
                   7028: 	    $userinput = "$cmd:$newid";
                   7029: 	}
                   7030:     }
                   7031: 
1.212     foxr     7032:     if ($userinput =~ /^enc/) {
                   7033: 	$userinput = decipher($userinput);
                   7034: 	$wasenc=1;
                   7035: 	if(!$userinput) {	# Cipher not defined.
1.251     foxr     7036: 	    &Failure($client, "error: Encrypted data without negotated key\n");
1.212     foxr     7037: 	    return 0;
                   7038: 	}
                   7039:     }
                   7040:     Debug("process_request: $userinput\n");
                   7041:     
1.213     foxr     7042:     #  
                   7043:     #   The 'correct way' to add a command to lond is now to
                   7044:     #   write a sub to execute it and Add it to the command dispatch
                   7045:     #   hash via a call to register_handler..  The comments to that
                   7046:     #   sub should give you enough to go on to show how to do this
                   7047:     #   along with the examples that are building up as this code
                   7048:     #   is getting refactored.   Until all branches of the
                   7049:     #   if/elseif monster below have been factored out into
                   7050:     #   separate procesor subs, if the dispatch hash is missing
                   7051:     #   the command keyword, we will fall through to the remainder
                   7052:     #   of the if/else chain below in order to keep this thing in 
                   7053:     #   working order throughout the transmogrification.
                   7054: 
                   7055:     my ($command, $tail) = split(/:/, $userinput, 2);
                   7056:     chomp($command);
                   7057:     chomp($tail);
                   7058:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
1.214     foxr     7059:     $command =~ s/(\r)//;	# And this too for parameterless commands.
                   7060:     if(!$tail) {
                   7061: 	$tail ="";		# defined but blank.
                   7062:     }
1.213     foxr     7063: 
                   7064:     &Debug("Command received: $command, encoded = $wasenc");
                   7065: 
                   7066:     if(defined $Dispatcher{$command}) {
                   7067: 
                   7068: 	my $dispatch_info = $Dispatcher{$command};
                   7069: 	my $handler       = $$dispatch_info[0];
                   7070: 	my $need_encode   = $$dispatch_info[1];
                   7071: 	my $client_types  = $$dispatch_info[2];
                   7072: 	Debug("Matched dispatch hash: mustencode: $need_encode "
                   7073: 	      ."ClientType $client_types");
                   7074:       
                   7075: 	#  Validate the request:
                   7076:       
                   7077: 	my $ok = 1;
                   7078: 	my $requesterprivs = 0;
                   7079: 	if(&isClient()) {
                   7080: 	    $requesterprivs |= $CLIENT_OK;
                   7081: 	}
                   7082: 	if(&isManager()) {
                   7083: 	    $requesterprivs |= $MANAGER_OK;
                   7084: 	}
                   7085: 	if($need_encode && (!$wasenc)) {
                   7086: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
                   7087: 	    $ok = 0;
                   7088: 	}
                   7089: 	if(($client_types & $requesterprivs) == 0) {
                   7090: 	    Debug("Client not privileged to do this operation");
                   7091: 	    $ok = 0;
                   7092: 	}
1.525     raeburn  7093:         if ($ok) {
1.535     raeburn  7094:             my $realcommand = $command;
                   7095:             if ($command eq 'querysend') {
                   7096:                 my ($query,$rest)=split(/\:/,$tail,2);
                   7097:                 $query=~s/\n*$//g;
                   7098:                 my @possqueries = 
                   7099:                     qw(userlog courselog fetchenrollment institutionalphotos usersearch instdirsearch getinstuser getmultinstusers);
                   7100:                 if (grep(/^\Q$query\E$/,@possqueries)) {
                   7101:                     $command .= '_'.$query;
                   7102:                 } elsif ($query eq 'prepare activity log') {
                   7103:                     $command .= '_activitylog';
                   7104:                 }
                   7105:             }
1.525     raeburn  7106:             if (ref($trust{$command}) eq 'HASH') {
                   7107:                 my $donechecks;
                   7108:                 if ($trust{$command}{'anywhere'}) {
                   7109:                    $donechecks = 1;
                   7110:                 } elsif ($trust{$command}{'manageronly'}) {
                   7111:                     unless (&isManager()) {
                   7112:                         $ok = 0;
                   7113:                     }
                   7114:                     $donechecks = 1;
                   7115:                 } elsif ($trust{$command}{'institutiononly'}) {
                   7116:                     unless ($clientsameinst) {
                   7117:                         $ok = 0;
                   7118:                     }
                   7119:                     $donechecks = 1;
                   7120:                 } elsif ($clientsameinst) {
                   7121:                     $donechecks = 1;
                   7122:                 }
                   7123:                 unless ($donechecks) {
                   7124:                     foreach my $rule (keys(%{$trust{$command}})) {
                   7125:                         next if ($rule eq 'remote');
                   7126:                         if ($trust{$command}{$rule}) {
                   7127:                             if ($clientprohibited{$rule}) {
                   7128:                                 $ok = 0;
                   7129:                             } else {
                   7130:                                 $ok = 1;
                   7131:                                 $donechecks = 1;
                   7132:                                 last;
                   7133:                             }
                   7134:                         }
                   7135:                     }
                   7136:                 }
                   7137:                 unless ($donechecks) {
                   7138:                     if ($trust{$command}{'remote'}) {
                   7139:                         if ($clientremoteok) {
                   7140:                             $ok = 1;
                   7141:                         } else {
                   7142:                             $ok = 0;
                   7143:                         } 
                   7144:                     }
                   7145:                 }
                   7146:             }
1.535     raeburn  7147:             $command = $realcommand;
1.525     raeburn  7148:         }
1.213     foxr     7149: 
                   7150: 	if($ok) {
                   7151: 	    Debug("Dispatching to handler $command $tail");
                   7152: 	    my $keep_going = &$handler($command, $tail, $client);
                   7153: 	    return $keep_going;
                   7154: 	} else {
                   7155: 	    Debug("Refusing to dispatch because client did not match requirements");
                   7156: 	    Failure($client, "refused\n", $userinput);
                   7157: 	    return 1;
                   7158: 	}
1.525     raeburn  7159:     }
1.213     foxr     7160: 
1.262     foxr     7161:     print $client "unknown_cmd\n";
1.212     foxr     7162: # -------------------------------------------------------------------- complete
                   7163:     Debug("process_request - returning 1");
                   7164:     return 1;
                   7165: }
1.207     foxr     7166: #
                   7167: #   Decipher encoded traffic
                   7168: #  Parameters:
                   7169: #     input      - Encoded data.
                   7170: #  Returns:
                   7171: #     Decoded data or undef if encryption key was not yet negotiated.
                   7172: #  Implicit input:
                   7173: #     cipher  - This global holds the negotiated encryption key.
                   7174: #
1.211     albertel 7175: sub decipher {
1.207     foxr     7176:     my ($input)  = @_;
                   7177:     my $output = '';
1.212     foxr     7178:     
                   7179:     
1.207     foxr     7180:     if($cipher) {
                   7181: 	my($enc, $enclength, $encinput) = split(/:/, $input);
                   7182: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
                   7183: 	    $output .= 
                   7184: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
                   7185: 	}
                   7186: 	return substr($output, 0, $enclength);
                   7187:     } else {
                   7188: 	return undef;
                   7189:     }
                   7190: }
                   7191: 
                   7192: #
                   7193: #   Register a command processor.  This function is invoked to register a sub
                   7194: #   to process a request.  Once registered, the ProcessRequest sub can automatically
                   7195: #   dispatch requests to an appropriate sub, and do the top level validity checking
                   7196: #   as well:
                   7197: #    - Is the keyword recognized.
                   7198: #    - Is the proper client type attempting the request.
                   7199: #    - Is the request encrypted if it has to be.
                   7200: #   Parameters:
                   7201: #    $request_name         - Name of the request being registered.
                   7202: #                           This is the command request that will match
                   7203: #                           against the hash keywords to lookup the information
                   7204: #                           associated with the dispatch information.
                   7205: #    $procedure           - Reference to a sub to call to process the request.
                   7206: #                           All subs get called as follows:
                   7207: #                             Procedure($cmd, $tail, $replyfd, $key)
                   7208: #                             $cmd    - the actual keyword that invoked us.
                   7209: #                             $tail   - the tail of the request that invoked us.
                   7210: #                             $replyfd- File descriptor connected to the client
                   7211: #    $must_encode          - True if the request must be encoded to be good.
                   7212: #    $client_ok            - True if it's ok for a client to request this.
                   7213: #    $manager_ok           - True if it's ok for a manager to request this.
                   7214: # Side effects:
                   7215: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
                   7216: #      - On failure, the program will die as it's a bad internal bug to try to 
                   7217: #        register a duplicate command handler.
                   7218: #
1.211     albertel 7219: sub register_handler {
1.212     foxr     7220:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
1.207     foxr     7221: 
                   7222:     #  Don't allow duplication#
                   7223:    
                   7224:     if (defined $Dispatcher{$request_name}) {
                   7225: 	die "Attempting to define a duplicate request handler for $request_name\n";
                   7226:     }
                   7227:     #   Build the client type mask:
                   7228:     
                   7229:     my $client_type_mask = 0;
                   7230:     if($client_ok) {
                   7231: 	$client_type_mask  |= $CLIENT_OK;
                   7232:     }
                   7233:     if($manager_ok) {
                   7234: 	$client_type_mask  |= $MANAGER_OK;
                   7235:     }
                   7236:    
                   7237:     #  Enter the hash:
                   7238:       
                   7239:     my @entry = ($procedure, $must_encode, $client_type_mask);
                   7240:    
                   7241:     $Dispatcher{$request_name} = \@entry;
                   7242:    
                   7243: }
                   7244: 
                   7245: 
                   7246: #------------------------------------------------------------------
                   7247: 
                   7248: 
                   7249: 
                   7250: 
1.141     foxr     7251: #
1.96      foxr     7252: #  Convert an error return code from lcpasswd to a string value.
                   7253: #
                   7254: sub lcpasswdstrerror {
                   7255:     my $ErrorCode = shift;
1.97      foxr     7256:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96      foxr     7257: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
                   7258:     } else {
1.98      foxr     7259: 	return $passwderrors[$ErrorCode];
1.96      foxr     7260:     }
                   7261: }
                   7262: 
1.23      harris41 7263: # grabs exception and records it to log before exiting
                   7264: sub catchexception {
1.27      albertel 7265:     my ($error)=@_;
1.25      www      7266:     $SIG{'QUIT'}='DEFAULT';
                   7267:     $SIG{__DIE__}='DEFAULT';
1.165     albertel 7268:     &status("Catching exception");
1.190     albertel 7269:     &logthis("<font color='red'>CRITICAL: "
1.373     albertel 7270:      ."ABNORMAL EXIT. Child $$ for server ".$perlvar{'lonHostID'}." died through "
1.27      albertel 7271:      ."a crash with this error msg->[$error]</font>");
1.57      www      7272:     &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27      albertel 7273:     if ($client) { print $client "error: $error\n"; }
1.59      www      7274:     $server->close();
1.27      albertel 7275:     die($error);
1.23      harris41 7276: }
1.63      www      7277: sub timeout {
1.165     albertel 7278:     &status("Handling Timeout");
1.190     albertel 7279:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
1.63      www      7280:     &catchexception('Timeout');
                   7281: }
1.22      harris41 7282: # -------------------------------- Set signal handlers to record abnormal exits
                   7283: 
1.226     foxr     7284: 
1.22      harris41 7285: $SIG{'QUIT'}=\&catchexception;
                   7286: $SIG{__DIE__}=\&catchexception;
                   7287: 
1.81      matthew  7288: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95      harris41 7289: &status("Read loncapa.conf and loncapa_apache.conf");
                   7290: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141     foxr     7291: %perlvar=%{$perlvarref};
1.80      harris41 7292: undef $perlvarref;
1.19      www      7293: 
1.35      harris41 7294: # ----------------------------- Make sure this process is running from user=www
                   7295: my $wwwid=getpwnam('www');
                   7296: if ($wwwid!=$<) {
1.134     albertel 7297:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   7298:    my $subj="LON: $currenthostid User ID mismatch";
1.550     raeburn  7299:    system("echo 'User ID mismatch.  lond must be run as user www.' |".
                   7300:           " mail -s '$subj' $emailto > /dev/null");
1.35      harris41 7301:    exit 1;
                   7302: }
                   7303: 
1.19      www      7304: # --------------------------------------------- Check if other instance running
                   7305: 
                   7306: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
                   7307: 
                   7308: if (-e $pidfile) {
                   7309:    my $lfh=IO::File->new("$pidfile");
                   7310:    my $pide=<$lfh>;
                   7311:    chomp($pide);
1.29      harris41 7312:    if (kill 0 => $pide) { die "already running"; }
1.19      www      7313: }
1.1       albertel 7314: 
                   7315: # ------------------------------------------------------------- Read hosts file
                   7316: 
                   7317: 
                   7318: 
                   7319: # establish SERVER socket, bind and listen.
                   7320: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
                   7321:                                 Type      => SOCK_STREAM,
                   7322:                                 Proto     => 'tcp',
1.469     foxr     7323:                                 ReuseAddr     => 1,
1.1       albertel 7324:                                 Listen    => 10 )
1.29      harris41 7325:   or die "making socket: $@\n";
1.1       albertel 7326: 
                   7327: # --------------------------------------------------------- Do global variables
                   7328: 
                   7329: # global variables
                   7330: 
1.134     albertel 7331: my %children               = ();       # keys are current child process IDs
1.1       albertel 7332: 
                   7333: sub REAPER {                        # takes care of dead children
                   7334:     $SIG{CHLD} = \&REAPER;
1.165     albertel 7335:     &status("Handling child death");
1.178     foxr     7336:     my $pid;
                   7337:     do {
                   7338: 	$pid = waitpid(-1,&WNOHANG());
                   7339: 	if (defined($children{$pid})) {
                   7340: 	    &logthis("Child $pid died");
                   7341: 	    delete($children{$pid});
1.183     albertel 7342: 	} elsif ($pid > 0) {
1.178     foxr     7343: 	    &logthis("Unknown Child $pid died");
                   7344: 	}
                   7345:     } while ( $pid > 0 );
                   7346:     foreach my $child (keys(%children)) {
                   7347: 	$pid = waitpid($child,&WNOHANG());
                   7348: 	if ($pid > 0) {
                   7349: 	    &logthis("Child $child - $pid looks like we missed it's death");
                   7350: 	    delete($children{$pid});
                   7351: 	}
1.176     albertel 7352:     }
1.165     albertel 7353:     &status("Finished Handling child death");
1.1       albertel 7354: }
                   7355: 
                   7356: sub HUNTSMAN {                      # signal handler for SIGINT
1.165     albertel 7357:     &status("Killing children (INT)");
1.1       albertel 7358:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
                   7359:     kill 'INT' => keys %children;
1.59      www      7360:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1       albertel 7361:     my $execdir=$perlvar{'lonDaemons'};
                   7362:     unlink("$execdir/logs/lond.pid");
1.190     albertel 7363:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.165     albertel 7364:     &status("Done killing children");
1.1       albertel 7365:     exit;                           # clean up with dignity
                   7366: }
                   7367: 
                   7368: sub HUPSMAN {                      # signal handler for SIGHUP
                   7369:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
1.165     albertel 7370:     &status("Killing children for restart (HUP)");
1.1       albertel 7371:     kill 'INT' => keys %children;
1.59      www      7372:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.190     albertel 7373:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.134     albertel 7374:     my $execdir=$perlvar{'lonDaemons'};
1.30      harris41 7375:     unlink("$execdir/logs/lond.pid");
1.165     albertel 7376:     &status("Restarting self (HUP)");
1.1       albertel 7377:     exec("$execdir/lond");         # here we go again
                   7378: }
                   7379: 
1.144     foxr     7380: #
1.148     foxr     7381: #  Reload the Apache daemon's state.
1.150     foxr     7382: #  This is done by invoking /home/httpd/perl/apachereload
                   7383: #  a setuid perl script that can be root for us to do this job.
1.148     foxr     7384: #
                   7385: sub ReloadApache {
1.473     raeburn  7386: # --------------------------- Handle case of another apachereload process (locking)
1.474     raeburn  7387:     if (&LONCAPA::try_to_lock('/tmp/lock_apachereload')) {
                   7388:         my $execdir = $perlvar{'lonDaemons'};
                   7389:         my $script  = $execdir."/apachereload";
                   7390:         system($script);
                   7391:         unlink('/tmp/lock_apachereload'); #  Remove the lock file.
                   7392:     }
1.148     foxr     7393: }
                   7394: 
                   7395: #
1.144     foxr     7396: #   Called in response to a USR2 signal.
                   7397: #   - Reread hosts.tab
                   7398: #   - All children connected to hosts that were removed from hosts.tab
                   7399: #     are killed via SIGINT
                   7400: #   - All children connected to previously existing hosts are sent SIGUSR1
                   7401: #   - Our internal hosts hash is updated to reflect the new contents of
                   7402: #     hosts.tab causing connections from hosts added to hosts.tab to
                   7403: #     now be honored.
                   7404: #
                   7405: sub UpdateHosts {
1.165     albertel 7406:     &status("Reload hosts.tab");
1.147     foxr     7407:     logthis('<font color="blue"> Updating connections </font>');
1.148     foxr     7408:     #
                   7409:     #  The %children hash has the set of IP's we currently have children
                   7410:     #  on.  These need to be matched against records in the hosts.tab
                   7411:     #  Any ip's no longer in the table get killed off they correspond to
                   7412:     #  either dropped or changed hosts.  Note that the re-read of the table
                   7413:     #  will take care of new and changed hosts as connections come into being.
                   7414: 
1.371     albertel 7415:     &Apache::lonnet::reset_hosts_info();
1.532     raeburn  7416:     my %active;
1.148     foxr     7417: 
1.368     albertel 7418:     foreach my $child (keys(%children)) {
1.148     foxr     7419: 	my $childip = $children{$child};
1.374     albertel 7420: 	if ($childip ne '127.0.0.1'
                   7421: 	    && !defined(&Apache::lonnet::get_hosts_from_ip($childip))) {
1.149     foxr     7422: 	    logthis('<font color="blue"> UpdateHosts killing child '
                   7423: 		    ." $child for ip $childip </font>");
1.148     foxr     7424: 	    kill('INT', $child);
1.149     foxr     7425: 	} else {
1.532     raeburn  7426:             $active{$child} = $childip;
1.149     foxr     7427: 	    logthis('<font color="green"> keeping child for ip '
                   7428: 		    ." $childip (pid=$child) </font>");
1.148     foxr     7429: 	}
                   7430:     }
1.532     raeburn  7431: 
                   7432:     my %oldconf = %secureconf;
                   7433:     my %connchange;
1.555     raeburn  7434:     if (lonssl::Read_Connect_Config(\%secureconf,\%perlvar,\%crlchecked) eq 'ok') {
1.545     raeburn  7435:         logthis('<font color="blue"> Reloaded SSL connection rules and cleared CRL checking history </font>');
1.532     raeburn  7436:     } else {
1.545     raeburn  7437:         logthis('<font color="yellow"> Failed to reload SSL connection rules and clear CRL checking history </font>');
1.532     raeburn  7438:     }
                   7439:     if ((ref($oldconf{'connfrom'}) eq 'HASH') && (ref($secureconf{'connfrom'}) eq 'HASH')) {
                   7440:         foreach my $type ('dom','intdom','other') {
                   7441:             if ((($oldconf{'connfrom'}{$type} eq 'no') && ($secureconf{'connfrom'}{$type} eq 'req')) ||
                   7442:                 (($oldconf{'connfrom'}{$type} eq 'req') && ($secureconf{'connfrom'}{$type} eq 'no'))) {
                   7443:                 $connchange{$type} = 1;
                   7444:             }
                   7445:         }
                   7446:     }
                   7447:     if (keys(%connchange)) {
                   7448:         foreach my $child (keys(%active)) {
                   7449:             my $childip = $active{$child};
                   7450:             if ($childip ne '127.0.0.1') {
                   7451:                 my $childhostname  = gethostbyaddr(Socket::inet_aton($childip),AF_INET);
                   7452:                 if ($childhostname ne '') {
                   7453:                     my $childlonhost = &Apache::lonnet::get_server_homeID($childhostname);
                   7454:                     my ($samedom,$sameinst) = &set_client_info($childlonhost);
                   7455:                     if ($samedom) {
                   7456:                         if ($connchange{'dom'}) {
                   7457:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7458:                                    ." $child for ip $childip </font>");
                   7459:                             kill('INT', $child);
                   7460:                         }
                   7461:                     } elsif ($sameinst) {
                   7462:                         if ($connchange{'intdom'}) {
                   7463:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7464:                                    ." $child for ip $childip </font>");
                   7465:                            kill('INT', $child);
                   7466:                         }
                   7467:                     } else {
                   7468:                         if ($connchange{'other'}) {
                   7469:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7470:                                    ." $child for ip $childip </font>");
                   7471:                             kill('INT', $child);
                   7472:                         }
                   7473:                     }
                   7474:                 }
                   7475:             }
                   7476:         }
                   7477:     }
1.148     foxr     7478:     ReloadApache;
1.165     albertel 7479:     &status("Finished reloading hosts.tab");
1.144     foxr     7480: }
                   7481: 
1.57      www      7482: sub checkchildren {
1.165     albertel 7483:     &status("Checking on the children (sending signals)");
1.57      www      7484:     &initnewstatus();
                   7485:     &logstatus();
                   7486:     &logthis('Going to check on the children');
1.134     albertel 7487:     my $docdir=$perlvar{'lonDocRoot'};
1.61      harris41 7488:     foreach (sort keys %children) {
1.221     albertel 7489: 	#sleep 1;
1.57      www      7490:         unless (kill 'USR1' => $_) {
                   7491: 	    &logthis ('Child '.$_.' is dead');
                   7492:             &logstatus($$.' is dead');
1.221     albertel 7493: 	    delete($children{$_});
1.57      www      7494:         } 
1.61      harris41 7495:     }
1.63      www      7496:     sleep 5;
1.212     foxr     7497:     $SIG{ALRM} = sub { Debug("timeout"); 
                   7498: 		       die "timeout";  };
1.113     albertel 7499:     $SIG{__DIE__} = 'DEFAULT';
1.165     albertel 7500:     &status("Checking on the children (waiting for reports)");
1.63      www      7501:     foreach (sort keys %children) {
                   7502:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113     albertel 7503:           eval {
                   7504:             alarm(300);
1.63      www      7505: 	    &logthis('Child '.$_.' did not respond');
1.67      albertel 7506: 	    kill 9 => $_;
1.131     albertel 7507: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   7508: 	    #$subj="LON: $currenthostid killed lond process $_";
                   7509: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
                   7510: 	    #$execdir=$perlvar{'lonDaemons'};
                   7511: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.221     albertel 7512: 	    delete($children{$_});
1.113     albertel 7513: 	    alarm(0);
                   7514: 	  }
1.63      www      7515:         }
                   7516:     }
1.113     albertel 7517:     $SIG{ALRM} = 'DEFAULT';
1.155     albertel 7518:     $SIG{__DIE__} = \&catchexception;
1.165     albertel 7519:     &status("Finished checking children");
1.221     albertel 7520:     &logthis('Finished Checking children');
1.57      www      7521: }
                   7522: 
1.1       albertel 7523: # --------------------------------------------------------------------- Logging
                   7524: 
                   7525: sub logthis {
                   7526:     my $message=shift;
                   7527:     my $execdir=$perlvar{'lonDaemons'};
                   7528:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
                   7529:     my $now=time;
                   7530:     my $local=localtime($now);
1.58      www      7531:     $lastlog=$local.': '.$message;
1.1       albertel 7532:     print $fh "$local ($$): $message\n";
                   7533: }
                   7534: 
1.77      foxr     7535: # ------------------------- Conditional log if $DEBUG true.
                   7536: sub Debug {
                   7537:     my $message = shift;
                   7538:     if($DEBUG) {
                   7539: 	&logthis($message);
                   7540:     }
                   7541: }
1.161     foxr     7542: 
                   7543: #
                   7544: #   Sub to do replies to client.. this gives a hook for some
                   7545: #   debug tracing too:
                   7546: #  Parameters:
                   7547: #     fd      - File open on client.
                   7548: #     reply   - Text to send to client.
                   7549: #     request - Original request from client.
                   7550: #
1.490     droeschl 7551: #NOTE $reply must be terminated by exactly *one* \n. If $reply is a reference
                   7552: #this is done automatically ($$reply must not contain any \n in this case). 
                   7553: #If $reply is a string the caller has to ensure this.
1.161     foxr     7554: sub Reply {
1.192     foxr     7555:     my ($fd, $reply, $request) = @_;
1.387     albertel 7556:     if (ref($reply)) {
                   7557: 	print $fd $$reply;
                   7558: 	print $fd "\n";
                   7559: 	if ($DEBUG) { Debug("Request was $request  Reply was $$reply"); }
                   7560:     } else {
                   7561: 	print $fd $reply;
                   7562: 	if ($DEBUG) { Debug("Request was $request  Reply was $reply"); }
                   7563:     }
1.212     foxr     7564:     $Transactions++;
                   7565: }
                   7566: 
                   7567: 
                   7568: #
                   7569: #    Sub to report a failure.
                   7570: #    This function:
                   7571: #     -   Increments the failure statistic counters.
                   7572: #     -   Invokes Reply to send the error message to the client.
                   7573: # Parameters:
                   7574: #    fd       - File descriptor open on the client
                   7575: #    reply    - Reply text to emit.
                   7576: #    request  - The original request message (used by Reply
                   7577: #               to debug if that's enabled.
                   7578: # Implicit outputs:
                   7579: #    $Failures- The number of failures is incremented.
                   7580: #    Reply (invoked here) sends a message to the 
                   7581: #    client:
                   7582: #
                   7583: sub Failure {
                   7584:     my $fd      = shift;
                   7585:     my $reply   = shift;
                   7586:     my $request = shift;
                   7587:    
                   7588:     $Failures++;
                   7589:     Reply($fd, $reply, $request);      # That's simple eh?
1.161     foxr     7590: }
1.57      www      7591: # ------------------------------------------------------------------ Log status
                   7592: 
                   7593: sub logstatus {
1.178     foxr     7594:     &status("Doing logging");
                   7595:     my $docdir=$perlvar{'lonDocRoot'};
                   7596:     {
                   7597: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
1.200     matthew  7598:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
1.178     foxr     7599:         $fh->close();
                   7600:     }
1.221     albertel 7601:     &status("Finished $$.txt");
                   7602:     {
                   7603: 	open(LOG,">>$docdir/lon-status/londstatus.txt");
                   7604: 	flock(LOG,LOCK_EX);
                   7605: 	print LOG $$."\t".$clientname."\t".$currenthostid."\t"
                   7606: 	    .$status."\t".$lastlog."\t $keymode\n";
1.275     albertel 7607: 	flock(LOG,LOCK_UN);
1.221     albertel 7608: 	close(LOG);
                   7609:     }
1.178     foxr     7610:     &status("Finished logging");
1.57      www      7611: }
                   7612: 
                   7613: sub initnewstatus {
                   7614:     my $docdir=$perlvar{'lonDocRoot'};
                   7615:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
1.460     foxr     7616:     my $now=time();
1.57      www      7617:     my $local=localtime($now);
                   7618:     print $fh "LOND status $local - parent $$\n\n";
1.64      www      7619:     opendir(DIR,"$docdir/lon-status/londchld");
1.134     albertel 7620:     while (my $filename=readdir(DIR)) {
1.64      www      7621:         unlink("$docdir/lon-status/londchld/$filename");
                   7622:     }
                   7623:     closedir(DIR);
1.57      www      7624: }
                   7625: 
                   7626: # -------------------------------------------------------------- Status setting
                   7627: 
                   7628: sub status {
                   7629:     my $what=shift;
                   7630:     my $now=time;
                   7631:     my $local=localtime($now);
1.178     foxr     7632:     $status=$local.': '.$what;
                   7633:     $0='lond: '.$what.' '.$local;
1.57      www      7634: }
1.11      www      7635: 
1.13      www      7636: # -------------------------------------------------------------- Talk to lonsql
                   7637: 
1.234     foxr     7638: sub sql_reply {
1.12      harris41 7639:     my ($cmd)=@_;
1.234     foxr     7640:     my $answer=&sub_sql_reply($cmd);
                   7641:     if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
1.12      harris41 7642:     return $answer;
                   7643: }
                   7644: 
1.234     foxr     7645: sub sub_sql_reply {
1.12      harris41 7646:     my ($cmd)=@_;
                   7647:     my $unixsock="mysqlsock";
                   7648:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
                   7649:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                   7650:                                       Type    => SOCK_STREAM,
                   7651:                                       Timeout => 10)
                   7652:        or return "con_lost";
1.319     www      7653:     print $sclient "$cmd:$currentdomainid\n";
1.12      harris41 7654:     my $answer=<$sclient>;
                   7655:     chomp($answer);
                   7656:     if (!$answer) { $answer="con_lost"; }
                   7657:     return $answer;
                   7658: }
                   7659: 
1.1       albertel 7660: # --------------------------------------- Is this the home server of an author?
1.11      www      7661: 
1.1       albertel 7662: sub ishome {
                   7663:     my $author=shift;
                   7664:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   7665:     my ($udom,$uname)=split(/\//,$author);
                   7666:     my $proname=propath($udom,$uname);
                   7667:     if (-e $proname) {
                   7668: 	return 'owner';
                   7669:     } else {
                   7670:         return 'not_owner';
                   7671:     }
                   7672: }
                   7673: 
                   7674: # ======================================================= Continue main program
                   7675: # ---------------------------------------------------- Fork once and dissociate
                   7676: 
1.134     albertel 7677: my $fpid=fork;
1.1       albertel 7678: exit if $fpid;
1.29      harris41 7679: die "Couldn't fork: $!" unless defined ($fpid);
1.1       albertel 7680: 
1.29      harris41 7681: POSIX::setsid() or die "Can't start new session: $!";
1.1       albertel 7682: 
                   7683: # ------------------------------------------------------- Write our PID on disk
                   7684: 
1.134     albertel 7685: my $execdir=$perlvar{'lonDaemons'};
1.1       albertel 7686: open (PIDSAVE,">$execdir/logs/lond.pid");
                   7687: print PIDSAVE "$$\n";
                   7688: close(PIDSAVE);
1.190     albertel 7689: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.57      www      7690: &status('Starting');
1.1       albertel 7691: 
1.106     foxr     7692: 
1.1       albertel 7693: 
                   7694: # ----------------------------------------------------- Install signal handlers
                   7695: 
1.57      www      7696: 
1.1       albertel 7697: $SIG{CHLD} = \&REAPER;
                   7698: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   7699: $SIG{HUP}  = \&HUPSMAN;
1.57      www      7700: $SIG{USR1} = \&checkchildren;
1.144     foxr     7701: $SIG{USR2} = \&UpdateHosts;
1.106     foxr     7702: 
1.148     foxr     7703: #  Read the host hashes:
1.368     albertel 7704: &Apache::lonnet::load_hosts_tab();
1.447     raeburn  7705: my %iphost = &Apache::lonnet::get_iphost(1);
1.106     foxr     7706: 
1.480     raeburn  7707: $dist=`$perlvar{'lonDaemons'}/distprobe`;
1.286     albertel 7708: 
1.471     raeburn  7709: my $arch = `uname -i`;
1.475     raeburn  7710: chomp($arch);
1.471     raeburn  7711: if ($arch eq 'unknown') {
                   7712:     $arch = `uname -m`;
1.475     raeburn  7713:     chomp($arch);
1.471     raeburn  7714: }
                   7715: 
1.555     raeburn  7716: unless (lonssl::Read_Connect_Config(\%secureconf,\%perlvar,\%crlchecked) eq 'ok') {
1.532     raeburn  7717:     &logthis('<font color="blue">No connectionrules table. Will fallback to loncapa.conf</font>');
                   7718: }
                   7719: 
1.106     foxr     7720: # --------------------------------------------------------------
                   7721: #   Accept connections.  When a connection comes in, it is validated
                   7722: #   and if good, a child process is created to process transactions
                   7723: #   along the connection.
                   7724: 
1.1       albertel 7725: while (1) {
1.165     albertel 7726:     &status('Starting accept');
1.106     foxr     7727:     $client = $server->accept() or next;
1.165     albertel 7728:     &status('Accepted '.$client.' off to spawn');
1.386     albertel 7729:     make_new_child($client);
1.165     albertel 7730:     &status('Finished spawning');
1.1       albertel 7731: }
                   7732: 
1.212     foxr     7733: sub make_new_child {
                   7734:     my $pid;
                   7735: #    my $cipher;     # Now global
                   7736:     my $sigset;
1.178     foxr     7737: 
1.212     foxr     7738:     $client = shift;
                   7739:     &status('Starting new child '.$client);
                   7740:     &logthis('<font color="green"> Attempting to start child ('.$client.
                   7741: 	     ")</font>");    
                   7742:     # block signal for fork
                   7743:     $sigset = POSIX::SigSet->new(SIGINT);
                   7744:     sigprocmask(SIG_BLOCK, $sigset)
                   7745:         or die "Can't block SIGINT for fork: $!\n";
1.178     foxr     7746: 
1.212     foxr     7747:     die "fork: $!" unless defined ($pid = fork);
1.178     foxr     7748: 
1.212     foxr     7749:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
                   7750: 	                               # connection liveness.
1.178     foxr     7751: 
1.212     foxr     7752:     #
                   7753:     #  Figure out who we're talking to so we can record the peer in 
                   7754:     #  the pid hash.
                   7755:     #
                   7756:     my $caller = getpeername($client);
                   7757:     my ($port,$iaddr);
                   7758:     if (defined($caller) && length($caller) > 0) {
                   7759: 	($port,$iaddr)=unpack_sockaddr_in($caller);
                   7760:     } else {
                   7761: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
                   7762:     }
                   7763:     if (defined($iaddr)) {
                   7764: 	$clientip  = inet_ntoa($iaddr);
                   7765: 	Debug("Connected with $clientip");
                   7766:     } else {
                   7767: 	&logthis("Unable to determine clientip");
                   7768: 	$clientip='Unavailable';
                   7769:     }
                   7770:     
                   7771:     if ($pid) {
                   7772:         # Parent records the child's birth and returns.
                   7773:         sigprocmask(SIG_UNBLOCK, $sigset)
                   7774:             or die "Can't unblock SIGINT for fork: $!\n";
                   7775:         $children{$pid} = $clientip;
                   7776:         &status('Started child '.$pid);
1.462     foxr     7777: 	close($client);
1.212     foxr     7778:         return;
                   7779:     } else {
                   7780:         # Child can *not* return from this subroutine.
                   7781:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
                   7782:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
                   7783:                                 #don't get intercepted
                   7784:         $SIG{USR1}= \&logstatus;
                   7785:         $SIG{ALRM}= \&timeout;
1.468     foxr     7786: 	#
                   7787: 	# Block sigpipe as it gets thrownon socket disconnect and we want to 
                   7788: 	# deal with that as a read faiure instead.
                   7789: 	#
                   7790: 	my $blockset = POSIX::SigSet->new(SIGPIPE);
                   7791: 	sigprocmask(SIG_BLOCK, $blockset);
                   7792: 
1.212     foxr     7793:         $lastlog='Forked ';
                   7794:         $status='Forked';
1.178     foxr     7795: 
1.212     foxr     7796:         # unblock signals
                   7797:         sigprocmask(SIG_UNBLOCK, $sigset)
                   7798:             or die "Can't unblock SIGINT for fork: $!\n";
1.178     foxr     7799: 
1.212     foxr     7800: #        my $tmpsnum=0;            # Now global
                   7801: #---------------------------------------------------- kerberos 5 initialization
                   7802:         &Authen::Krb5::init_context();
1.511     raeburn  7803: 
                   7804:         my $no_ets;
1.570   ! raeburn  7805:         if ($dist =~ /^(?:centos|rhes|scientific|oracle|rocky|alma)(\d+)$/) {
1.511     raeburn  7806:             if ($1 >= 7) {
                   7807:                 $no_ets = 1;
                   7808:             }
                   7809:         } elsif ($dist =~ /^suse(\d+\.\d+)$/) {
                   7810:             if (($1 eq '9.3') || ($1 >= 12.2)) {
                   7811:                 $no_ets = 1; 
                   7812:             }
1.514     raeburn  7813:         } elsif ($dist =~ /^sles(\d+)$/) {
                   7814:             if ($1 > 11) {
                   7815:                 $no_ets = 1;
                   7816:             }
1.511     raeburn  7817:         } elsif ($dist =~ /^fedora(\d+)$/) {
                   7818:             if ($1 < 7) {
                   7819:                 $no_ets = 1;
                   7820:             }
                   7821:         }
                   7822:         unless ($no_ets) {
1.286     albertel 7823: 	    &Authen::Krb5::init_ets();
                   7824: 	}
1.209     albertel 7825: 
1.212     foxr     7826: 	&status('Accepted connection');
                   7827: # =============================================================================
                   7828:             # do something with the connection
                   7829: # -----------------------------------------------------------------------------
                   7830: 	# see if we know client and 'check' for spoof IP by ineffective challenge
1.178     foxr     7831: 
1.278     albertel 7832: 	my $outsideip=$clientip;
                   7833: 	if ($clientip eq '127.0.0.1') {
1.368     albertel 7834: 	    $outsideip=&Apache::lonnet::get_host_ip($perlvar{'lonHostID'});
1.278     albertel 7835: 	}
1.412     foxr     7836: 	&ReadManagerTable();
1.368     albertel 7837: 	my $clientrec=defined(&Apache::lonnet::get_hosts_from_ip($outsideip));
1.278     albertel 7838: 	my $ismanager=($managers{$outsideip}    ne undef);
1.432     raeburn  7839: 	$clientname  = "[unknown]";
1.212     foxr     7840: 	if($clientrec) {	# Establish client type.
                   7841: 	    $ConnectionType = "client";
1.368     albertel 7842: 	    $clientname = (&Apache::lonnet::get_hosts_from_ip($outsideip))[-1];
1.212     foxr     7843: 	    if($ismanager) {
                   7844: 		$ConnectionType = "both";
                   7845: 	    }
                   7846: 	} else {
                   7847: 	    $ConnectionType = "manager";
1.278     albertel 7848: 	    $clientname = $managers{$outsideip};
1.212     foxr     7849: 	}
1.556     raeburn  7850: 	my $clientok;
1.178     foxr     7851: 
1.212     foxr     7852: 	if ($clientrec || $ismanager) {
                   7853: 	    &status("Waiting for init from $clientip $clientname");
                   7854: 	    &logthis('<font color="yellow">INFO: Connection, '.
                   7855: 		     $clientip.
                   7856: 		  " ($clientname) connection type = $ConnectionType </font>" );
                   7857: 	    &status("Connecting $clientip  ($clientname))"); 
                   7858: 	    my $remotereq=<$client>;
                   7859: 	    chomp($remotereq);
                   7860: 	    Debug("Got init: $remotereq");
1.337     albertel 7861: 
1.212     foxr     7862: 	    if ($remotereq =~ /^init/) {
                   7863: 		&sethost("sethost:$perlvar{'lonHostID'}");
                   7864: 		#
                   7865: 		#  If the remote is attempting a local init... give that a try:
                   7866: 		#
1.432     raeburn  7867: 		(my $i, my $inittype, $clientversion) = split(/:/, $remotereq);
1.492     droeschl 7868:         # For LON-CAPA 2.9, the  client session will have sent its LON-CAPA
                   7869:         # version when initiating the connection. For LON-CAPA 2.8 and older,
                   7870:         # the version is retrieved from the global %loncaparevs in lonnet.pm.            
1.494     droeschl 7871:         # $clientversion contains path to keyfile if $inittype eq 'local'
                   7872:         # it's overridden below in this case
1.492     droeschl 7873:         $clientversion ||= $Apache::lonnet::loncaparevs{$clientname};
1.209     albertel 7874: 
1.212     foxr     7875: 		# If the connection type is ssl, but I didn't get my
                   7876: 		# certificate files yet, then I'll drop  back to 
                   7877: 		# insecure (if allowed).
1.532     raeburn  7878: 
                   7879:                 if ($inittype eq "ssl") {
                   7880:                     my $context;
                   7881:                     if ($clientsamedom) {
                   7882:                         $context = 'dom';
                   7883:                         if ($secureconf{'connfrom'}{'dom'} eq 'no') {
                   7884:                             $inittype = "";
                   7885:                         }
                   7886:                     } elsif ($clientsameinst) {
                   7887:                         $context = 'intdom';
                   7888:                         if ($secureconf{'connfrom'}{'intdom'} eq 'no') {
                   7889:                             $inittype = "";
                   7890:                         }
                   7891:                     } else {
                   7892:                         $context = 'other';
                   7893:                         if ($secureconf{'connfrom'}{'other'} eq 'no') {
                   7894:                             $inittype = "";
                   7895:                         }
                   7896:                     }
                   7897:                     if ($inittype eq '') {
                   7898:                         &logthis("<font color=\"blue\"> Domain config set "
                   7899:                                 ."to no ssl for $clientname (context: $context)"
                   7900:                                 ." -- trying insecure auth</font>");
                   7901:                     }
                   7902:                 }
                   7903: 
1.212     foxr     7904: 		if($inittype eq "ssl") {
                   7905: 		    my ($ca, $cert) = lonssl::CertificateFile;
                   7906: 		    my $kfile       = lonssl::KeyFile;
                   7907: 		    if((!$ca)   || 
                   7908: 		       (!$cert) || 
                   7909: 		       (!$kfile)) {
                   7910: 			$inittype = ""; # This forces insecure attempt.
                   7911: 			&logthis("<font color=\"blue\"> Certificates not "
                   7912: 				 ."installed -- trying insecure auth</font>");
1.224     foxr     7913: 		    } else {	# SSL certificates are in place so
1.212     foxr     7914: 		    }		# Leave the inittype alone.
                   7915: 		}
                   7916: 
                   7917: 		if($inittype eq "local") {
1.432     raeburn  7918:                     $clientversion = $perlvar{'lonVersion'};
1.212     foxr     7919: 		    my $key = LocalConnection($client, $remotereq);
                   7920: 		    if($key) {
                   7921: 			Debug("Got local key $key");
                   7922: 			$clientok     = 1;
                   7923: 			my $cipherkey = pack("H32", $key);
                   7924: 			$cipher       = new IDEA($cipherkey);
                   7925: 			print $client "ok:local\n";
1.442     www      7926: 			&logthis('<font color="green">'
1.212     foxr     7927: 				 . "Successful local authentication </font>");
                   7928: 			$keymode = "local"
1.178     foxr     7929: 		    } else {
1.212     foxr     7930: 			Debug("Failed to get local key");
                   7931: 			$clientok = 0;
                   7932: 			shutdown($client, 3);
                   7933: 			close $client;
1.178     foxr     7934: 		    }
1.212     foxr     7935: 		} elsif ($inittype eq "ssl") {
1.532     raeburn  7936: 		    my $key = SSLConnection($client,$clientname);
1.212     foxr     7937: 		    if ($key) {
                   7938: 			$clientok = 1;
                   7939: 			my $cipherkey = pack("H32", $key);
                   7940: 			$cipher       = new IDEA($cipherkey);
                   7941: 			&logthis('<font color="green">'
                   7942: 				 ."Successfull ssl authentication with $clientname </font>");
                   7943: 			$keymode = "ssl";
                   7944: 	     
1.178     foxr     7945: 		    } else {
1.212     foxr     7946: 			$clientok = 0;
                   7947: 			close $client;
1.178     foxr     7948: 		    }
1.212     foxr     7949: 	   
                   7950: 		} else {
                   7951: 		    my $ok = InsecureConnection($client);
                   7952: 		    if($ok) {
                   7953: 			$clientok = 1;
                   7954: 			&logthis('<font color="green">'
                   7955: 				 ."Successful insecure authentication with $clientname </font>");
                   7956: 			print $client "ok\n";
                   7957: 			$keymode = "insecure";
1.178     foxr     7958: 		    } else {
1.212     foxr     7959: 			&logthis('<font color="yellow">'
                   7960: 				  ."Attempted insecure connection disallowed </font>");
                   7961: 			close $client;
                   7962: 			$clientok = 0;
1.178     foxr     7963: 		    }
                   7964: 		}
1.212     foxr     7965: 	    } else {
                   7966: 		&logthis(
                   7967: 			 "<font color='blue'>WARNING: "
                   7968: 			 ."$clientip failed to initialize: >$remotereq< </font>");
                   7969: 		&status('No init '.$clientip);
                   7970: 	    }
                   7971: 	} else {
                   7972: 	    &logthis(
                   7973: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
                   7974: 	    &status('Hung up on '.$clientip);
                   7975: 	}
                   7976:  
                   7977: 	if ($clientok) {
                   7978: # ---------------- New known client connecting, could mean machine online again
1.368     albertel 7979: 	    if (&Apache::lonnet::get_host_ip($currenthostid) ne $clientip 
1.367     albertel 7980: 		&& $clientip ne '127.0.0.1') {
1.375     albertel 7981: 		&Apache::lonnet::reconlonc($clientname);
1.212     foxr     7982: 	    }
                   7983: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
                   7984: 	    &status('Will listen to '.$clientname);
                   7985: # ------------------------------------------------------------ Process requests
                   7986: 	    my $keep_going = 1;
                   7987: 	    my $user_input;
1.556     raeburn  7988: 
1.212     foxr     7989: 	    while(($user_input = get_request) && $keep_going) {
                   7990: 		alarm(120);
                   7991: 		Debug("Main: Got $user_input\n");
                   7992: 		$keep_going = &process_request($user_input);
1.178     foxr     7993: 		alarm(0);
1.569     raeburn  7994: 		&status('Listening to '.$clientname." ($keymode)");
1.161     foxr     7995: 	    }
1.212     foxr     7996: 
1.59      www      7997: # --------------------------------------------- client unknown or fishy, refuse
1.212     foxr     7998: 	}  else {
1.161     foxr     7999: 	    print $client "refused\n";
                   8000: 	    $client->close();
1.190     albertel 8001: 	    &logthis("<font color='blue'>WARNING: "
1.161     foxr     8002: 		     ."Rejected client $clientip, closing connection</font>");
                   8003: 	}
1.525     raeburn  8004:     }
1.161     foxr     8005:     
1.1       albertel 8006: # =============================================================================
1.161     foxr     8007:     
1.190     albertel 8008:     &logthis("<font color='red'>CRITICAL: "
1.161     foxr     8009: 	     ."Disconnect from $clientip ($clientname)</font>");    
1.569     raeburn  8010: 
                   8011: 
1.161     foxr     8012:     # this exit is VERY important, otherwise the child will become
                   8013:     # a producer of more and more children, forking yourself into
                   8014:     # process death.
                   8015:     exit;
1.106     foxr     8016:     
1.78      foxr     8017: }
1.532     raeburn  8018: 
                   8019: #
                   8020: #  Used to determine if a particular client is from the same domain
1.556     raeburn  8021: #  as the current server, or from the same internet domain, and
                   8022: #  also if the client can host sessions for the domain's users.
                   8023: #  A hash is populated with keys set to commands sent by the client
                   8024: #  which may not be executed for this domain.
1.532     raeburn  8025: #
                   8026: #  Optional input -- the client to check for domain and internet domain.
                   8027: #  If not specified, defaults to the package variable: $clientname
                   8028: #
                   8029: #  If called in array context will not set package variables, but will
                   8030: #  instead return an array of two values - (a) true if client is in the
1.556     raeburn  8031: #  same domain as the server, and (b) true if client is in the same 
                   8032: #  internet domain.
1.532     raeburn  8033: #
                   8034: #  If called in scalar context, sets package variables for current client:
                   8035: #
1.556     raeburn  8036: #  $clienthomedom    - LonCAPA domain of homeID for client.
                   8037: #  $clientsamedom    - LonCAPA domain same for this host and client.
                   8038: #  $clientintdom     - LonCAPA "internet domain" for client.
                   8039: #  $clientsameinst   - LonCAPA "internet domain" same for this host & client.
                   8040: #  $clientremoteok   - If current domain permits hosting on this client: 1
                   8041: #  %clientprohibited - Commands prohibited for domain's users for this client.
                   8042: #
                   8043: #  if the host and client have the same "internet domain", then the value
                   8044: #  of $clientremoteok is not used, and no commands are prohibited.
1.532     raeburn  8045: #
                   8046: #  returns 1 to indicate package variables have been set for current client.
                   8047: #
                   8048: 
                   8049: sub set_client_info {
                   8050:     my ($lonhost) = @_;
                   8051:     $lonhost ||= $clientname;
                   8052:     my $clienthost = &Apache::lonnet::hostname($lonhost);
                   8053:     my $clientserverhomeID = &Apache::lonnet::get_server_homeID($clienthost);
                   8054:     my $homedom = &Apache::lonnet::host_domain($clientserverhomeID);
                   8055:     my $samedom = 0;
1.557     raeburn  8056:     if ($perlvar{'lonDefDomain'} eq $homedom) {
1.532     raeburn  8057:         $samedom = 1;
                   8058:     }
                   8059:     my $intdom = &Apache::lonnet::internet_dom($clientserverhomeID);
                   8060:     my $sameinst = 0;
                   8061:     if ($intdom ne '') {
                   8062:         my $internet_names = &Apache::lonnet::get_internet_names($currenthostid);
                   8063:         if (ref($internet_names) eq 'ARRAY') {
                   8064:             if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   8065:                 $sameinst = 1;
                   8066:             }
                   8067:         }
                   8068:     }
                   8069:     if (wantarray) {
                   8070:         return ($samedom,$sameinst);
                   8071:     } else {
                   8072:         $clienthomedom = $homedom;
                   8073:         $clientsamedom = $samedom;
                   8074:         $clientintdom = $intdom;
                   8075:         $clientsameinst = $sameinst;
1.556     raeburn  8076:         if ($clientsameinst) {
                   8077:             undef($clientremoteok);
                   8078:             undef(%clientprohibited);
                   8079:         } else {
                   8080:             $clientremoteok = &get_remote_hostable($currentdomainid);
                   8081:             %clientprohibited = &get_prohibited($currentdomainid);
                   8082:         }
1.532     raeburn  8083:         return 1;
                   8084:     }
                   8085: }
                   8086: 
1.261     foxr     8087: #
                   8088: #   Determine if a user is an author for the indicated domain.
                   8089: #
                   8090: # Parameters:
                   8091: #    domain          - domain to check in .
                   8092: #    user            - Name of user to check.
                   8093: #
                   8094: # Return:
                   8095: #     1             - User is an author for domain.
                   8096: #     0             - User is not an author for domain.
                   8097: sub is_author {
                   8098:     my ($domain, $user) = @_;
                   8099: 
                   8100:     &Debug("is_author: $user @ $domain");
                   8101: 
                   8102:     my $hashref = &tie_user_hash($domain, $user, "roles",
                   8103: 				 &GDBM_READER());
                   8104: 
                   8105:     #  Author role should show up as a key /domain/_au
1.78      foxr     8106: 
1.321     albertel 8107:     my $value;
1.487     foxr     8108:     if ($hashref) {
1.78      foxr     8109: 
1.487     foxr     8110: 	my $key    = "/$domain/_au";
                   8111: 	if (defined($hashref)) {
                   8112: 	    $value = $hashref->{$key};
                   8113: 	    if(!untie_user_hash($hashref)) {
                   8114: 		return 'error: ' .  ($!+0)." untie (GDBM) Failed";
                   8115: 	    }
                   8116: 	}
                   8117: 	
                   8118: 	if(defined($value)) {
                   8119: 	    &Debug("$user @ $domain is an author");
                   8120: 	}
                   8121:     } else {
                   8122: 	return 'error: '.($!+0)." tie (GDBM) Failed";
1.261     foxr     8123:     }
                   8124: 
                   8125:     return defined($value);
                   8126: }
1.78      foxr     8127: #
                   8128: #   Checks to see if the input roleput request was to set
1.482     www      8129: # an author role.  If so, creates construction space 
1.78      foxr     8130: # Parameters:
                   8131: #    request   - The request sent to the rolesput subchunk.
                   8132: #                We're looking for  /domain/_au
                   8133: #    domain    - The domain in which the user is having roles doctored.
                   8134: #    user      - Name of the user for which the role is being put.
                   8135: #    authtype  - The authentication type associated with the user.
                   8136: #
1.289     albertel 8137: sub manage_permissions {
1.192     foxr     8138:     my ($request, $domain, $user, $authtype) = @_;
1.78      foxr     8139:     # See if the request is of the form /$domain/_au
1.289     albertel 8140:     if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
1.484     raeburn  8141:         my $path=$perlvar{'lonDocRoot'}."/priv/$domain";
1.482     www      8142:         unless (-e $path) {        
                   8143:            mkdir($path);
                   8144:         }
                   8145:         unless (-e $path.'/'.$user) {
                   8146:            mkdir($path.'/'.$user);
                   8147:         }
1.78      foxr     8148:     }
                   8149: }
1.222     foxr     8150: 
                   8151: 
                   8152: #
                   8153: #  Return the full path of a user password file, whether it exists or not.
                   8154: # Parameters:
                   8155: #   domain     - Domain in which the password file lives.
                   8156: #   user       - name of the user.
                   8157: # Returns:
                   8158: #    Full passwd path:
                   8159: #
                   8160: sub password_path {
                   8161:     my ($domain, $user) = @_;
1.264     albertel 8162:     return &propath($domain, $user).'/passwd';
1.222     foxr     8163: }
                   8164: 
                   8165: #   Password Filename
                   8166: #   Returns the path to a passwd file given domain and user... only if
                   8167: #  it exists.
                   8168: # Parameters:
                   8169: #   domain    - Domain in which to search.
                   8170: #   user      - username.
                   8171: # Returns:
                   8172: #   - If the password file exists returns its path.
                   8173: #   - If the password file does not exist, returns undefined.
                   8174: #
                   8175: sub password_filename {
                   8176:     my ($domain, $user) = @_;
                   8177: 
                   8178:     Debug ("PasswordFilename called: dom = $domain user = $user");
                   8179: 
                   8180:     my $path  = &password_path($domain, $user);
                   8181:     Debug("PasswordFilename got path: $path");
                   8182:     if(-e $path) {
                   8183: 	return $path;
                   8184:     } else {
                   8185: 	return undef;
                   8186:     }
                   8187: }
                   8188: 
                   8189: #
                   8190: #   Rewrite the contents of the user's passwd file.
                   8191: #  Parameters:
                   8192: #    domain    - domain of the user.
                   8193: #    name      - User's name.
                   8194: #    contents  - New contents of the file.
1.533     raeburn  8195: #    saveold   - (optional). If true save old file in a passwd.bak file.
1.222     foxr     8196: # Returns:
                   8197: #   0    - Failed.
                   8198: #   1    - Success.
                   8199: #
                   8200: sub rewrite_password_file {
1.533     raeburn  8201:     my ($domain, $user, $contents, $saveold) = @_;
1.222     foxr     8202: 
                   8203:     my $file = &password_filename($domain, $user);
                   8204:     if (defined $file) {
1.533     raeburn  8205:         if ($saveold) {
                   8206:             my $bakfile = $file.'.bak';
                   8207:             if (CopyFile($file,$bakfile)) {
                   8208:                 chmod(0400,$bakfile);
                   8209:                 &logthis("Old password saved in passwd.bak for internally authenticated user: $user:$domain");
                   8210:             } else {
                   8211:                 &logthis("Failed to save old password in passwd.bak for internally authenticated user: $user:$domain");
                   8212:             }
                   8213:         }
1.222     foxr     8214: 	my $pf = IO::File->new(">$file");
                   8215: 	if($pf) {
                   8216: 	    print $pf "$contents\n";
                   8217: 	    return 1;
                   8218: 	} else {
                   8219: 	    return 0;
                   8220: 	}
                   8221:     } else {
                   8222: 	return 0;
                   8223:     }
                   8224: 
                   8225: }
                   8226: 
1.78      foxr     8227: #
1.222     foxr     8228: #   get_auth_type - Determines the authorization type of a user in a domain.
1.78      foxr     8229: 
                   8230: #     Returns the authorization type or nouser if there is no such user.
                   8231: #
1.436     raeburn  8232: sub get_auth_type {
1.192     foxr     8233:     my ($domain, $user)  = @_;
1.78      foxr     8234: 
1.222     foxr     8235:     Debug("get_auth_type( $domain, $user ) \n");
1.78      foxr     8236:     my $proname    = &propath($domain, $user); 
                   8237:     my $passwdfile = "$proname/passwd";
                   8238:     if( -e $passwdfile ) {
                   8239: 	my $pf = IO::File->new($passwdfile);
                   8240: 	my $realpassword = <$pf>;
                   8241: 	chomp($realpassword);
1.79      foxr     8242: 	Debug("Password info = $realpassword\n");
1.78      foxr     8243: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79      foxr     8244: 	Debug("Authtype = $authtype, content = $contentpwd\n");
1.259     raeburn  8245: 	return "$authtype:$contentpwd";     
1.224     foxr     8246:     } else {
1.79      foxr     8247: 	Debug("Returning nouser");
1.78      foxr     8248: 	return "nouser";
                   8249:     }
1.1       albertel 8250: }
                   8251: 
1.220     foxr     8252: #
                   8253: #  Validate a user given their domain, name and password.  This utility
                   8254: #  function is used by both  AuthenticateHandler and ChangePasswordHandler
                   8255: #  to validate the login credentials of a user.
                   8256: # Parameters:
                   8257: #    $domain    - The domain being logged into (this is required due to
                   8258: #                 the capability for multihomed systems.
                   8259: #    $user      - The name of the user being validated.
                   8260: #    $password  - The user's propoposed password.
                   8261: #
                   8262: # Returns:
                   8263: #     1        - The domain,user,pasword triplet corresponds to a valid
                   8264: #                user.
                   8265: #     0        - The domain,user,password triplet is not a valid user.
                   8266: #
                   8267: sub validate_user {
1.396     raeburn  8268:     my ($domain, $user, $password, $checkdefauth) = @_;
1.220     foxr     8269: 
                   8270:     # Why negative ~pi you may well ask?  Well this function is about
                   8271:     # authentication, and therefore very important to get right.
                   8272:     # I've initialized the flag that determines whether or not I've 
                   8273:     # validated correctly to a value it's not supposed to get.
                   8274:     # At the end of this function. I'll ensure that it's not still that
                   8275:     # value so we don't just wind up returning some accidental value
                   8276:     # as a result of executing an unforseen code path that
1.249     foxr     8277:     # did not set $validated.  At the end of valid execution paths,
                   8278:     # validated shoule be 1 for success or 0 for failuer.
1.220     foxr     8279: 
                   8280:     my $validated = -3.14159;
                   8281: 
                   8282:     #  How we authenticate is determined by the type of authentication
                   8283:     #  the user has been assigned.  If the authentication type is
                   8284:     #  "nouser", the user does not exist so we will return 0.
                   8285: 
1.222     foxr     8286:     my $contents = &get_auth_type($domain, $user);
1.220     foxr     8287:     my ($howpwd, $contentpwd) = split(/:/, $contents);
                   8288: 
                   8289:     my $null = pack("C",0);	# Used by kerberos auth types.
                   8290: 
1.395     raeburn  8291:     if ($howpwd eq 'nouser') {
1.396     raeburn  8292:         if ($checkdefauth) {
                   8293:             my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   8294:             if ($domdefaults{'auth_def'} eq 'localauth') {
                   8295:                 $howpwd = $domdefaults{'auth_def'};
                   8296:                 $contentpwd = $domdefaults{'auth_arg_def'};
                   8297:             } elsif ((($domdefaults{'auth_def'} eq 'krb4') || 
                   8298:                       ($domdefaults{'auth_def'} eq 'krb5')) &&
                   8299:                      ($domdefaults{'auth_arg_def'} ne '')) {
                   8300:                 $howpwd = $domdefaults{'auth_def'};
                   8301:                 $contentpwd = $domdefaults{'auth_arg_def'}; 
                   8302:             }
1.395     raeburn  8303:         }
1.533     raeburn  8304:     }
1.220     foxr     8305:     if ($howpwd ne 'nouser') {
                   8306: 	if($howpwd eq "internal") { # Encrypted is in local password file.
1.518     raeburn  8307:             if (length($contentpwd) == 13) {
                   8308:                 $validated = (crypt($password,$contentpwd) eq $contentpwd);
                   8309:                 if ($validated) {
1.533     raeburn  8310:                     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   8311:                     if ($domdefaults{'intauth_switch'}) {
                   8312:                         my $ncpass = &hash_passwd($domain,$password);
                   8313:                         my $saveold;
                   8314:                         if ($domdefaults{'intauth_switch'} == 2) {
                   8315:                             $saveold = 1;
                   8316:                         }
                   8317:                         if (&rewrite_password_file($domain,$user,"$howpwd:$ncpass",$saveold)) {
                   8318:                             &update_passwd_history($user,$domain,$howpwd,'conversion');
                   8319:                             &logthis("Validated password hashed with bcrypt for $user:$domain");
                   8320:                         }
1.518     raeburn  8321:                     }
                   8322:                 }
                   8323:             } else {
1.533     raeburn  8324:                 $validated = &check_internal_passwd($password,$contentpwd,$domain,$user);
1.518     raeburn  8325:             }
1.220     foxr     8326: 	}
                   8327: 	elsif ($howpwd eq "unix") { # User is a normal unix user.
                   8328: 	    $contentpwd = (getpwnam($user))[1];
                   8329: 	    if($contentpwd) {
                   8330: 		if($contentpwd eq 'x') { # Shadow password file...
                   8331: 		    my $pwauth_path = "/usr/local/sbin/pwauth";
                   8332: 		    open PWAUTH,  "|$pwauth_path" or
                   8333: 			die "Cannot invoke authentication";
                   8334: 		    print PWAUTH "$user\n$password\n";
                   8335: 		    close PWAUTH;
                   8336: 		    $validated = ! $?;
                   8337: 
                   8338: 		} else { 	         # Passwords in /etc/passwd. 
                   8339: 		    $validated = (crypt($password,
                   8340: 					$contentpwd) eq $contentpwd);
                   8341: 		}
                   8342: 	    } else {
                   8343: 		$validated = 0;
                   8344: 	    }
1.439     raeburn  8345: 	} elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
                   8346:             my $checkwithkrb5 = 0;
                   8347:             if ($dist =~/^fedora(\d+)$/) {
                   8348:                 if ($1 > 11) {
                   8349:                     $checkwithkrb5 = 1;
                   8350:                 }
                   8351:             } elsif ($dist =~ /^suse([\d.]+)$/) {
                   8352:                 if ($1 > 11.1) {
                   8353:                     $checkwithkrb5 = 1; 
                   8354:                 }
                   8355:             }
                   8356:             if ($checkwithkrb5) {
                   8357:                 $validated = &krb5_authen($password,$null,$user,$contentpwd);
                   8358:             } else {
                   8359:                 $validated = &krb4_authen($password,$null,$user,$contentpwd);
                   8360:             }
1.224     foxr     8361: 	} elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
1.439     raeburn  8362:             $validated = &krb5_authen($password,$null,$user,$contentpwd);
1.224     foxr     8363: 	} elsif ($howpwd eq "localauth") { 
1.220     foxr     8364: 	    #  Authenticate via installation specific authentcation method:
                   8365: 	    $validated = &localauth::localauth($user, 
                   8366: 					       $password, 
1.353     albertel 8367: 					       $contentpwd,
                   8368: 					       $domain);
1.358     albertel 8369: 	    if ($validated < 0) {
1.357     albertel 8370: 		&logthis("localauth for $contentpwd $user:$domain returned a $validated");
                   8371: 		$validated = 0;
                   8372: 	    }
1.224     foxr     8373: 	} else {			# Unrecognized auth is also bad.
1.220     foxr     8374: 	    $validated = 0;
                   8375: 	}
                   8376:     } else {
                   8377: 	$validated = 0;
                   8378:     }
                   8379:     #
                   8380:     #  $validated has the correct stat of the authentication:
                   8381:     #
                   8382: 
                   8383:     unless ($validated != -3.14159) {
1.249     foxr     8384: 	#  I >really really< want to know if this happens.
                   8385: 	#  since it indicates that user authentication is badly
                   8386: 	#  broken in some code path.
                   8387:         #
                   8388: 	die "ValidateUser - failed to set the value of validated $domain, $user $password";
1.220     foxr     8389:     }
                   8390:     return $validated;
                   8391: }
                   8392: 
1.518     raeburn  8393: sub check_internal_passwd {
1.533     raeburn  8394:     my ($plainpass,$stored,$domain,$user) = @_;
1.518     raeburn  8395:     my (undef,$method,@rest) = split(/!/,$stored);
1.533     raeburn  8396:     if ($method eq 'bcrypt') {
1.518     raeburn  8397:         my $result = &hash_passwd($domain,$plainpass,@rest);
                   8398:         if ($result ne $stored) {
                   8399:             return 0;
                   8400:         }
1.533     raeburn  8401:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   8402:         if ($domdefaults{'intauth_check'}) {
                   8403:             # Upgrade to a larger number of rounds if necessary
                   8404:             my $defaultcost = $domdefaults{'intauth_cost'};
                   8405:             if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
                   8406:                 $defaultcost = 10;
                   8407:             }
                   8408:             if (int($rest[0])<int($defaultcost)) {
                   8409:                 if ($domdefaults{'intauth_check'} == 1) { 
                   8410:                     my $ncpass = &hash_passwd($domain,$plainpass);
                   8411:                     if (&rewrite_password_file($domain,$user,"internal:$ncpass")) {
                   8412:                         &update_passwd_history($user,$domain,'internal','update cost');
                   8413:                         &logthis("Validated password hashed with bcrypt for $user:$domain");
                   8414:                     }
                   8415:                     return 1;
                   8416:                 } elsif ($domdefaults{'intauth_check'} == 2) {
                   8417:                     return 0;
                   8418:                 }
                   8419:             }
                   8420:         } else {
                   8421:             return 1;
1.518     raeburn  8422:         }
                   8423:     }
                   8424:     return 0;
                   8425: }
                   8426: 
                   8427: sub get_last_authchg {
                   8428:     my ($domain,$user) = @_;
                   8429:     my $lastmod;
                   8430:     my $logname = &propath($domain,$user).'/passwd.log';
                   8431:     if (-e "$logname") {
                   8432:         $lastmod = (stat("$logname"))[9];
                   8433:     }
                   8434:     return $lastmod;
                   8435: }
                   8436: 
1.439     raeburn  8437: sub krb4_authen {
                   8438:     my ($password,$null,$user,$contentpwd) = @_;
                   8439:     my $validated = 0;
                   8440:     if (!($password =~ /$null/) ) {  # Null password not allowed.
                   8441:         eval {
                   8442:             require Authen::Krb4;
                   8443:         };
                   8444:         if (!$@) {
                   8445:             my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
                   8446:                                                        "",
                   8447:                                                        $contentpwd,,
                   8448:                                                        'krbtgt',
                   8449:                                                        $contentpwd,
                   8450:                                                        1,
                   8451:                                                        $password);
                   8452:             if(!$k4error) {
                   8453:                 $validated = 1;
                   8454:             } else {
                   8455:                 $validated = 0;
                   8456:                 &logthis('krb4: '.$user.', '.$contentpwd.', '.
                   8457:                           &Authen::Krb4::get_err_txt($Authen::Krb4::error));
                   8458:             }
                   8459:         } else {
                   8460:             $validated = krb5_authen($password,$null,$user,$contentpwd);
                   8461:         }
                   8462:     }
                   8463:     return $validated;
                   8464: }
                   8465: 
                   8466: sub krb5_authen {
                   8467:     my ($password,$null,$user,$contentpwd) = @_;
                   8468:     my $validated = 0;
                   8469:     if(!($password =~ /$null/)) { # Null password not allowed.
                   8470:         my $krbclient = &Authen::Krb5::parse_name($user.'@'
                   8471:                                                   .$contentpwd);
                   8472:         my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
                   8473:         my $krbserver  = &Authen::Krb5::parse_name($krbservice);
                   8474:         my $credentials= &Authen::Krb5::cc_default();
                   8475:         $credentials->initialize(&Authen::Krb5::parse_name($user.'@'
                   8476:                                                             .$contentpwd));
                   8477:         my $krbreturn;
                   8478:         if (exists(&Authen::Krb5::get_init_creds_password)) {
                   8479:             $krbreturn =
                   8480:                 &Authen::Krb5::get_init_creds_password($krbclient,$password,
                   8481:                                                           $krbservice);
                   8482:             $validated = (ref($krbreturn) eq 'Authen::Krb5::Creds');
                   8483:         } else {
                   8484:             $krbreturn  =
                   8485:                 &Authen::Krb5::get_in_tkt_with_password($krbclient,$krbserver,
                   8486:                                                          $password,$credentials);
                   8487:             $validated = ($krbreturn == 1);
                   8488:         }
                   8489:         if (!$validated) {
                   8490:             &logthis('krb5: '.$user.', '.$contentpwd.', '.
                   8491:                      &Authen::Krb5::error());
                   8492:         }
                   8493:     }
                   8494:     return $validated;
                   8495: }
1.220     foxr     8496: 
1.84      albertel 8497: sub addline {
                   8498:     my ($fname,$hostid,$ip,$newline)=@_;
                   8499:     my $contents;
                   8500:     my $found=0;
1.355     albertel 8501:     my $expr='^'.quotemeta($hostid).':'.quotemeta($ip).':';
1.134     albertel 8502:     my $sh;
1.84      albertel 8503:     if ($sh=IO::File->new("$fname.subscription")) {
                   8504: 	while (my $subline=<$sh>) {
                   8505: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
                   8506: 	}
                   8507: 	$sh->close();
                   8508:     }
                   8509:     $sh=IO::File->new(">$fname.subscription");
                   8510:     if ($contents) { print $sh $contents; }
                   8511:     if ($newline) { print $sh $newline; }
                   8512:     $sh->close();
                   8513:     return $found;
1.86      www      8514: }
                   8515: 
1.234     foxr     8516: sub get_chat {
1.324     raeburn  8517:     my ($cdom,$cname,$udom,$uname,$group)=@_;
1.310     albertel 8518: 
1.87      www      8519:     my @entries=();
1.324     raeburn  8520:     my $namespace = 'nohist_chatroom';
                   8521:     my $namespace_inroom = 'nohist_inchatroom';
1.335     albertel 8522:     if ($group ne '') {
1.324     raeburn  8523:         $namespace .= '_'.$group;
                   8524:         $namespace_inroom .= '_'.$group;
                   8525:     }
                   8526:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 8527: 				 &GDBM_READER());
                   8528:     if ($hashref) {
                   8529: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.311     albertel 8530: 	&untie_user_hash($hashref);
1.123     www      8531:     }
1.124     www      8532:     my @participants=();
1.134     albertel 8533:     my $cutoff=time-60;
1.324     raeburn  8534:     $hashref = &tie_user_hash($cdom, $cname, $namespace_inroom,
1.310     albertel 8535: 			      &GDBM_WRCREAT());
                   8536:     if ($hashref) {
                   8537:         $hashref->{$uname.':'.$udom}=time;
                   8538:         foreach my $user (sort(keys(%$hashref))) {
                   8539: 	    if ($hashref->{$user}>$cutoff) {
                   8540: 		push(@participants, 'active_participant:'.$user);
1.123     www      8541:             }
                   8542:         }
1.311     albertel 8543:         &untie_user_hash($hashref);
1.86      www      8544:     }
1.124     www      8545:     return (@participants,@entries);
1.86      www      8546: }
                   8547: 
1.234     foxr     8548: sub chat_add {
1.324     raeburn  8549:     my ($cdom,$cname,$newchat,$group)=@_;
1.88      albertel 8550:     my @entries=();
1.142     www      8551:     my $time=time;
1.324     raeburn  8552:     my $namespace = 'nohist_chatroom';
                   8553:     my $logfile = 'chatroom.log';
1.335     albertel 8554:     if ($group ne '') {
1.324     raeburn  8555:         $namespace .= '_'.$group;
                   8556:         $logfile = 'chatroom_'.$group.'.log';
                   8557:     }
                   8558:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 8559: 				 &GDBM_WRCREAT());
                   8560:     if ($hashref) {
                   8561: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.88      albertel 8562: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
                   8563: 	my ($thentime,$idnum)=split(/\_/,$lastid);
                   8564: 	my $newid=$time.'_000000';
                   8565: 	if ($thentime==$time) {
                   8566: 	    $idnum=~s/^0+//;
                   8567: 	    $idnum++;
                   8568: 	    $idnum=substr('000000'.$idnum,-6,6);
                   8569: 	    $newid=$time.'_'.$idnum;
                   8570: 	}
1.310     albertel 8571: 	$hashref->{$newid}=$newchat;
1.88      albertel 8572: 	my $expired=$time-3600;
1.310     albertel 8573: 	foreach my $comment (keys(%$hashref)) {
                   8574: 	    my ($thistime) = ($comment=~/(\d+)\_/);
1.88      albertel 8575: 	    if ($thistime<$expired) {
1.310     albertel 8576: 		delete $hashref->{$comment};
1.88      albertel 8577: 	    }
                   8578: 	}
1.310     albertel 8579: 	{
                   8580: 	    my $proname=&propath($cdom,$cname);
1.324     raeburn  8581: 	    if (open(CHATLOG,">>$proname/$logfile")) { 
1.310     albertel 8582: 		print CHATLOG ("$time:".&unescape($newchat)."\n");
                   8583: 	    }
                   8584: 	    close(CHATLOG);
1.142     www      8585: 	}
1.311     albertel 8586: 	&untie_user_hash($hashref);
1.86      www      8587:     }
1.84      albertel 8588: }
                   8589: 
                   8590: sub unsub {
                   8591:     my ($fname,$clientip)=@_;
                   8592:     my $result;
1.188     foxr     8593:     my $unsubs = 0;		# Number of successful unsubscribes:
                   8594: 
                   8595: 
                   8596:     # An old way subscriptions were handled was to have a 
                   8597:     # subscription marker file:
                   8598: 
                   8599:     Debug("Attempting unlink of $fname.$clientname");
1.161     foxr     8600:     if (unlink("$fname.$clientname")) {
1.188     foxr     8601: 	$unsubs++;		# Successful unsub via marker file.
                   8602:     } 
                   8603: 
                   8604:     # The more modern way to do it is to have a subscription list
                   8605:     # file:
                   8606: 
1.84      albertel 8607:     if (-e "$fname.subscription") {
1.161     foxr     8608: 	my $found=&addline($fname,$clientname,$clientip,'');
1.188     foxr     8609: 	if ($found) { 
                   8610: 	    $unsubs++;
                   8611: 	}
                   8612:     } 
                   8613: 
                   8614:     #  If either or both of these mechanisms succeeded in unsubscribing a 
                   8615:     #  resource we can return ok:
                   8616: 
                   8617:     if($unsubs) {
                   8618: 	$result = "ok\n";
1.84      albertel 8619:     } else {
1.188     foxr     8620: 	$result = "not_subscribed\n";
1.84      albertel 8621:     }
1.188     foxr     8622: 
1.84      albertel 8623:     return $result;
                   8624: }
                   8625: 
1.101     www      8626: sub currentversion {
                   8627:     my $fname=shift;
                   8628:     my $version=-1;
                   8629:     my $ulsdir='';
                   8630:     if ($fname=~/^(.+)\/[^\/]+$/) {
                   8631:        $ulsdir=$1;
                   8632:     }
1.114     albertel 8633:     my ($fnamere1,$fnamere2);
                   8634:     # remove version if already specified
1.101     www      8635:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114     albertel 8636:     # get the bits that go before and after the version number
                   8637:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
                   8638: 	$fnamere1=$1;
                   8639: 	$fnamere2='.'.$2;
                   8640:     }
1.101     www      8641:     if (-e $fname) { $version=1; }
                   8642:     if (-e $ulsdir) {
1.134     albertel 8643: 	if(-d $ulsdir) {
                   8644: 	    if (opendir(LSDIR,$ulsdir)) {
                   8645: 		my $ulsfn;
                   8646: 		while ($ulsfn=readdir(LSDIR)) {
1.101     www      8647: # see if this is a regular file (ignore links produced earlier)
1.134     albertel 8648: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
                   8649: 		    unless (-l $thisfile) {
1.160     www      8650: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134     albertel 8651: 			    if ($1>$version) { $version=$1; }
                   8652: 			}
                   8653: 		    }
                   8654: 		}
                   8655: 		closedir(LSDIR);
                   8656: 		$version++;
                   8657: 	    }
                   8658: 	}
                   8659:     }
                   8660:     return $version;
1.101     www      8661: }
                   8662: 
                   8663: sub thisversion {
                   8664:     my $fname=shift;
                   8665:     my $version=-1;
                   8666:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
                   8667: 	$version=$1;
                   8668:     }
                   8669:     return $version;
                   8670: }
                   8671: 
1.84      albertel 8672: sub subscribe {
                   8673:     my ($userinput,$clientip)=@_;
                   8674:     my $result;
1.293     albertel 8675:     my ($cmd,$fname)=split(/:/,$userinput,2);
1.84      albertel 8676:     my $ownership=&ishome($fname);
                   8677:     if ($ownership eq 'owner') {
1.101     www      8678: # explitly asking for the current version?
                   8679:         unless (-e $fname) {
                   8680:             my $currentversion=&currentversion($fname);
                   8681: 	    if (&thisversion($fname)==$currentversion) {
                   8682:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
                   8683: 		    my $root=$1;
                   8684:                     my $extension=$2;
                   8685:                     symlink($root.'.'.$extension,
                   8686:                             $root.'.'.$currentversion.'.'.$extension);
1.102     www      8687:                     unless ($extension=~/\.meta$/) {
                   8688:                        symlink($root.'.'.$extension.'.meta',
                   8689:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
                   8690: 		    }
1.101     www      8691:                 }
                   8692:             }
                   8693:         }
1.84      albertel 8694: 	if (-e $fname) {
                   8695: 	    if (-d $fname) {
                   8696: 		$result="directory\n";
                   8697: 	    } else {
1.161     foxr     8698: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134     albertel 8699: 		my $now=time;
1.161     foxr     8700: 		my $found=&addline($fname,$clientname,$clientip,
                   8701: 				   "$clientname:$clientip:$now\n");
1.84      albertel 8702: 		if ($found) { $result="$fname\n"; }
                   8703: 		# if they were subscribed to only meta data, delete that
                   8704:                 # subscription, when you subscribe to a file you also get
                   8705:                 # the metadata
                   8706: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
                   8707: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
1.476     raeburn  8708:                 my $protocol = $Apache::lonnet::protocol{$perlvar{'lonHostID'}};
                   8709:                 $protocol = 'http' if ($protocol ne 'https');
                   8710: 		$fname=$protocol.'://'.&Apache::lonnet::hostname($perlvar{'lonHostID'})."/".$fname;
1.84      albertel 8711: 		$result="$fname\n";
                   8712: 	    }
                   8713: 	} else {
                   8714: 	    $result="not_found\n";
                   8715: 	}
                   8716:     } else {
                   8717: 	$result="rejected\n";
                   8718:     }
                   8719:     return $result;
                   8720: }
1.287     foxr     8721: #  Change the passwd of a unix user.  The caller must have
                   8722: #  first verified that the user is a loncapa user.
                   8723: #
                   8724: # Parameters:
                   8725: #    user      - Unix user name to change.
                   8726: #    pass      - New password for the user.
                   8727: # Returns:
                   8728: #    ok    - if success
                   8729: #    other - Some meaningfule error message string.
                   8730: # NOTE:
                   8731: #    invokes a setuid script to change the passwd.
                   8732: sub change_unix_password {
                   8733:     my ($user, $pass) = @_;
                   8734: 
                   8735:     &Debug("change_unix_password");
                   8736:     my $execdir=$perlvar{'lonDaemons'};
                   8737:     &Debug("Opening lcpasswd pipeline");
                   8738:     my $pf = IO::File->new("|$execdir/lcpasswd > "
                   8739: 			   ."$perlvar{'lonDaemons'}"
                   8740: 			   ."/logs/lcpasswd.log");
                   8741:     print $pf "$user\n$pass\n$pass\n";
                   8742:     close $pf;
                   8743:     my $err = $?;
                   8744:     return ($err < @passwderrors) ? $passwderrors[$err] : 
                   8745: 	"pwchange_falure - unknown error";
                   8746: 
                   8747:     
                   8748: }
                   8749: 
1.91      albertel 8750: 
                   8751: sub make_passwd_file {
1.518     raeburn  8752:     my ($uname,$udom,$umode,$npass,$passfilename,$action)=@_;
1.390     raeburn  8753:     my $result="ok";
1.91      albertel 8754:     if ($umode eq 'krb4' or $umode eq 'krb5') {
                   8755: 	{
                   8756: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8757: 	    if ($pf) {
                   8758: 		print $pf "$umode:$npass\n";
1.518     raeburn  8759:                 &update_passwd_history($uname,$udom,$umode,$action);
1.261     foxr     8760: 	    } else {
                   8761: 		$result = "pass_file_failed_error";
                   8762: 	    }
1.91      albertel 8763: 	}
                   8764:     } elsif ($umode eq 'internal') {
1.518     raeburn  8765:         my $ncpass = &hash_passwd($udom,$npass);
1.91      albertel 8766: 	{
                   8767: 	    &Debug("Creating internal auth");
                   8768: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8769: 	    if($pf) {
1.518     raeburn  8770: 		print $pf "internal:$ncpass\n";
                   8771:                 &update_passwd_history($uname,$udom,$umode,$action); 
1.261     foxr     8772: 	    } else {
                   8773: 		$result = "pass_file_failed_error";
                   8774: 	    }
1.91      albertel 8775: 	}
                   8776:     } elsif ($umode eq 'localauth') {
                   8777: 	{
                   8778: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8779: 	    if($pf) {
                   8780: 		print $pf "localauth:$npass\n";
1.524     raeburn  8781:                 &update_passwd_history($uname,$udom,$umode,$action);
1.261     foxr     8782: 	    } else {
                   8783: 		$result = "pass_file_failed_error";
                   8784: 	    }
1.91      albertel 8785: 	}
                   8786:     } elsif ($umode eq 'unix') {
1.502     raeburn  8787: 	&logthis(">>>Attempt to create unix account blocked -- unix auth not available for new users.");
                   8788: 	$result="no_new_unix_accounts";
1.91      albertel 8789:     } elsif ($umode eq 'none') {
                   8790: 	{
1.223     foxr     8791: 	    my $pf = IO::File->new("> $passfilename");
1.261     foxr     8792: 	    if($pf) {
                   8793: 		print $pf "none:\n";
                   8794: 	    } else {
                   8795: 		$result = "pass_file_failed_error";
                   8796: 	    }
1.91      albertel 8797: 	}
1.543     raeburn  8798:     } elsif ($umode eq 'lti') {
                   8799:         my $pf = IO::File->new(">$passfilename");
                   8800:         if($pf) {
                   8801:             print $pf "lti:\n";
                   8802:             &update_passwd_history($uname,$udom,$umode,$action);
                   8803:         } else {
                   8804:             $result = "pass_file_failed_error";
                   8805:         }
1.91      albertel 8806:     } else {
1.390     raeburn  8807: 	$result="auth_mode_error";
1.91      albertel 8808:     }
                   8809:     return $result;
1.121     albertel 8810: }
                   8811: 
1.265     albertel 8812: sub convert_photo {
                   8813:     my ($start,$dest)=@_;
                   8814:     system("convert $start $dest");
                   8815: }
                   8816: 
1.121     albertel 8817: sub sethost {
                   8818:     my ($remotereq) = @_;
                   8819:     my (undef,$hostid)=split(/:/,$remotereq);
1.322     albertel 8820:     # ignore sethost if we are already correct
                   8821:     if ($hostid eq $currenthostid) {
                   8822: 	return 'ok';
                   8823:     }
                   8824: 
1.121     albertel 8825:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
1.368     albertel 8826:     if (&Apache::lonnet::get_host_ip($perlvar{'lonHostID'}) 
                   8827: 	eq &Apache::lonnet::get_host_ip($hostid)) {
1.200     matthew  8828: 	$currenthostid  =$hostid;
1.369     albertel 8829: 	$currentdomainid=&Apache::lonnet::host_domain($hostid);
1.556     raeburn  8830:         &set_client_info();
1.443     www      8831: #	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
1.121     albertel 8832:     } else {
                   8833: 	&logthis("Requested host id $hostid not an alias of ".
                   8834: 		 $perlvar{'lonHostID'}." refusing connection");
                   8835: 	return 'unable_to_set';
                   8836:     }
                   8837:     return 'ok';
                   8838: }
                   8839: 
                   8840: sub version {
                   8841:     my ($userinput)=@_;
                   8842:     $remoteVERSION=(split(/:/,$userinput))[1];
                   8843:     return "version:$VERSION";
1.127     albertel 8844: }
1.178     foxr     8845: 
1.447     raeburn  8846: sub get_usersession_config {
                   8847:     my ($dom,$name) = @_;
                   8848:     my ($usersessionconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8849:     if (defined($cached)) {
                   8850:         return $usersessionconf;
                   8851:     } else {
                   8852:         my %domconfig = &Apache::lonnet::get_dom('configuration',['usersessions'],$dom);
1.525     raeburn  8853:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'usersessions'},3600);
                   8854:         return $domconfig{'usersessions'};
1.447     raeburn  8855:     }
                   8856:     return;
                   8857: }
1.200     matthew  8858: 
1.534     raeburn  8859: sub get_usersearch_config {
                   8860:     my ($dom,$name) = @_;
                   8861:     my ($usersearchconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8862:     if (defined($cached)) {
                   8863:         return $usersearchconf;
                   8864:     } else {
                   8865:         my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$dom);
                   8866:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'directorysrch'},600);
                   8867:         return $domconfig{'directorysrch'};
                   8868:     }
                   8869:     return;
                   8870: }
                   8871: 
1.525     raeburn  8872: sub get_prohibited {
                   8873:     my ($dom) = @_;
                   8874:     my $name = 'trust';
                   8875:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8876:     unless (defined($cached)) {
                   8877:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$dom);
                   8878:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'trust'},3600);
                   8879:         $trustconfig = $domconfig{'trust'};
                   8880:     }
                   8881:     my %prohibited;
                   8882:     if (ref($trustconfig)) {
                   8883:         foreach my $prefix (keys(%{$trustconfig})) {
                   8884:             if (ref($trustconfig->{$prefix}) eq 'HASH') {
                   8885:                 my $reject;
                   8886:                 if (ref($trustconfig->{$prefix}->{'exc'}) eq 'ARRAY') {
                   8887:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'exc'}})) {
                   8888:                         $reject = 1;
                   8889:                     }
                   8890:                 }
                   8891:                 if (ref($trustconfig->{$prefix}->{'inc'}) eq 'ARRAY') {
                   8892:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'inc'}})) {
                   8893:                         $reject = 0;
                   8894:                     } else {
                   8895:                         $reject = 1;
                   8896:                     }
                   8897:                 }
                   8898:                 if ($reject) {
                   8899:                     $prohibited{$prefix} = 1;
                   8900:                 }
                   8901:             }
                   8902:         }
                   8903:     }
                   8904:     return %prohibited;
                   8905: }
1.450     raeburn  8906: 
1.556     raeburn  8907: sub get_remote_hostable {
                   8908:     my ($dom) = @_;
                   8909:     my $result;
                   8910:     if ($clientintdom) {
                   8911:         $result = 1;
                   8912:         my $remsessconf = &get_usersession_config($dom,'remotesession');
                   8913:         if (ref($remsessconf) eq 'HASH') {
                   8914:             if (ref($remsessconf->{'remote'}) eq 'HASH') {
                   8915:                 if (ref($remsessconf->{'remote'}->{'excludedomain'}) eq 'ARRAY') {
                   8916:                     if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'excludedomain'}})) {
                   8917:                         $result = 0;
                   8918:                     }
                   8919:                 }
                   8920:                 if (ref($remsessconf->{'remote'}->{'includedomain'}) eq 'ARRAY') {
                   8921:                     if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'includedomain'}})) {
                   8922:                         $result = 1;
                   8923:                     } else {
                   8924:                         $result = 0;
                   8925:                     }
                   8926:                 }
                   8927:             }
                   8928:         }
                   8929:     }
                   8930:     return $result;
                   8931: }
                   8932: 
1.471     raeburn  8933: sub distro_and_arch {
                   8934:     return $dist.':'.$arch;
                   8935: }
                   8936: 
1.61      harris41 8937: # ----------------------------------- POD (plain old documentation, CPAN style)
                   8938: 
                   8939: =head1 NAME
                   8940: 
                   8941: lond - "LON Daemon" Server (port "LOND" 5663)
                   8942: 
                   8943: =head1 SYNOPSIS
                   8944: 
1.74      harris41 8945: Usage: B<lond>
                   8946: 
                   8947: Should only be run as user=www.  This is a command-line script which
                   8948: is invoked by B<loncron>.  There is no expectation that a typical user
                   8949: will manually start B<lond> from the command-line.  (In other words,
                   8950: DO NOT START B<lond> YOURSELF.)
1.61      harris41 8951: 
                   8952: =head1 DESCRIPTION
                   8953: 
1.74      harris41 8954: There are two characteristics associated with the running of B<lond>,
                   8955: PROCESS MANAGEMENT (starting, stopping, handling child processes)
                   8956: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
                   8957: subscriptions, etc).  These are described in two large
                   8958: sections below.
                   8959: 
                   8960: B<PROCESS MANAGEMENT>
                   8961: 
1.61      harris41 8962: Preforker - server who forks first. Runs as a daemon. HUPs.
                   8963: Uses IDEA encryption
                   8964: 
1.74      harris41 8965: B<lond> forks off children processes that correspond to the other servers
                   8966: in the network.  Management of these processes can be done at the
                   8967: parent process level or the child process level.
                   8968: 
                   8969: B<logs/lond.log> is the location of log messages.
                   8970: 
                   8971: The process management is now explained in terms of linux shell commands,
                   8972: subroutines internal to this code, and signal assignments:
                   8973: 
                   8974: =over 4
                   8975: 
                   8976: =item *
                   8977: 
                   8978: PID is stored in B<logs/lond.pid>
                   8979: 
                   8980: This is the process id number of the parent B<lond> process.
                   8981: 
                   8982: =item *
                   8983: 
                   8984: SIGTERM and SIGINT
                   8985: 
                   8986: Parent signal assignment:
                   8987:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   8988: 
                   8989: Child signal assignment:
                   8990:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
                   8991: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
                   8992:  to restart a new child.)
                   8993: 
                   8994: Command-line invocations:
                   8995:  B<kill> B<-s> SIGTERM I<PID>
                   8996:  B<kill> B<-s> SIGINT I<PID>
                   8997: 
                   8998: Subroutine B<HUNTSMAN>:
                   8999:  This is only invoked for the B<lond> parent I<PID>.
                   9000: This kills all the children, and then the parent.
                   9001: The B<lonc.pid> file is cleared.
                   9002: 
                   9003: =item *
                   9004: 
                   9005: SIGHUP
                   9006: 
                   9007: Current bug:
                   9008:  This signal can only be processed the first time
                   9009: on the parent process.  Subsequent SIGHUP signals
                   9010: have no effect.
                   9011: 
                   9012: Parent signal assignment:
                   9013:  $SIG{HUP}  = \&HUPSMAN;
                   9014: 
                   9015: Child signal assignment:
                   9016:  none (nothing happens)
                   9017: 
                   9018: Command-line invocations:
                   9019:  B<kill> B<-s> SIGHUP I<PID>
                   9020: 
                   9021: Subroutine B<HUPSMAN>:
                   9022:  This is only invoked for the B<lond> parent I<PID>,
                   9023: This kills all the children, and then the parent.
                   9024: The B<lond.pid> file is cleared.
                   9025: 
                   9026: =item *
                   9027: 
                   9028: SIGUSR1
                   9029: 
                   9030: Parent signal assignment:
                   9031:  $SIG{USR1} = \&USRMAN;
                   9032: 
                   9033: Child signal assignment:
                   9034:  $SIG{USR1}= \&logstatus;
                   9035: 
                   9036: Command-line invocations:
                   9037:  B<kill> B<-s> SIGUSR1 I<PID>
                   9038: 
                   9039: Subroutine B<USRMAN>:
                   9040:  When invoked for the B<lond> parent I<PID>,
                   9041: SIGUSR1 is sent to all the children, and the status of
                   9042: each connection is logged.
1.144     foxr     9043: 
                   9044: =item *
                   9045: 
                   9046: SIGUSR2
                   9047: 
                   9048: Parent Signal assignment:
                   9049:     $SIG{USR2} = \&UpdateHosts
                   9050: 
                   9051: Child signal assignment:
                   9052:     NONE
                   9053: 
1.74      harris41 9054: 
                   9055: =item *
                   9056: 
                   9057: SIGCHLD
                   9058: 
                   9059: Parent signal assignment:
                   9060:  $SIG{CHLD} = \&REAPER;
                   9061: 
                   9062: Child signal assignment:
                   9063:  none
                   9064: 
                   9065: Command-line invocations:
                   9066:  B<kill> B<-s> SIGCHLD I<PID>
                   9067: 
                   9068: Subroutine B<REAPER>:
                   9069:  This is only invoked for the B<lond> parent I<PID>.
                   9070: Information pertaining to the child is removed.
                   9071: The socket port is cleaned up.
                   9072: 
                   9073: =back
                   9074: 
                   9075: B<SERVER-SIDE ACTIVITIES>
                   9076: 
                   9077: Server-side information can be accepted in an encrypted or non-encrypted
                   9078: method.
                   9079: 
                   9080: =over 4
                   9081: 
                   9082: =item ping
                   9083: 
                   9084: Query a client in the hosts.tab table; "Are you there?"
                   9085: 
                   9086: =item pong
                   9087: 
                   9088: Respond to a ping query.
                   9089: 
                   9090: =item ekey
                   9091: 
                   9092: Read in encrypted key, make cipher.  Respond with a buildkey.
                   9093: 
                   9094: =item load
                   9095: 
                   9096: Respond with CPU load based on a computation upon /proc/loadavg.
                   9097: 
                   9098: =item currentauth
                   9099: 
                   9100: Reply with current authentication information (only over an
                   9101: encrypted channel).
                   9102: 
                   9103: =item auth
                   9104: 
                   9105: Only over an encrypted channel, reply as to whether a user's
                   9106: authentication information can be validated.
                   9107: 
                   9108: =item passwd
                   9109: 
                   9110: Allow for a password to be set.
                   9111: 
                   9112: =item makeuser
                   9113: 
                   9114: Make a user.
                   9115: 
1.517     raeburn  9116: =item changeuserauth
1.74      harris41 9117: 
                   9118: Allow for authentication mechanism and password to be changed.
                   9119: 
                   9120: =item home
1.61      harris41 9121: 
1.74      harris41 9122: Respond to a question "are you the home for a given user?"
                   9123: 
                   9124: =item update
                   9125: 
                   9126: Update contents of a subscribed resource.
                   9127: 
                   9128: =item unsubscribe
                   9129: 
                   9130: The server is unsubscribing from a resource.
                   9131: 
                   9132: =item subscribe
                   9133: 
                   9134: The server is subscribing to a resource.
                   9135: 
                   9136: =item log
                   9137: 
                   9138: Place in B<logs/lond.log>
                   9139: 
                   9140: =item put
                   9141: 
                   9142: stores hash in namespace
                   9143: 
1.496     raeburn  9144: =item rolesput
1.74      harris41 9145: 
                   9146: put a role into a user's environment
                   9147: 
                   9148: =item get
                   9149: 
                   9150: returns hash with keys from array
                   9151: reference filled in from namespace
                   9152: 
                   9153: =item eget
                   9154: 
                   9155: returns hash with keys from array
                   9156: reference filled in from namesp (encrypts the return communication)
                   9157: 
                   9158: =item rolesget
                   9159: 
                   9160: get a role from a user's environment
                   9161: 
                   9162: =item del
                   9163: 
                   9164: deletes keys out of array from namespace
                   9165: 
                   9166: =item keys
                   9167: 
                   9168: returns namespace keys
                   9169: 
                   9170: =item dump
                   9171: 
                   9172: dumps the complete (or key matching regexp) namespace into a hash
                   9173: 
                   9174: =item store
                   9175: 
                   9176: stores hash permanently
                   9177: for this url; hashref needs to be given and should be a \%hashname; the
                   9178: remaining args aren't required and if they aren't passed or are '' they will
                   9179: be derived from the ENV
                   9180: 
                   9181: =item restore
                   9182: 
                   9183: returns a hash for a given url
                   9184: 
                   9185: =item querysend
                   9186: 
                   9187: Tells client about the lonsql process that has been launched in response
                   9188: to a sent query.
                   9189: 
                   9190: =item queryreply
                   9191: 
                   9192: Accept information from lonsql and make appropriate storage in temporary
                   9193: file space.
                   9194: 
                   9195: =item idput
                   9196: 
                   9197: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
                   9198: for each student, defined perhaps by the institutional Registrar.)
                   9199: 
                   9200: =item idget
                   9201: 
                   9202: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
                   9203: for each student, defined perhaps by the institutional Registrar.)
                   9204: 
1.517     raeburn  9205: =item iddel
                   9206: 
                   9207: Deletes one or more ids in a domain's id database.
                   9208: 
1.74      harris41 9209: =item tmpput
                   9210: 
                   9211: Accept and store information in temporary space.
                   9212: 
                   9213: =item tmpget
                   9214: 
                   9215: Send along temporarily stored information.
                   9216: 
                   9217: =item ls
                   9218: 
                   9219: List part of a user's directory.
                   9220: 
1.135     foxr     9221: =item pushtable
                   9222: 
                   9223: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
                   9224: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
                   9225: must be restored manually in case of a problem with the new table file.
                   9226: pushtable requires that the request be encrypted and validated via
                   9227: ValidateManager.  The form of the command is:
                   9228: enc:pushtable tablename <tablecontents> \n
                   9229: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
                   9230: cleartext newline.
                   9231: 
1.74      harris41 9232: =item Hanging up (exit or init)
                   9233: 
                   9234: What to do when a client tells the server that they (the client)
                   9235: are leaving the network.
                   9236: 
                   9237: =item unknown command
                   9238: 
                   9239: If B<lond> is sent an unknown command (not in the list above),
                   9240: it replys to the client "unknown_cmd".
1.135     foxr     9241: 
1.74      harris41 9242: 
                   9243: =item UNKNOWN CLIENT
                   9244: 
                   9245: If the anti-spoofing algorithm cannot verify the client,
                   9246: the client is rejected (with a "refused" message sent
                   9247: to the client, and the connection is closed.
                   9248: 
                   9249: =back
1.61      harris41 9250: 
                   9251: =head1 PREREQUISITES
                   9252: 
                   9253: IO::Socket
                   9254: IO::File
                   9255: Apache::File
                   9256: POSIX
                   9257: Crypt::IDEA
                   9258: GDBM_File
                   9259: Authen::Krb4
1.91      albertel 9260: Authen::Krb5
1.61      harris41 9261: 
                   9262: =head1 COREQUISITES
                   9263: 
1.490     droeschl 9264: none
                   9265: 
1.61      harris41 9266: =head1 OSNAMES
                   9267: 
                   9268: linux
                   9269: 
                   9270: =head1 SCRIPT CATEGORIES
                   9271: 
                   9272: Server/Process
                   9273: 
                   9274: =cut
1.409     foxr     9275: 
                   9276: 
                   9277: =pod
                   9278: 
                   9279: =head1 LOG MESSAGES
                   9280: 
                   9281: The messages below can be emitted in the lond log.  This log is located
                   9282: in ~httpd/perl/logs/lond.log  Many log messages have HTML encapsulation
                   9283: to provide coloring if examined from inside a web page. Some do not.
                   9284: Where color is used, the colors are; Red for sometihhng to get excited
                   9285: about and to follow up on. Yellow for something to keep an eye on to
                   9286: be sure it does not get worse, Green,and Blue for informational items.
                   9287: 
                   9288: In the discussions below, sometimes reference is made to ~httpd
                   9289: when describing file locations.  There isn't really an httpd 
                   9290: user, however there is an httpd directory that gets installed in the
                   9291: place that user home directories go.  On linux, this is usually
                   9292: (always?) /home/httpd.
                   9293: 
                   9294: 
                   9295: Some messages are colorless.  These are usually (not always)
                   9296: Green/Blue color level messages.
                   9297: 
                   9298: =over 2
                   9299: 
                   9300: =item (Red)  LocalConnection rejecting non local: <ip> ne 127.0.0.1
                   9301: 
                   9302: A local connection negotiation was attempted by
                   9303: a host whose IP address was not 127.0.0.1.
                   9304: The socket is closed and the child will exit.
                   9305: lond has three ways to establish an encyrption
                   9306: key with a client:
                   9307: 
                   9308: =over 2
                   9309: 
                   9310: =item local 
                   9311: 
                   9312: The key is written and read from a file.
                   9313: This is only valid for connections from localhost.
                   9314: 
                   9315: =item insecure 
                   9316: 
                   9317: The key is generated by the server and
                   9318: transmitted to the client.
                   9319: 
                   9320: =item  ssl (secure)
                   9321: 
                   9322: An ssl connection is negotiated with the client,
                   9323: the key is generated by the server and sent to the 
                   9324: client across this ssl connection before the
                   9325: ssl connectionis terminated and clear text
                   9326: transmission resumes.
                   9327: 
                   9328: =back
                   9329: 
                   9330: =item (Red) LocalConnection: caller is insane! init = <init> and type = <type>
                   9331: 
                   9332: The client is local but has not sent an initialization
                   9333: string that is the literal "init:local"  The connection
                   9334: is closed and the child exits.
                   9335: 
                   9336: =item Red CRITICAL Can't get key file <error>        
                   9337: 
                   9338: SSL key negotiation is being attempted but the call to
1.549     raeburn  9339: lonssl::KeyFile failed.  This usually means that the
1.409     foxr     9340: configuration file is not correctly defining or protecting
                   9341: the directories/files lonCertificateDirectory or
                   9342: lonnetPrivateKey
                   9343: <error> is a string that describes the reason that
                   9344: the key file could not be located.
                   9345: 
                   9346: =item (Red) CRITICAL  Can't get certificates <error>  
                   9347: 
                   9348: SSL key negotiation failed because we were not able to retrives our certificate
                   9349: or the CA's certificate in the call to lonssl::CertificateFile
                   9350: <error> is the textual reason this failed.  Usual reasons:
                   9351: 
                   9352: =over 2
1.490     droeschl 9353: 
1.409     foxr     9354: =item Apache config file for loncapa  incorrect:
1.490     droeschl 9355: 
1.409     foxr     9356: one of the variables 
                   9357: lonCertificateDirectory, lonnetCertificateAuthority, or lonnetCertificate
                   9358: undefined or incorrect
                   9359: 
                   9360: =item Permission error:
                   9361: 
                   9362: The directory pointed to by lonCertificateDirectory is not readable by lond
                   9363: 
                   9364: =item Permission error:
                   9365: 
                   9366: Files in the directory pointed to by lonCertificateDirectory are not readable by lond.
                   9367: 
                   9368: =item Installation error:                         
                   9369: 
                   9370: Either the certificate authority file or the certificate have not
                   9371: been installed in lonCertificateDirectory.
                   9372: 
                   9373: =item (Red) CRITICAL SSL Socket promotion failed:  <err> 
                   9374: 
                   9375: The promotion of the connection from plaintext to SSL failed
                   9376: <err> is the reason for the failure.  There are two
                   9377: system calls involved in the promotion (one of which failed), 
                   9378: a dup to produce
                   9379: a second fd on the raw socket over which the encrypted data
                   9380: will flow and IO::SOcket::SSL->new_from_fd which creates
                   9381: the SSL connection on the duped fd.
                   9382: 
                   9383: =item (Blue)   WARNING client did not respond to challenge 
                   9384: 
                   9385: This occurs on an insecure (non SSL) connection negotiation request.
                   9386: lond generates some number from the time, the PID and sends it to
                   9387: the client.  The client must respond by echoing this information back.
                   9388: If the client does not do so, that's a violation of the challenge
                   9389: protocols and the connection will be failed.
                   9390: 
                   9391: =item (Red) No manager table. Nobody can manage!!    
                   9392: 
                   9393: lond has the concept of privileged hosts that
                   9394: can perform remote management function such
                   9395: as update the hosts.tab.   The manager hosts
                   9396: are described in the 
                   9397: ~httpd/lonTabs/managers.tab file.
                   9398: this message is logged if this file is missing.
                   9399: 
                   9400: 
                   9401: =item (Green) Registering manager <dnsname> as <cluster_name> with <ipaddress>
                   9402: 
                   9403: Reports the successful parse and registration
                   9404: of a specific manager. 
                   9405: 
                   9406: =item Green existing host <clustername:dnsname>  
                   9407: 
                   9408: The manager host is already defined in the hosts.tab
                   9409: the information in that table, rather than the info in the
                   9410: manager table will be used to determine the manager's ip.
                   9411: 
                   9412: =item (Red) Unable to craete <filename>                 
                   9413: 
                   9414: lond has been asked to create new versions of an administrative
                   9415: file (by a manager).  When this is done, the new file is created
                   9416: in a temp file and then renamed into place so that there are always
                   9417: usable administrative files, even if the update fails.  This failure
                   9418: message means that the temp file could not be created.
                   9419: The update is abandoned, and the old file is available for use.
                   9420: 
                   9421: =item (Green) CopyFile from <oldname> to <newname> failed
                   9422: 
                   9423: In an update of administrative files, the copy of the existing file to a
                   9424: backup file failed.  The installation of the new file may still succeed,
                   9425: but there will not be a back up file to rever to (this should probably
                   9426: be yellow).
                   9427: 
                   9428: =item (Green) Pushfile: backed up <oldname> to <newname>
                   9429: 
                   9430: See above, the backup of the old administrative file succeeded.
                   9431: 
                   9432: =item (Red)  Pushfile: Unable to install <filename> <reason>
                   9433: 
                   9434: The new administrative file could not be installed.  In this case,
                   9435: the old administrative file is still in use.
                   9436: 
                   9437: =item (Green) Installed new < filename>.                      
                   9438: 
                   9439: The new administrative file was successfullly installed.                                               
                   9440: 
                   9441: =item (Red) Reinitializing lond pid=<pid>                    
                   9442: 
                   9443: The lonc child process <pid> will be sent a USR2 
                   9444: signal.
                   9445: 
                   9446: =item (Red) Reinitializing self                                    
                   9447: 
                   9448: We've been asked to re-read our administrative files,and
                   9449: are doing so.
                   9450: 
                   9451: =item (Yellow) error:Invalid process identifier <ident>  
                   9452: 
                   9453: A reinit command was received, but the target part of the 
                   9454: command was not valid.  It must be either
                   9455: 'lond' or 'lonc' but was <ident>
                   9456: 
                   9457: =item (Green) isValideditCommand checking: Command = <command> Key = <key> newline = <newline>
                   9458: 
                   9459: Checking to see if lond has been handed a valid edit
                   9460: command.  It is possible the edit command is not valid
                   9461: in that case there are no log messages to indicate that.
                   9462: 
                   9463: =item Result of password change for  <username> pwchange_success
                   9464: 
                   9465: The password for <username> was
                   9466: successfully changed.
                   9467: 
                   9468: =item Unable to open <user> passwd to change password
                   9469: 
                   9470: Could not rewrite the 
                   9471: internal password file for a user
                   9472: 
                   9473: =item Result of password change for <user> : <result>
1.490     droeschl 9474: 
1.409     foxr     9475: A unix password change for <user> was attempted 
                   9476: and the pipe returned <result>  
                   9477: 
                   9478: =item LWP GET: <message> for <fname> (<remoteurl>)
                   9479: 
                   9480: The lightweight process fetch for a resource failed
                   9481: with <message> the local filename that should
                   9482: have existed/been created was  <fname> the
                   9483: corresponding URI: <remoteurl>  This is emitted in several
                   9484: places.
                   9485: 
                   9486: =item Unable to move <transname> to <destname>     
                   9487: 
                   9488: From fetch_user_file_handler - the user file was replicated but could not
                   9489: be mv'd to its final location.
                   9490: 
                   9491: =item Looking for <domain> <username>              
                   9492: 
                   9493: From user_has_session_handler - This should be a Debug call instead
                   9494: it indicates lond is about to check whether the specified user has a 
                   9495: session active on the specified domain on the local host.
                   9496: 
                   9497: =item Client <ip> (<name>) hanging up: <input>     
                   9498: 
                   9499: lond has been asked to exit by its client.  The <ip> and <name> identify the
                   9500: client systemand <input> is the full exit command sent to the server.
                   9501: 
                   9502: =item Red CRITICAL: ABNORMAL EXIT. child <pid> for server <hostname> died through a crass with this error->[<message>].
1.490     droeschl 9503: 
1.409     foxr     9504: A lond child terminated.  NOte that this termination can also occur when the
                   9505: child receives the QUIT or DIE signals.  <pid> is the process id of the child,
                   9506: <hostname> the host lond is working for, and <message> the reason the child died
                   9507: to the best of our ability to get it (I would guess that any numeric value
                   9508: represents and errno value).  This is immediately followed by
                   9509: 
                   9510: =item  Famous last words: Catching exception - <log> 
                   9511: 
                   9512: Where log is some recent information about the state of the child.
                   9513: 
                   9514: =item Red CRITICAL: TIME OUT <pid>                     
                   9515: 
                   9516: Some timeout occured for server <pid>.  THis is normally a timeout on an LWP
                   9517: doing an HTTP::GET.
                   9518: 
                   9519: =item child <pid> died                              
                   9520: 
                   9521: The reaper caught a SIGCHILD for the lond child process <pid>
                   9522: This should be modified to also display the IP of the dying child
                   9523: $children{$pid}
                   9524: 
                   9525: =item Unknown child 0 died                           
                   9526: A child died but the wait for it returned a pid of zero which really should not
                   9527: ever happen. 
                   9528: 
                   9529: =item Child <which> - <pid> looks like we missed it's death 
                   9530: 
                   9531: When a sigchild is received, the reaper process checks all children to see if they are
                   9532: alive.  If children are dying quite quickly, the lack of signal queuing can mean
                   9533: that a signal hearalds the death of more than one child.  If so this message indicates
                   9534: which other one died. <which> is the ip of a dead child
                   9535: 
                   9536: =item Free socket: <shutdownretval>                
                   9537: 
                   9538: The HUNTSMAN sub was called due to a SIGINT in a child process.  The socket is being shutdown.
                   9539: for whatever reason, <shutdownretval> is printed but in fact shutdown() is not documented
                   9540: to return anything. This is followed by: 
                   9541: 
                   9542: =item Red CRITICAL: Shutting down                       
                   9543: 
                   9544: Just prior to exit.
                   9545: 
                   9546: =item Free socket: <shutdownretval>                 
                   9547: 
                   9548: The HUPSMAN sub was called due to a SIGHUP.  all children get killsed, and lond execs itself.
                   9549: This is followed by:
                   9550: 
                   9551: =item (Red) CRITICAL: Restarting                         
                   9552: 
                   9553: lond is about to exec itself to restart.
                   9554: 
                   9555: =item (Blue) Updating connections                        
                   9556: 
                   9557: (In response to a USR2).  All the children (except the one for localhost)
                   9558: are about to be killed, the hosts tab reread, and Apache reloaded via apachereload.
                   9559: 
                   9560: =item (Blue) UpdateHosts killing child <pid> for ip <ip>   
                   9561: 
                   9562: Due to USR2 as above.
                   9563: 
                   9564: =item (Green) keeping child for ip <ip> (pid = <pid>)    
                   9565: 
                   9566: In response to USR2 as above, the child indicated is not being restarted because
                   9567: it's assumed that we'll always need a child for the localhost.
                   9568: 
                   9569: 
                   9570: =item Going to check on the children                
                   9571: 
                   9572: Parent is about to check on the health of the child processes.
                   9573: Note that this is in response to a USR1 sent to the parent lond.
                   9574: there may be one or more of the next two messages:
                   9575: 
                   9576: =item <pid> is dead                                 
                   9577: 
                   9578: A child that we have in our child hash as alive has evidently died.
                   9579: 
                   9580: =item  Child <pid> did not respond                   
                   9581: 
                   9582: In the health check the child <pid> did not update/produce a pid_.txt
                   9583: file when sent it's USR1 signal.  That process is killed with a 9 signal, as it's
                   9584: assumed to be hung in some un-fixable way.
                   9585: 
                   9586: =item Finished checking children                   
1.490     droeschl 9587: 
1.409     foxr     9588: Master processs's USR1 processing is cojmplete.
                   9589: 
                   9590: =item (Red) CRITICAL: ------- Starting ------            
                   9591: 
                   9592: (There are more '-'s on either side).  Lond has forked itself off to 
                   9593: form a new session and is about to start actual initialization.
                   9594: 
                   9595: =item (Green) Attempting to start child (<client>)       
                   9596: 
                   9597: Started a new child process for <client>.  Client is IO::Socket object
                   9598: connected to the child.  This was as a result of a TCP/IP connection from a client.
                   9599: 
                   9600: =item Unable to determine who caller was, getpeername returned nothing
1.490     droeschl 9601: 
1.409     foxr     9602: In child process initialization.  either getpeername returned undef or
                   9603: a zero sized object was returned.  Processing continues, but in my opinion,
                   9604: this should be cause for the child to exit.
                   9605: 
                   9606: =item Unable to determine clientip                  
                   9607: 
                   9608: In child process initialization.  The peer address from getpeername was not defined.
                   9609: The client address is stored as "Unavailable" and processing continues.
                   9610: 
                   9611: =item (Yellow) INFO: Connection <ip> <name> connection type = <type>
1.490     droeschl 9612: 
1.409     foxr     9613: In child initialization.  A good connectionw as received from <ip>.
                   9614: 
                   9615: =over 2
                   9616: 
                   9617: =item <name> 
                   9618: 
                   9619: is the name of the client from hosts.tab.
                   9620: 
                   9621: =item <type> 
                   9622: 
                   9623: Is the connection type which is either 
                   9624: 
                   9625: =over 2
                   9626: 
                   9627: =item manager 
                   9628: 
                   9629: The connection is from a manager node, not in hosts.tab
                   9630: 
                   9631: =item client  
                   9632: 
                   9633: the connection is from a non-manager in the hosts.tab
                   9634: 
                   9635: =item both
                   9636: 
                   9637: The connection is from a manager in the hosts.tab.
                   9638: 
                   9639: =back
                   9640: 
                   9641: =back
                   9642: 
                   9643: =item (Blue) Certificates not installed -- trying insecure auth
                   9644: 
                   9645: One of the certificate file, key file or
                   9646: certificate authority file could not be found for a client attempting
                   9647: SSL connection intiation.  COnnection will be attemptied in in-secure mode.
                   9648: (this would be a system with an up to date lond that has not gotten a 
                   9649: certificate from us).
                   9650: 
                   9651: =item (Green)  Successful local authentication            
                   9652: 
                   9653: A local connection successfully negotiated the encryption key. 
                   9654: In this case the IDEA key is in a file (that is hopefully well protected).
                   9655: 
                   9656: =item (Green) Successful ssl authentication with <client>  
                   9657: 
                   9658: The client (<client> is the peer's name in hosts.tab), has successfully
                   9659: negotiated an SSL connection with this child process.
                   9660: 
                   9661: =item (Green) Successful insecure authentication with <client>
1.490     droeschl 9662: 
1.409     foxr     9663: 
                   9664: The client has successfully negotiated an  insecure connection withthe child process.
                   9665: 
                   9666: =item (Yellow) Attempted insecure connection disallowed    
                   9667: 
                   9668: The client attempted and failed to successfully negotiate a successful insecure
                   9669: connection.  This can happen either because the variable londAllowInsecure is false
                   9670: or undefined, or becuse the child did not successfully echo back the challenge
                   9671: string.
                   9672: 
                   9673: 
                   9674: =back
                   9675: 
1.441     raeburn  9676: =back
                   9677: 
1.409     foxr     9678: 
                   9679: =cut

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