Annotation of loncom/lond, revision 1.557

1.1       albertel    1: #!/usr/bin/perl
                      2: # The LearningOnline Network
                      3: # lond "LON Daemon" Server (port "LOND" 5663)
1.60      www         4: #
1.557   ! raeburn     5: # $Id: lond,v 1.556 2018/12/13 03:23:05 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.557   ! raeburn    68: my $VERSION='$Revision: 1.556 $'; #' stupid emacs
1.121     albertel   69: my $remoteVERSION;
1.214     foxr       70: my $currenthostid="default";
1.115     albertel   71: my $currentdomainid;
1.134     albertel   72: 
                     73: my $client;
1.200     matthew    74: my $clientip;			# IP address of client.
                     75: my $clientname;			# LonCAPA name of client.
1.448     raeburn    76: my $clientversion;              # LonCAPA version running on client.
                     77: my $clienthomedom;              # LonCAPA domain of homeID for client. 
1.525     raeburn    78: my $clientintdom;               # LonCAPA "internet domain" for client.
1.532     raeburn    79: my $clientsamedom;              # LonCAPA domain same for this host 
                     80:                                 # and client.
1.525     raeburn    81: my $clientsameinst;             # LonCAPA "internet domain" same for 
                     82:                                 # this host and client.
1.556     raeburn    83: my $clientremoteok;             # Current domain permits hosting on client
                     84:                                 # (not set if host and client share "internet domain").
                     85:                                 # Values are 0 or 1; 1 if allowed.
                     86: my %clientprohibited;           # Commands from client prohibited for domain's
                     87:                                 # users.
                     88: 
1.134     albertel   89: my $server;
1.200     matthew    90: 
                     91: my $keymode;
1.198     foxr       92: 
1.207     foxr       93: my $cipher;			# Cipher key negotiated with client
                     94: my $tmpsnum = 0;		# Id of tmpputs.
                     95: 
1.178     foxr       96: # 
                     97: #   Connection type is:
                     98: #      client                   - All client actions are allowed
                     99: #      manager                  - only management functions allowed.
                    100: #      both                     - Both management and client actions are allowed
                    101: #
1.161     foxr      102: 
1.178     foxr      103: my $ConnectionType;
1.161     foxr      104: 
1.178     foxr      105: my %managers;			# Ip -> manager names
1.161     foxr      106: 
1.178     foxr      107: my %perlvar;			# Will have the apache conf defined perl vars.
1.134     albertel  108: 
1.532     raeburn   109: my %secureconf;                 # Will have requirements for security 
                    110:                                 # of lond connections
                    111: 
1.545     raeburn   112: my %crlchecked;                 # Will contain clients for which the client's SSL
                    113:                                 # has been checked against the cluster's Certificate
                    114:                                 # Revocation List.
                    115: 
1.480     raeburn   116: my $dist;
                    117: 
1.178     foxr      118: #
1.207     foxr      119: #   The hash below is used for command dispatching, and is therefore keyed on the request keyword.
                    120: #    Each element of the hash contains a reference to an array that contains:
                    121: #          A reference to a sub that executes the request corresponding to the keyword.
                    122: #          A flag that is true if the request must be encoded to be acceptable.
                    123: #          A mask with bits as follows:
                    124: #                      CLIENT_OK    - Set when the function is allowed by ordinary clients
                    125: #                      MANAGER_OK   - Set when the function is allowed to manager clients.
                    126: #
                    127: my $CLIENT_OK  = 1;
                    128: my $MANAGER_OK = 2;
                    129: my %Dispatcher;
                    130: 
                    131: 
                    132: #
1.178     foxr      133: #  The array below are password error strings."
                    134: #
                    135: my $lastpwderror    = 13;		# Largest error number from lcpasswd.
                    136: my @passwderrors = ("ok",
1.287     foxr      137: 		   "pwchange_failure - lcpasswd must be run as user 'www'",
                    138: 		   "pwchange_failure - lcpasswd got incorrect number of arguments",
                    139: 		   "pwchange_failure - lcpasswd did not get the right nubmer of input text lines",
                    140: 		   "pwchange_failure - lcpasswd too many simultaneous pwd changes in progress",
                    141: 		   "pwchange_failure - lcpasswd User does not exist.",
                    142: 		   "pwchange_failure - lcpasswd Incorrect current passwd",
                    143: 		   "pwchange_failure - lcpasswd Unable to su to root.",
                    144: 		   "pwchange_failure - lcpasswd Cannot set new passwd.",
                    145: 		   "pwchange_failure - lcpasswd Username has invalid characters",
                    146: 		   "pwchange_failure - lcpasswd Invalid characters in password",
                    147: 		   "pwchange_failure - lcpasswd User already exists", 
                    148:                    "pwchange_failure - lcpasswd Something went wrong with user addition.",
                    149: 		   "pwchange_failure - lcpasswd Password mismatch",
                    150: 		   "pwchange_failure - lcpasswd Error filename is invalid");
1.97      foxr      151: 
                    152: 
1.412     foxr      153: # This array are the errors from lcinstallfile:
                    154: 
                    155: my @installerrors = ("ok",
                    156: 		     "Initial user id of client not that of www",
                    157: 		     "Usage error, not enough command line arguments",
1.500     bisitz    158: 		     "Source filename does not exist",
                    159: 		     "Destination filename does not exist",
1.412     foxr      160: 		     "Some file operation failed",
                    161: 		     "Invalid table filename."
                    162: 		     );
1.207     foxr      163: 
                    164: #
1.525     raeburn   165: # The %trust hash classifies commands according to type of trust 
                    166: # required for execution of the command.
                    167: #
                    168: # When clients from a different institution request execution of a
                    169: # particular command, the trust settings for that institution set
                    170: # for this domain (or default domain for a multi-domain server) will
                    171: # be checked to see if running the command is allowed.
                    172: #
                    173: # Trust types which depend on the "Trust" domain configuration
                    174: # for the machine's default domain are:
                    175: #
                    176: # content   ("Access to this domain's content by others")
                    177: # shared    ("Access to other domain's content by this domain")
                    178: # enroll    ("Enrollment in this domain's courses by others")
                    179: # coaurem   ("Co-author roles for this domain's users elsewhere")
1.552     raeburn   180: # othcoau   ("Co-author roles in this domain for others")
1.525     raeburn   181: # domroles  ("Domain roles in this domain assignable to others")
                    182: # catalog   ("Course Catalog for this domain displayed elsewhere")
                    183: # reqcrs    ("Requests for creation of courses in this domain by others")
                    184: # msg       ("Users in other domains can send messages to this domain")
                    185: # 
                    186: # Trust type which depends on the User Session Hosting (remote) 
                    187: # domain configuration for machine's default domain is: "remote".
                    188: #
                    189: # Trust types which depend on contents of manager.tab in 
                    190: # /home/httpd/lonTabs is: "manageronly".
                    191: # 
                    192: # Trust type which requires client to share the same LON-CAPA
                    193: # "internet domain" (i.e., same institution as this server) is:
                    194: # "institutiononly".
                    195: #
                    196: 
                    197: my %trust = (
                    198:                auth => {remote => 1},
                    199:                autocreatepassword => {remote => 1},
                    200:                autocrsreqchecks => {remote => 1, reqcrs => 1},
                    201:                autocrsrequpdate => {remote => 1},
                    202:                autocrsreqvalidation => {remote => 1},
                    203:                autogetsections => {remote => 1},
                    204:                autoinstcodedefaults => {remote => 1, catalog => 1},
                    205:                autoinstcodeformat => {remote => 1, catalog => 1},
                    206:                autonewcourse => {remote => 1, reqcrs => 1},
                    207:                autophotocheck => {remote => 1, enroll => 1},
                    208:                autophotochoice => {remote => 1},
                    209:                autophotopermission => {remote => 1, enroll => 1},
                    210:                autopossibleinstcodes => {remote => 1, reqcrs => 1},
                    211:                autoretrieve => {remote => 1, enroll => 1, catalog => 1},
                    212:                autorun => {remote => 1, enroll => 1, reqcrs => 1},
                    213:                autovalidateclass_sec => {catalog => 1},
                    214:                autovalidatecourse => {remote => 1, enroll => 1},
                    215:                autovalidateinstcode => {domroles => 1, remote => 1, enroll => 1},
                    216:                changeuserauth => {remote => 1, domroles => 1},
                    217:                chatretr => {remote => 1, enroll => 1},
                    218:                chatsend => {remote => 1, enroll => 1},
                    219:                courseiddump => {remote => 1, domroles => 1, enroll => 1},
                    220:                courseidput => {remote => 1, domroles => 1, enroll => 1},
                    221:                courseidputhash => {remote => 1, domroles => 1, enroll => 1},
                    222:                courselastaccess => {remote => 1, domroles => 1, enroll => 1},
                    223:                currentauth => {remote => 1, domroles => 1, enroll => 1},
                    224:                currentdump => {remote => 1, enroll => 1},
                    225:                currentversion => {remote=> 1, content => 1},
                    226:                dcmaildump => {remote => 1, domroles => 1},
                    227:                dcmailput => {remote => 1, domroles => 1},
                    228:                del => {remote => 1, domroles => 1, enroll => 1, content => 1},
1.551     raeburn   229:                delbalcookie => {institutiononly => 1},
1.525     raeburn   230:                deldom => {remote => 1, domroles => 1}, # not currently used
                    231:                devalidatecache => {institutiononly => 1},
                    232:                domroleput => {remote => 1, enroll => 1},
                    233:                domrolesdump => {remote => 1, catalog => 1},
                    234:                du => {remote => 1, enroll => 1},
                    235:                du2 => {remote => 1, enroll => 1},
                    236:                dump => {remote => 1, enroll => 1, domroles => 1},
                    237:                edit => {institutiononly => 1},  #not used currently
                    238:                eget => {remote => 1, domroles => 1, enroll => 1}, #not used currently
1.536     raeburn   239:                egetdom => {remote => 1, domroles => 1, enroll => 1, },
1.553     raeburn   240:                ekey => {anywhere => 1},
1.525     raeburn   241:                exit => {anywhere => 1},
                    242:                fetchuserfile => {remote => 1, enroll => 1},
                    243:                get => {remote => 1, domroles => 1, enroll => 1},
                    244:                getdom => {anywhere => 1},
                    245:                home => {anywhere => 1},
                    246:                iddel => {remote => 1, enroll => 1},
                    247:                idget => {remote => 1, enroll => 1},
                    248:                idput => {remote => 1, domroles => 1, enroll => 1},
                    249:                inc => {remote => 1, enroll => 1},
                    250:                init => {anywhere => 1},
                    251:                inst_usertypes => {remote => 1, domroles => 1, enroll => 1},
                    252:                instemailrules => {remote => 1, domroles => 1},
                    253:                instidrulecheck => {remote => 1, domroles => 1,},
                    254:                instidrules => {remote => 1, domroles => 1,},
                    255:                instrulecheck => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1},
                    256:                instselfcreatecheck => {institutiononly => 1},
                    257:                instuserrules => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1},
                    258:                keys => {remote => 1,},
                    259:                load => {anywhere => 1},
                    260:                log => {anywhere => 1},
                    261:                ls => {remote => 1, enroll => 1, content => 1,},
                    262:                ls2 => {remote => 1, enroll => 1, content => 1,},
                    263:                ls3 => {remote => 1, enroll => 1, content => 1,},
                    264:                makeuser => {remote => 1, enroll => 1, domroles => 1,},
                    265:                mkdiruserfile => {remote => 1, enroll => 1,},
                    266:                newput => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1,},
                    267:                passwd => {remote => 1},
                    268:                ping => {anywhere => 1},
                    269:                pong => {anywhere => 1},
                    270:                pushfile => {manageronly => 1},
                    271:                put => {remote => 1, enroll => 1, domroles => 1, msg => 1, content => 1, shared => 1},
                    272:                putdom => {remote => 1, domroles => 1,},
                    273:                putstore => {remote => 1, enroll => 1},
                    274:                queryreply => {anywhere => 1},
                    275:                querysend => {anywhere => 1},
1.535     raeburn   276:                querysend_activitylog => {remote => 1},
                    277:                querysend_allusers => {remote => 1, domroles => 1},
                    278:                querysend_courselog => {remote => 1},
                    279:                querysend_fetchenrollment => {remote => 1},
                    280:                querysend_getinstuser => {remote => 1},
                    281:                querysend_getmultinstusers => {remote => 1},
                    282:                querysend_instdirsearch => {remote => 1, domroles => 1, coaurem => 1},
                    283:                querysend_institutionalphotos => {remote => 1},
                    284:                querysend_portfolio_metadata => {remote => 1, content => 1},
                    285:                querysend_userlog => {remote => 1, domroles => 1},
                    286:                querysend_usersearch => {remote => 1, enroll => 1, coaurem => 1},
1.525     raeburn   287:                quit => {anywhere => 1},
                    288:                readlonnetglobal => {institutiononly => 1},
                    289:                reinit => {manageronly => 1}, #not used currently
                    290:                removeuserfile => {remote => 1, enroll => 1},
                    291:                renameuserfile => {remote => 1,},
                    292:                restore => {remote => 1, enroll => 1, reqcrs => 1,},
                    293:                rolesdel => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
                    294:                rolesput => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
1.527     raeburn   295:                servercerts => {institutiononly => 1},
1.528     raeburn   296:                serverdistarch => {anywhere => 1},
1.525     raeburn   297:                serverhomeID => {anywhere => 1},
                    298:                serverloncaparev => {anywhere => 1},
                    299:                servertimezone => {remote => 1, enroll => 1},
                    300:                setannounce => {remote => 1, domroles => 1},
                    301:                sethost => {anywhere => 1},
                    302:                store => {remote => 1, enroll => 1, reqcrs => 1,},
                    303:                studentphoto => {remote => 1, enroll => 1},
                    304:                sub => {content => 1,},
1.552     raeburn   305:                tmpdel => {institutiononly => 1},
                    306:                tmpget => {institutiononly => 1},
                    307:                tmpput => {remote => 1, othcoau => 1},
1.525     raeburn   308:                tokenauthuserfile => {anywhere => 1},
                    309:                unsub => {content => 1,},
                    310:                update => {shared => 1},
                    311:                updateclickers => {remote => 1},
                    312:                userhassession => {anywhere => 1},
                    313:                userload => {anywhere => 1},
                    314:                version => {anywhere => 1}, #not used
                    315:             );
                    316: 
                    317: #
1.207     foxr      318: #   Statistics that are maintained and dislayed in the status line.
                    319: #
1.212     foxr      320: my $Transactions = 0;		# Number of attempted transactions.
                    321: my $Failures     = 0;		# Number of transcations failed.
1.207     foxr      322: 
                    323: #   ResetStatistics: 
                    324: #      Resets the statistics counters:
                    325: #
                    326: sub ResetStatistics {
                    327:     $Transactions = 0;
                    328:     $Failures     = 0;
                    329: }
                    330: 
1.200     matthew   331: #------------------------------------------------------------------------
                    332: #
                    333: #   LocalConnection
                    334: #     Completes the formation of a locally authenticated connection.
                    335: #     This function will ensure that the 'remote' client is really the
                    336: #     local host.  If not, the connection is closed, and the function fails.
                    337: #     If so, initcmd is parsed for the name of a file containing the
                    338: #     IDEA session key.  The fie is opened, read, deleted and the session
                    339: #     key returned to the caller.
                    340: #
                    341: # Parameters:
                    342: #   $Socket      - Socket open on client.
                    343: #   $initcmd     - The full text of the init command.
                    344: #
                    345: # Returns:
                    346: #     IDEA session key on success.
                    347: #     undef on failure.
                    348: #
                    349: sub LocalConnection {
                    350:     my ($Socket, $initcmd) = @_;
1.373     albertel  351:     Debug("Attempting local connection: $initcmd client: $clientip");
1.277     albertel  352:     if($clientip ne "127.0.0.1") {
1.200     matthew   353: 	&logthis('<font color="red"> LocalConnection rejecting non local: '
1.373     albertel  354: 		 ."$clientip ne 127.0.0.1 </font>");
1.200     matthew   355: 	close $Socket;
                    356: 	return undef;
1.224     foxr      357:     }  else {
1.200     matthew   358: 	chomp($initcmd);	# Get rid of \n in filename.
                    359: 	my ($init, $type, $name) = split(/:/, $initcmd);
                    360: 	Debug(" Init command: $init $type $name ");
                    361: 
                    362: 	# Require that $init = init, and $type = local:  Otherwise
                    363: 	# the caller is insane:
                    364: 
                    365: 	if(($init ne "init") && ($type ne "local")) {
                    366: 	    &logthis('<font color = "red"> LocalConnection: caller is insane! '
                    367: 		     ."init = $init, and type = $type </font>");
                    368: 	    close($Socket);;
                    369: 	    return undef;
                    370: 		
                    371: 	}
                    372: 	#  Now get the key filename:
                    373: 
                    374: 	my $IDEAKey = lonlocal::ReadKeyFile($name);
                    375: 	return $IDEAKey;
                    376:     }
                    377: }
                    378: #------------------------------------------------------------------------------
                    379: #
                    380: #  SSLConnection
                    381: #   Completes the formation of an ssh authenticated connection. The
                    382: #   socket is promoted to an ssl socket.  If this promotion and the associated
                    383: #   certificate exchange are successful, the IDEA key is generated and sent
                    384: #   to the remote peer via the SSL tunnel. The IDEA key is also returned to
                    385: #   the caller after the SSL tunnel is torn down.
                    386: #
                    387: # Parameters:
                    388: #   Name              Type             Purpose
                    389: #   $Socket          IO::Socket::INET  Plaintext socket.
                    390: #
                    391: # Returns:
                    392: #    IDEA key on success.
                    393: #    undef on failure.
                    394: #
                    395: sub SSLConnection {
                    396:     my $Socket   = shift;
                    397: 
                    398:     Debug("SSLConnection: ");
                    399:     my $KeyFile         = lonssl::KeyFile();
                    400:     if(!$KeyFile) {
                    401: 	my $err = lonssl::LastError();
                    402: 	&logthis("<font color=\"red\"> CRITICAL"
                    403: 		 ."Can't get key file $err </font>");
                    404: 	return undef;
                    405:     }
                    406:     my ($CACertificate,
                    407: 	$Certificate) = lonssl::CertificateFile();
                    408: 
                    409: 
                    410:     # If any of the key, certificate or certificate authority 
                    411:     # certificate filenames are not defined, this can't work.
                    412: 
                    413:     if((!$Certificate) || (!$CACertificate)) {
                    414: 	my $err = lonssl::LastError();
                    415: 	&logthis("<font color=\"red\"> CRITICAL"
                    416: 		 ."Can't get certificates: $err </font>");
                    417: 
                    418: 	return undef;
                    419:     }
                    420:     Debug("Key: $KeyFile CA: $CACertificate Cert: $Certificate");
                    421: 
                    422:     # Indicate to our peer that we can procede with
                    423:     # a transition to ssl authentication:
                    424: 
                    425:     print $Socket "ok:ssl\n";
                    426: 
                    427:     Debug("Approving promotion -> ssl");
                    428:     #  And do so:
                    429: 
1.545     raeburn   430:     my $CRLFile;
                    431:     unless ($crlchecked{$clientname}) {
                    432:         $CRLFile = lonssl::CRLFile();
                    433:         $crlchecked{$clientname} = 1;
                    434:     }
                    435: 
1.200     matthew   436:     my $SSLSocket = lonssl::PromoteServerSocket($Socket,
                    437: 						$CACertificate,
                    438: 						$Certificate,
1.544     raeburn   439: 						$KeyFile,
1.545     raeburn   440: 						$clientname,
1.546     raeburn   441:                                                 $CRLFile,
                    442:                                                 $clientversion);
1.200     matthew   443:     if(! ($SSLSocket) ) {	# SSL socket promotion failed.
                    444: 	my $err = lonssl::LastError();
                    445: 	&logthis("<font color=\"red\"> CRITICAL "
                    446: 		 ."SSL Socket promotion failed: $err </font>");
                    447: 	return undef;
                    448:     }
                    449:     Debug("SSL Promotion successful");
                    450: 
                    451:     # 
                    452:     #  The only thing we'll use the socket for is to send the IDEA key
                    453:     #  to the peer:
                    454: 
                    455:     my $Key = lonlocal::CreateCipherKey();
                    456:     print $SSLSocket "$Key\n";
                    457: 
                    458:     lonssl::Close($SSLSocket); 
                    459: 
                    460:     Debug("Key exchange complete: $Key");
                    461: 
                    462:     return $Key;
                    463: }
                    464: #
                    465: #     InsecureConnection: 
                    466: #        If insecure connections are allowd,
                    467: #        exchange a challenge with the client to 'validate' the
                    468: #        client (not really, but that's the protocol):
                    469: #        We produce a challenge string that's sent to the client.
                    470: #        The client must then echo the challenge verbatim to us.
                    471: #
                    472: #  Parameter:
                    473: #      Socket      - Socket open on the client.
                    474: #  Returns:
                    475: #      1           - success.
                    476: #      0           - failure (e.g.mismatch or insecure not allowed).
                    477: #
                    478: sub InsecureConnection {
                    479:     my $Socket  =  shift;
                    480: 
                    481:     #   Don't even start if insecure connections are not allowed.
1.532     raeburn   482:     #   return 0 if Insecure connections not allowed.
                    483:     #
                    484:     if (ref($secureconf{'connfrom'}) eq 'HASH') {
                    485:         if ($clientsamedom) {
                    486:             if ($secureconf{'connfrom'}{'dom'} eq 'req') {
                    487:                 return 0;
                    488:             } 
                    489:         } elsif ($clientsameinst) {
                    490:             if ($secureconf{'connfrom'}{'intdom'} eq 'req') {
                    491:                 return 0;
                    492:             }
                    493:         } else {
                    494:             if ($secureconf{'connfrom'}{'other'} eq 'req') {
                    495:                 return 0;
                    496:             }
                    497:         }
                    498:     } elsif (!$perlvar{londAllowInsecure}) {
1.200     matthew   499: 	return 0;
                    500:     }
                    501: 
                    502:     #   Fabricate a challenge string and send it..
                    503: 
                    504:     my $challenge = "$$".time;	# pid + time.
                    505:     print $Socket "$challenge\n";
                    506:     &status("Waiting for challenge reply");
                    507: 
                    508:     my $answer = <$Socket>;
                    509:     $answer    =~s/\W//g;
                    510:     if($challenge eq $answer) {
                    511: 	return 1;
1.224     foxr      512:     } else {
1.200     matthew   513: 	logthis("<font color='blue'>WARNING client did not respond to challenge</font>");
                    514: 	&status("No challenge reqply");
                    515: 	return 0;
                    516:     }
                    517:     
                    518: 
                    519: }
1.251     foxr      520: #
                    521: #   Safely execute a command (as long as it's not a shel command and doesn
                    522: #   not require/rely on shell escapes.   The function operates by doing a
                    523: #   a pipe based fork and capturing stdout and stderr  from the pipe.
                    524: #
                    525: # Formal Parameters:
                    526: #     $line                    - A line of text to be executed as a command.
                    527: # Returns:
                    528: #     The output from that command.  If the output is multiline the caller
                    529: #     must know how to split up the output.
                    530: #
                    531: #
                    532: sub execute_command {
                    533:     my ($line)    = @_;
                    534:     my @words     = split(/\s/, $line);	# Bust the command up into words.
                    535:     my $output    = "";
                    536: 
                    537:     my $pid = open(CHILD, "-|");
                    538:     
                    539:     if($pid) {			# Parent process
                    540: 	Debug("In parent process for execute_command");
                    541: 	my @data = <CHILD>;	# Read the child's outupt...
                    542: 	close CHILD;
                    543: 	foreach my $output_line (@data) {
                    544: 	    Debug("Adding $output_line");
                    545: 	    $output .= $output_line; # Presumably has a \n on it.
                    546: 	}
                    547: 
                    548:     } else {			# Child process
                    549: 	close (STDERR);
                    550: 	open  (STDERR, ">&STDOUT");# Combine stderr, and stdout...
                    551: 	exec(@words);		# won't return.
                    552:     }
                    553:     return $output;
                    554: }
                    555: 
1.200     matthew   556: 
1.140     foxr      557: #   GetCertificate: Given a transaction that requires a certificate,
                    558: #   this function will extract the certificate from the transaction
                    559: #   request.  Note that at this point, the only concept of a certificate
                    560: #   is the hostname to which we are connected.
                    561: #
                    562: #   Parameter:
                    563: #      request   - The request sent by our client (this parameterization may
                    564: #                  need to change when we really use a certificate granting
                    565: #                  authority.
                    566: #
                    567: sub GetCertificate {
                    568:     my $request = shift;
                    569: 
                    570:     return $clientip;
                    571: }
1.161     foxr      572: 
1.178     foxr      573: #
                    574: #   Return true if client is a manager.
                    575: #
                    576: sub isManager {
                    577:     return (($ConnectionType eq "manager") || ($ConnectionType eq "both"));
                    578: }
                    579: #
                    580: #   Return tru if client can do client functions
                    581: #
                    582: sub isClient {
                    583:     return (($ConnectionType eq "client") || ($ConnectionType eq "both"));
                    584: }
1.161     foxr      585: 
                    586: 
1.156     foxr      587: #
                    588: #   ReadManagerTable: Reads in the current manager table. For now this is
                    589: #                     done on each manager authentication because:
                    590: #                     - These authentications are not frequent
                    591: #                     - This allows dynamic changes to the manager table
                    592: #                       without the need to signal to the lond.
                    593: #
                    594: sub ReadManagerTable {
                    595: 
1.412     foxr      596:     &Debug("Reading manager table");
1.156     foxr      597:     #   Clean out the old table first..
                    598: 
1.166     foxr      599:    foreach my $key (keys %managers) {
                    600:       delete $managers{$key};
                    601:    }
                    602: 
                    603:    my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
                    604:    if (!open (MANAGERS, $tablename)) {
1.473     raeburn   605:        my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
                    606:        if (&Apache::lonnet::is_LC_dns($hostname)) {
1.472     raeburn   607:            &logthis('<font color="red">No manager table.  Nobody can manage!!</font>');
                    608:        }
                    609:        return;
1.166     foxr      610:    }
                    611:    while(my $host = <MANAGERS>) {
                    612:       chomp($host);
                    613:       if ($host =~ "^#") {                  # Comment line.
                    614:          next;
                    615:       }
1.368     albertel  616:       if (!defined &Apache::lonnet::get_host_ip($host)) { # This is a non cluster member
1.161     foxr      617: 	    #  The entry is of the form:
                    618: 	    #    cluname:hostname
                    619: 	    #  cluname - A 'cluster hostname' is needed in order to negotiate
                    620: 	    #            the host key.
                    621: 	    #  hostname- The dns name of the host.
                    622: 	    #
1.166     foxr      623:           my($cluname, $dnsname) = split(/:/, $host);
                    624:           
                    625:           my $ip = gethostbyname($dnsname);
                    626:           if(defined($ip)) {                 # bad names don't deserve entry.
                    627:             my $hostip = inet_ntoa($ip);
                    628:             $managers{$hostip} = $cluname;
                    629:             logthis('<font color="green"> registering manager '.
                    630:                     "$dnsname as $cluname with $hostip </font>\n");
                    631:          }
                    632:       } else {
                    633:          logthis('<font color="green"> existing host'." $host</font>\n");
1.472     raeburn   634:          $managers{&Apache::lonnet::get_host_ip($host)} = $host;  # Use info from cluster tab if cluster memeber
1.166     foxr      635:       }
                    636:    }
1.156     foxr      637: }
1.140     foxr      638: 
                    639: #
                    640: #  ValidManager: Determines if a given certificate represents a valid manager.
                    641: #                in this primitive implementation, the 'certificate' is
                    642: #                just the connecting loncapa client name.  This is checked
                    643: #                against a valid client list in the configuration.
                    644: #
                    645: #                  
                    646: sub ValidManager {
                    647:     my $certificate = shift; 
                    648: 
1.163     foxr      649:     return isManager;
1.140     foxr      650: }
                    651: #
1.143     foxr      652: #  CopyFile:  Called as part of the process of installing a 
                    653: #             new configuration file.  This function copies an existing
                    654: #             file to a backup file.
                    655: # Parameters:
                    656: #     oldfile  - Name of the file to backup.
                    657: #     newfile  - Name of the backup file.
                    658: # Return:
                    659: #     0   - Failure (errno has failure reason).
                    660: #     1   - Success.
                    661: #
                    662: sub CopyFile {
1.192     foxr      663: 
                    664:     my ($oldfile, $newfile) = @_;
1.143     foxr      665: 
1.281     matthew   666:     if (! copy($oldfile,$newfile)) {
                    667:         return 0;
1.143     foxr      668:     }
1.281     matthew   669:     chmod(0660, $newfile);
                    670:     return 1;
1.143     foxr      671: }
1.157     foxr      672: #
                    673: #  Host files are passed out with externally visible host IPs.
                    674: #  If, for example, we are behind a fire-wall or NAT host, our 
                    675: #  internally visible IP may be different than the externally
                    676: #  visible IP.  Therefore, we always adjust the contents of the
                    677: #  host file so that the entry for ME is the IP that we believe
                    678: #  we have.  At present, this is defined as the entry that
                    679: #  DNS has for us.  If by some chance we are not able to get a
                    680: #  DNS translation for us, then we assume that the host.tab file
                    681: #  is correct.  
                    682: #    BUGBUGBUG - in the future, we really should see if we can
                    683: #       easily query the interface(s) instead.
                    684: # Parameter(s):
                    685: #     contents    - The contents of the host.tab to check.
                    686: # Returns:
                    687: #     newcontents - The adjusted contents.
                    688: #
                    689: #
                    690: sub AdjustHostContents {
                    691:     my $contents  = shift;
                    692:     my $adjusted;
                    693:     my $me        = $perlvar{'lonHostID'};
                    694: 
1.354     albertel  695:     foreach my $line (split(/\n/,$contents)) {
1.472     raeburn   696: 	if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/) ||
                    697:              ($line =~ /^\s*\^/))) {
1.157     foxr      698: 	    chomp($line);
                    699: 	    my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
                    700: 	    if ($id eq $me) {
1.354     albertel  701: 		my $ip = gethostbyname($name);
                    702: 		my $ipnew = inet_ntoa($ip);
                    703: 		$ip = $ipnew;
1.157     foxr      704: 		#  Reconstruct the host line and append to adjusted:
                    705: 		
1.354     albertel  706: 		my $newline = "$id:$domain:$role:$name:$ip";
                    707: 		if($maxcon ne "") { # Not all hosts have loncnew tuning params
                    708: 		    $newline .= ":$maxcon:$idleto:$mincon";
                    709: 		}
                    710: 		$adjusted .= $newline."\n";
1.157     foxr      711: 		
1.354     albertel  712: 	    } else {		# Not me, pass unmodified.
                    713: 		$adjusted .= $line."\n";
                    714: 	    }
1.157     foxr      715: 	} else {                  # Blank or comment never re-written.
                    716: 	    $adjusted .= $line."\n";	# Pass blanks and comments as is.
                    717: 	}
1.354     albertel  718:     }
                    719:     return $adjusted;
1.157     foxr      720: }
1.143     foxr      721: #
                    722: #   InstallFile: Called to install an administrative file:
1.412     foxr      723: #       - The file is created int a temp directory called <name>.tmp
                    724: #       - lcinstall file is called to install the file.
                    725: #         since the web app has no direct write access to the table directory
1.143     foxr      726: #
                    727: #  Parameters:
                    728: #       Name of the file
                    729: #       File Contents.
                    730: #  Return:
                    731: #      nonzero - success.
                    732: #      0       - failure and $! has an errno.
1.412     foxr      733: # Assumptions:
                    734: #    File installtion is a relatively infrequent
1.143     foxr      735: #
                    736: sub InstallFile {
1.192     foxr      737: 
                    738:     my ($Filename, $Contents) = @_;
1.412     foxr      739: #     my $TempFile = $Filename.".tmp";
                    740:     my $exedir = $perlvar{'lonDaemons'};
                    741:     my $tmpdir = $exedir.'/tmp/';
                    742:     my $TempFile = $tmpdir."TempTableFile.tmp";
1.143     foxr      743: 
                    744:     #  Open the file for write:
                    745: 
                    746:     my $fh = IO::File->new("> $TempFile"); # Write to temp.
                    747:     if(!(defined $fh)) {
                    748: 	&logthis('<font color="red"> Unable to create '.$TempFile."</font>");
                    749: 	return 0;
                    750:     }
                    751:     #  write the contents of the file:
                    752: 
                    753:     print $fh ($Contents); 
                    754:     $fh->close;			# In case we ever have a filesystem w. locking
                    755: 
1.412     foxr      756:     chmod(0664, $TempFile);	# Everyone can write it.
                    757: 
                    758:     # Use lcinstall file to put the file in the table directory...
                    759: 
                    760:     &Debug("Opening pipe to $exedir/lcinstallfile $TempFile $Filename");
                    761:     my $pf = IO::File->new("| $exedir/lcinstallfile   $TempFile $Filename > $exedir/logs/lcinstallfile.log");
                    762:     close $pf;
                    763:     my $err = $?;
                    764:     &Debug("Status is $err");
                    765:     if ($err != 0) {
                    766: 	my $msg = $err;
                    767: 	if ($err < @installerrors) {
                    768: 	    $msg = $installerrors[$err];
                    769: 	}
                    770: 	&logthis("Install failed for table file $Filename : $msg");
                    771: 	return 0;
                    772:     }
                    773: 
                    774:     # Remove the temp file:
1.143     foxr      775: 
1.412     foxr      776:     unlink($TempFile);
1.143     foxr      777: 
                    778:     return 1;
                    779: }
1.200     matthew   780: 
                    781: 
1.169     foxr      782: #
                    783: #   ConfigFileFromSelector: converts a configuration file selector
1.411     foxr      784: #                 into a configuration file pathname.
1.472     raeburn   785: #                 Supports the following file selectors: 
                    786: #                 hosts, domain, dns_hosts, dns_domain  
1.411     foxr      787: #
1.169     foxr      788: #
                    789: #  Parameters:
                    790: #      selector  - Configuration file selector.
                    791: #  Returns:
                    792: #      Full path to the file or undef if the selector is invalid.
                    793: #
                    794: sub ConfigFileFromSelector {
                    795:     my $selector   = shift;
                    796:     my $tablefile;
                    797: 
1.549     raeburn   798:     if ($selector eq 'loncapaCAcrl') {
                    799:         my $tabledir = $perlvar{'lonCertificateDirectory'};
                    800:         if (-d $tabledir) {
                    801:             $tablefile =  $tabledir.'/'.$selector.'.pem';
                    802:         }
                    803:     } else {
                    804:         my $tabledir = $perlvar{'lonTabDir'}.'/';
                    805:         if (($selector eq "hosts") || ($selector eq "domain") || 
                    806:             ($selector eq "dns_hosts") || ($selector eq "dns_domain")) {
                    807: 	    $tablefile =  $tabledir.$selector.'.tab';
                    808:         }
1.169     foxr      809:     }
                    810:     return $tablefile;
                    811: }
1.143     foxr      812: #
1.141     foxr      813: #   PushFile:  Called to do an administrative push of a file.
                    814: #              - Ensure the file being pushed is one we support.
                    815: #              - Backup the old file to <filename.saved>
                    816: #              - Separate the contents of the new file out from the
                    817: #                rest of the request.
                    818: #              - Write the new file.
                    819: #  Parameter:
                    820: #     Request - The entire user request.  This consists of a : separated
                    821: #               string pushfile:tablename:contents.
                    822: #     NOTE:  The contents may have :'s in it as well making things a bit
                    823: #            more interesting... but not much.
                    824: #  Returns:
                    825: #     String to send to client ("ok" or "refused" if bad file).
                    826: #
                    827: sub PushFile {
1.510     raeburn   828:     my $request = shift;
1.141     foxr      829:     my ($command, $filename, $contents) = split(":", $request, 3);
1.412     foxr      830:     &Debug("PushFile");
1.141     foxr      831:     
1.549     raeburn   832:     #  At this point in time, pushes for only the following tables and
                    833:     #  CRL file are supported:
1.141     foxr      834:     #   hosts.tab  ($filename eq host).
                    835:     #   domain.tab ($filename eq domain).
1.472     raeburn   836:     #   dns_hosts.tab ($filename eq dns_host).
1.554     raeburn   837:     #   dns_domain.tab ($filename eq dns_domain).
                    838:     #   loncapaCAcrl.pem ($filename eq loncapaCAcrl).
1.141     foxr      839:     # Construct the destination filename or reject the request.
                    840:     #
                    841:     # lonManage is supposed to ensure this, however this session could be
                    842:     # part of some elaborate spoof that managed somehow to authenticate.
                    843:     #
                    844: 
1.169     foxr      845: 
                    846:     my $tablefile = ConfigFileFromSelector($filename);
                    847:     if(! (defined $tablefile)) {
1.141     foxr      848: 	return "refused";
                    849:     }
1.412     foxr      850: 
1.157     foxr      851:     #  If the file being pushed is the host file, we adjust the entry for ourself so that the
                    852:     #  IP will be our current IP as looked up in dns.  Note this is only 99% good as it's possible
                    853:     #  to conceive of conditions where we don't have a DNS entry locally.  This is possible in a 
                    854:     #  network sense but it doesn't make much sense in a LonCAPA sense so we ignore (for now)
                    855:     #  that possibilty.
                    856: 
                    857:     if($filename eq "host") {
                    858: 	$contents = AdjustHostContents($contents);
1.549     raeburn   859:     } elsif (($filename eq 'dns_host') || ($filename eq 'dns_domain') ||
                    860:              ($filename eq 'loncapaCAcrl')) {
1.510     raeburn   861:         if ($contents eq '') {
                    862:             &logthis('<font color="red"> Pushfile: unable to install '
                    863:                     .$tablefile." - no data received from push. </font>");
                    864:             return 'error: push had no data';
                    865:         }
                    866:         if (&Apache::lonnet::get_host_ip($clientname)) {
                    867:             my $clienthost = &Apache::lonnet::hostname($clientname);
                    868:             if ($managers{$clientip} eq $clientname) {
                    869:                 my $clientprotocol = $Apache::lonnet::protocol{$clientname};
                    870:                 $clientprotocol = 'http' if ($clientprotocol ne 'https');
1.549     raeburn   871:                 my $url;
                    872:                 if ($filename eq 'loncapaCAcrl') {
                    873:                     $url = '/adm/dns/loncapaCRL';
                    874:                 } else {
                    875:                     $url = '/adm/'.$filename;
                    876:                     $url =~ s{_}{/};
                    877:                 }
1.510     raeburn   878:                 my $request=new HTTP::Request('GET',"$clientprotocol://$clienthost$url");
1.523     raeburn   879:                 my $response = LONCAPA::LWPReq::makerequest($clientname,$request,'',\%perlvar,60,0);
1.510     raeburn   880:                 if ($response->is_error()) {
                    881:                     &logthis('<font color="red"> Pushfile: unable to install '
                    882:                             .$tablefile." - error attempting to pull data. </font>");
                    883:                     return 'error: pull failed';
                    884:                 } else {
                    885:                     my $result = $response->content;
                    886:                     chomp($result);
                    887:                     unless ($result eq $contents) {
                    888:                         &logthis('<font color="red"> Pushfile: unable to install '
                    889:                                 .$tablefile." - pushed data and pulled data differ. </font>");
                    890:                         my $pushleng = length($contents);
                    891:                         my $pullleng = length($result);
                    892:                         if ($pushleng != $pullleng) {
                    893:                             return "error: $pushleng vs $pullleng bytes";
                    894:                         } else {
                    895:                             return "error: mismatch push and pull";
                    896:                         }
                    897:                     }
                    898:                 }
                    899:             }
                    900:         }
1.157     foxr      901:     }
                    902: 
1.141     foxr      903:     #  Install the new file:
                    904: 
1.412     foxr      905:     &logthis("Installing new $tablefile contents:\n$contents");
1.143     foxr      906:     if(!InstallFile($tablefile, $contents)) {
                    907: 	&logthis('<font color="red"> Pushfile: unable to install '
1.145     foxr      908: 	 .$tablefile." $! </font>");
1.143     foxr      909: 	return "error:$!";
1.224     foxr      910:     } else {
1.143     foxr      911: 	&logthis('<font color="green"> Installed new '.$tablefile
1.473     raeburn   912: 		 ." - transaction by: $clientname ($clientip)</font>");
1.472     raeburn   913:         my $adminmail = $perlvar{'lonAdmEMail'};
                    914:         my $admindom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                    915:         if ($admindom ne '') {
                    916:             my %domconfig =
                    917:                 &Apache::lonnet::get_dom('configuration',['contacts'],$admindom);
                    918:             if (ref($domconfig{'contacts'}) eq 'HASH') {
                    919:                 if ($domconfig{'contacts'}{'adminemail'} ne '') {
                    920:                     $adminmail = $domconfig{'contacts'}{'adminemail'};
                    921:                 }
                    922:             }
                    923:         }
                    924:         if ($adminmail =~ /^[^\@]+\@[^\@]+$/) {
                    925:             my $msg = new Mail::Send;
                    926:             $msg->to($adminmail);
                    927:             $msg->subject('LON-CAPA DNS update on '.$perlvar{'lonHostID'});
                    928:             $msg->add('Content-type','text/plain; charset=UTF-8');
                    929:             if (my $fh = $msg->open()) {
                    930:                 print $fh 'Update to '.$tablefile.' from Cluster Manager '.
1.473     raeburn   931:                           "$clientname ($clientip)\n";
1.472     raeburn   932:                 $fh->close;
                    933:             }
                    934:         }
1.143     foxr      935:     }
                    936: 
1.141     foxr      937:     #  Indicate success:
                    938:  
                    939:     return "ok";
                    940: 
                    941: }
1.145     foxr      942: 
                    943: #
                    944: #  Called to re-init either lonc or lond.
                    945: #
                    946: #  Parameters:
                    947: #    request   - The full request by the client.  This is of the form
                    948: #                reinit:<process>  
                    949: #                where <process> is allowed to be either of 
                    950: #                lonc or lond
                    951: #
                    952: #  Returns:
                    953: #     The string to be sent back to the client either:
                    954: #   ok         - Everything worked just fine.
                    955: #   error:why  - There was a failure and why describes the reason.
                    956: #
                    957: #
                    958: sub ReinitProcess {
                    959:     my $request = shift;
                    960: 
1.146     foxr      961: 
                    962:     # separate the request (reinit) from the process identifier and
                    963:     # validate it producing the name of the .pid file for the process.
                    964:     #
                    965:     #
                    966:     my ($junk, $process) = split(":", $request);
1.147     foxr      967:     my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
1.146     foxr      968:     if($process eq 'lonc') {
                    969: 	$processpidfile = $processpidfile."lonc.pid";
1.147     foxr      970: 	if (!open(PIDFILE, "< $processpidfile")) {
                    971: 	    return "error:Open failed for $processpidfile";
                    972: 	}
                    973: 	my $loncpid = <PIDFILE>;
                    974: 	close(PIDFILE);
                    975: 	logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
                    976: 		."</font>");
                    977: 	kill("USR2", $loncpid);
1.146     foxr      978:     } elsif ($process eq 'lond') {
1.147     foxr      979: 	logthis('<font color="red"> Reinitializing self (lond) </font>');
                    980: 	&UpdateHosts;			# Lond is us!!
1.146     foxr      981:     } else {
                    982: 	&logthis('<font color="yellow" Invalid reinit request for '.$process
                    983: 		 ."</font>");
                    984: 	return "error:Invalid process identifier $process";
                    985:     }
1.145     foxr      986:     return 'ok';
                    987: }
1.168     foxr      988: #   Validate a line in a configuration file edit script:
                    989: #   Validation includes:
                    990: #     - Ensuring the command is valid.
                    991: #     - Ensuring the command has sufficient parameters
                    992: #   Parameters:
                    993: #     scriptline - A line to validate (\n has been stripped for what it's worth).
1.167     foxr      994: #
1.168     foxr      995: #   Return:
                    996: #      0     - Invalid scriptline.
                    997: #      1     - Valid scriptline
                    998: #  NOTE:
                    999: #     Only the command syntax is checked, not the executability of the
                   1000: #     command.
                   1001: #
                   1002: sub isValidEditCommand {
                   1003:     my $scriptline = shift;
                   1004: 
                   1005:     #   Line elements are pipe separated:
                   1006: 
                   1007:     my ($command, $key, $newline)  = split(/\|/, $scriptline);
                   1008:     &logthis('<font color="green"> isValideditCommand checking: '.
                   1009: 	     "Command = '$command', Key = '$key', Newline = '$newline' </font>\n");
                   1010:     
                   1011:     if ($command eq "delete") {
                   1012: 	#
                   1013: 	#   key with no newline.
                   1014: 	#
                   1015: 	if( ($key eq "") || ($newline ne "")) {
                   1016: 	    return 0;		# Must have key but no newline.
                   1017: 	} else {
                   1018: 	    return 1;		# Valid syntax.
                   1019: 	}
1.169     foxr     1020:     } elsif ($command eq "replace") {
1.168     foxr     1021: 	#
                   1022: 	#   key and newline:
                   1023: 	#
                   1024: 	if (($key eq "") || ($newline eq "")) {
                   1025: 	    return 0;
                   1026: 	} else {
                   1027: 	    return 1;
                   1028: 	}
1.169     foxr     1029:     } elsif ($command eq "append") {
                   1030: 	if (($key ne "") && ($newline eq "")) {
                   1031: 	    return 1;
                   1032: 	} else {
                   1033: 	    return 0;
                   1034: 	}
1.168     foxr     1035:     } else {
                   1036: 	return 0;		# Invalid command.
                   1037:     }
                   1038:     return 0;			# Should not get here!!!
                   1039: }
1.169     foxr     1040: #
                   1041: #   ApplyEdit - Applies an edit command to a line in a configuration 
                   1042: #               file.  It is the caller's responsiblity to validate the
                   1043: #               edit line.
                   1044: #   Parameters:
                   1045: #      $directive - A single edit directive to apply.  
                   1046: #                   Edit directives are of the form:
                   1047: #                  append|newline      - Appends a new line to the file.
                   1048: #                  replace|key|newline - Replaces the line with key value 'key'
                   1049: #                  delete|key          - Deletes the line with key value 'key'.
                   1050: #      $editor   - A config file editor object that contains the
                   1051: #                  file being edited.
                   1052: #
                   1053: sub ApplyEdit {
1.192     foxr     1054: 
                   1055:     my ($directive, $editor) = @_;
1.169     foxr     1056: 
                   1057:     # Break the directive down into its command and its parameters
                   1058:     # (at most two at this point.  The meaning of the parameters, if in fact
                   1059:     #  they exist depends on the command).
                   1060: 
                   1061:     my ($command, $p1, $p2) = split(/\|/, $directive);
                   1062: 
                   1063:     if($command eq "append") {
                   1064: 	$editor->Append($p1);	          # p1 - key p2 null.
                   1065:     } elsif ($command eq "replace") {
                   1066: 	$editor->ReplaceLine($p1, $p2);   # p1 - key p2 = newline.
                   1067:     } elsif ($command eq "delete") {
                   1068: 	$editor->DeleteLine($p1);         # p1 - key p2 null.
                   1069:     } else {			          # Should not get here!!!
                   1070: 	die "Invalid command given to ApplyEdit $command"
                   1071:     }
                   1072: }
                   1073: #
                   1074: # AdjustOurHost:
                   1075: #           Adjusts a host file stored in a configuration file editor object
                   1076: #           for the true IP address of this host. This is necessary for hosts
                   1077: #           that live behind a firewall.
                   1078: #           Those hosts have a publicly distributed IP of the firewall, but
                   1079: #           internally must use their actual IP.  We assume that a given
                   1080: #           host only has a single IP interface for now.
                   1081: # Formal Parameters:
                   1082: #     editor   - The configuration file editor to adjust.  This
                   1083: #                editor is assumed to contain a hosts.tab file.
                   1084: # Strategy:
                   1085: #    - Figure out our hostname.
                   1086: #    - Lookup the entry for this host.
                   1087: #    - Modify the line to contain our IP
                   1088: #    - Do a replace for this host.
                   1089: sub AdjustOurHost {
                   1090:     my $editor        = shift;
                   1091: 
                   1092:     # figure out who I am.
                   1093: 
                   1094:     my $myHostName    = $perlvar{'lonHostID'}; # LonCAPA hostname.
                   1095: 
                   1096:     #  Get my host file entry.
                   1097: 
                   1098:     my $ConfigLine    = $editor->Find($myHostName);
                   1099:     if(! (defined $ConfigLine)) {
                   1100: 	die "AdjustOurHost - no entry for me in hosts file $myHostName";
                   1101:     }
                   1102:     # figure out my IP:
                   1103:     #   Use the config line to get my hostname.
                   1104:     #   Use gethostbyname to translate that into an IP address.
                   1105:     #
1.338     albertel 1106:     my ($id,$domain,$role,$name,$maxcon,$idleto,$mincon) = split(/:/,$ConfigLine);
1.169     foxr     1107:     #
                   1108:     #  Reassemble the config line from the elements in the list.
                   1109:     #  Note that if the loncnew items were not present before, they will
                   1110:     #  be now even if they would be empty
                   1111:     #
                   1112:     my $newConfigLine = $id;
1.338     albertel 1113:     foreach my $item ($domain, $role, $name, $maxcon, $idleto, $mincon) {
1.169     foxr     1114: 	$newConfigLine .= ":".$item;
                   1115:     }
                   1116:     #  Replace the line:
                   1117: 
                   1118:     $editor->ReplaceLine($id, $newConfigLine);
                   1119:     
                   1120: }
                   1121: #
                   1122: #   ReplaceConfigFile:
                   1123: #              Replaces a configuration file with the contents of a
                   1124: #              configuration file editor object.
                   1125: #              This is done by:
                   1126: #              - Copying the target file to <filename>.old
                   1127: #              - Writing the new file to <filename>.tmp
                   1128: #              - Moving <filename.tmp>  -> <filename>
                   1129: #              This laborious process ensures that the system is never without
                   1130: #              a configuration file that's at least valid (even if the contents
                   1131: #              may be dated).
                   1132: #   Parameters:
                   1133: #        filename   - Name of the file to modify... this is a full path.
                   1134: #        editor     - Editor containing the file.
                   1135: #
                   1136: sub ReplaceConfigFile {
1.192     foxr     1137:     
                   1138:     my ($filename, $editor) = @_;
1.168     foxr     1139: 
1.169     foxr     1140:     CopyFile ($filename, $filename.".old");
                   1141: 
                   1142:     my $contents  = $editor->Get(); # Get the contents of the file.
                   1143: 
                   1144:     InstallFile($filename, $contents);
                   1145: }
1.168     foxr     1146: #   
                   1147: #
                   1148: #   Called to edit a configuration table  file
1.167     foxr     1149: #   Parameters:
                   1150: #      request           - The entire command/request sent by lonc or lonManage
                   1151: #   Return:
                   1152: #      The reply to send to the client.
1.168     foxr     1153: #
1.167     foxr     1154: sub EditFile {
                   1155:     my $request = shift;
                   1156: 
                   1157:     #  Split the command into it's pieces:  edit:filetype:script
                   1158: 
1.339     albertel 1159:     my ($cmd, $filetype, $script) = split(/:/, $request,3);	# : in script
1.167     foxr     1160: 
                   1161:     #  Check the pre-coditions for success:
                   1162: 
1.339     albertel 1163:     if($cmd != "edit") {	# Something is amiss afoot alack.
1.167     foxr     1164: 	return "error:edit request detected, but request != 'edit'\n";
                   1165:     }
                   1166:     if( ($filetype ne "hosts")  &&
                   1167: 	($filetype ne "domain")) {
                   1168: 	return "error:edit requested with invalid file specifier: $filetype \n";
                   1169:     }
                   1170: 
                   1171:     #   Split the edit script and check it's validity.
1.168     foxr     1172: 
                   1173:     my @scriptlines = split(/\n/, $script);  # one line per element.
                   1174:     my $linecount   = scalar(@scriptlines);
                   1175:     for(my $i = 0; $i < $linecount; $i++) {
                   1176: 	chomp($scriptlines[$i]);
                   1177: 	if(!isValidEditCommand($scriptlines[$i])) {
                   1178: 	    return "error:edit with bad script line: '$scriptlines[$i]' \n";
                   1179: 	}
                   1180:     }
1.145     foxr     1181: 
1.167     foxr     1182:     #   Execute the edit operation.
1.169     foxr     1183:     #   - Create a config file editor for the appropriate file and 
                   1184:     #   - execute each command in the script:
                   1185:     #
                   1186:     my $configfile = ConfigFileFromSelector($filetype);
                   1187:     if (!(defined $configfile)) {
                   1188: 	return "refused\n";
                   1189:     }
                   1190:     my $editor = ConfigFileEdit->new($configfile);
1.167     foxr     1191: 
1.169     foxr     1192:     for (my $i = 0; $i < $linecount; $i++) {
                   1193: 	ApplyEdit($scriptlines[$i], $editor);
                   1194:     }
                   1195:     # If the file is the host file, ensure that our host is
                   1196:     # adjusted to have our ip:
                   1197:     #
                   1198:     if($filetype eq "host") {
                   1199: 	AdjustOurHost($editor);
                   1200:     }
                   1201:     #  Finally replace the current file with our file.
                   1202:     #
                   1203:     ReplaceConfigFile($configfile, $editor);
1.167     foxr     1204: 
                   1205:     return "ok\n";
                   1206: }
1.207     foxr     1207: 
1.255     foxr     1208: #   read_profile
                   1209: #
                   1210: #   Returns a set of specific entries from a user's profile file.
                   1211: #   this is a utility function that is used by both get_profile_entry and
                   1212: #   get_profile_entry_encrypted.
                   1213: #
                   1214: # Parameters:
                   1215: #    udom       - Domain in which the user exists.
                   1216: #    uname      - User's account name (loncapa account)
                   1217: #    namespace  - The profile namespace to open.
                   1218: #    what       - A set of & separated queries.
                   1219: # Returns:
                   1220: #    If all ok: - The string that needs to be shipped back to the user.
                   1221: #    If failure - A string that starts with error: followed by the failure
                   1222: #                 reason.. note that this probabyl gets shipped back to the
                   1223: #                 user as well.
                   1224: #
                   1225: sub read_profile {
                   1226:     my ($udom, $uname, $namespace, $what) = @_;
                   1227:     
                   1228:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   1229: 				 &GDBM_READER());
                   1230:     if ($hashref) {
                   1231:         my @queries=split(/\&/,$what);
1.440     raeburn  1232:         if ($namespace eq 'roles') {
                   1233:             @queries = map { &unescape($_); } @queries; 
                   1234:         }
1.255     foxr     1235:         my $qresult='';
                   1236: 	
                   1237: 	for (my $i=0;$i<=$#queries;$i++) {
                   1238: 	    $qresult.="$hashref->{$queries[$i]}&";    # Presumably failure gives empty string.
                   1239: 	}
                   1240: 	$qresult=~s/\&$//;              # Remove trailing & from last lookup.
1.311     albertel 1241: 	if (&untie_user_hash($hashref)) {
1.255     foxr     1242: 	    return $qresult;
                   1243: 	} else {
                   1244: 	    return "error: ".($!+0)." untie (GDBM) Failed";
                   1245: 	}
                   1246:     } else {
                   1247: 	if ($!+0 == 2) {
                   1248: 	    return "error:No such file or GDBM reported bad block error";
                   1249: 	} else {
                   1250: 	    return "error: ".($!+0)." tie (GDBM) Failed";
                   1251: 	}
                   1252:     }
                   1253: 
                   1254: }
1.214     foxr     1255: #--------------------- Request Handlers --------------------------------------------
                   1256: #
1.215     foxr     1257: #   By convention each request handler registers itself prior to the sub 
                   1258: #   declaration:
1.214     foxr     1259: #
                   1260: 
1.216     foxr     1261: #++
                   1262: #
1.214     foxr     1263: #  Handles ping requests.
                   1264: #  Parameters:
                   1265: #      $cmd    - the actual keyword that invoked us.
                   1266: #      $tail   - the tail of the request that invoked us.
                   1267: #      $replyfd- File descriptor connected to the client
                   1268: #  Implicit Inputs:
                   1269: #      $currenthostid - Global variable that carries the name of the host we are
                   1270: #                       known as.
                   1271: #  Returns:
                   1272: #      1       - Ok to continue processing.
                   1273: #      0       - Program should exit.
                   1274: #  Side effects:
                   1275: #      Reply information is sent to the client.
                   1276: sub ping_handler {
                   1277:     my ($cmd, $tail, $client) = @_;
                   1278:     Debug("$cmd $tail $client .. $currenthostid:");
                   1279:    
1.387     albertel 1280:     Reply( $client,\$currenthostid,"$cmd:$tail");
1.214     foxr     1281:    
                   1282:     return 1;
                   1283: }
                   1284: &register_handler("ping", \&ping_handler, 0, 1, 1);       # Ping unencoded, client or manager.
                   1285: 
1.216     foxr     1286: #++
1.215     foxr     1287: #
                   1288: # Handles pong requests.  Pong replies with our current host id, and
                   1289: #                         the results of a ping sent to us via our lonc.
                   1290: #
                   1291: # Parameters:
                   1292: #      $cmd    - the actual keyword that invoked us.
                   1293: #      $tail   - the tail of the request that invoked us.
                   1294: #      $replyfd- File descriptor connected to the client
                   1295: #  Implicit Inputs:
                   1296: #      $currenthostid - Global variable that carries the name of the host we are
                   1297: #                       connected to.
                   1298: #  Returns:
                   1299: #      1       - Ok to continue processing.
                   1300: #      0       - Program should exit.
                   1301: #  Side effects:
                   1302: #      Reply information is sent to the client.
                   1303: sub pong_handler {
                   1304:     my ($cmd, $tail, $replyfd) = @_;
                   1305: 
1.365     albertel 1306:     my $reply=&Apache::lonnet::reply("ping",$clientname);
1.215     foxr     1307:     &Reply( $replyfd, "$currenthostid:$reply\n", "$cmd:$tail"); 
                   1308:     return 1;
                   1309: }
                   1310: &register_handler("pong", \&pong_handler, 0, 1, 1);       # Pong unencoded, client or manager
                   1311: 
1.216     foxr     1312: #++
                   1313: #      Called to establish an encrypted session key with the remote client.
                   1314: #      Note that with secure lond, in most cases this function is never
                   1315: #      invoked.  Instead, the secure session key is established either
                   1316: #      via a local file that's locked down tight and only lives for a short
                   1317: #      time, or via an ssl tunnel...and is generated from a bunch-o-random
                   1318: #      bits from /dev/urandom, rather than the predictable pattern used by
                   1319: #      by this sub.  This sub is only used in the old-style insecure
                   1320: #      key negotiation.
                   1321: # Parameters:
                   1322: #      $cmd    - the actual keyword that invoked us.
                   1323: #      $tail   - the tail of the request that invoked us.
                   1324: #      $replyfd- File descriptor connected to the client
                   1325: #  Implicit Inputs:
                   1326: #      $currenthostid - Global variable that carries the name of the host
                   1327: #                       known as.
1.448     raeburn  1328: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.216     foxr     1329: #  Returns:
                   1330: #      1       - Ok to continue processing.
                   1331: #      0       - Program should exit.
                   1332: #  Implicit Outputs:
                   1333: #      Reply information is sent to the client.
                   1334: #      $cipher is set with a reference to a new IDEA encryption object.
                   1335: #
                   1336: sub establish_key_handler {
                   1337:     my ($cmd, $tail, $replyfd) = @_;
                   1338: 
                   1339:     my $buildkey=time.$$.int(rand 100000);
                   1340:     $buildkey=~tr/1-6/A-F/;
                   1341:     $buildkey=int(rand 100000).$buildkey.int(rand 100000);
                   1342:     my $key=$currenthostid.$clientname;
                   1343:     $key=~tr/a-z/A-Z/;
                   1344:     $key=~tr/G-P/0-9/;
                   1345:     $key=~tr/Q-Z/0-9/;
                   1346:     $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
                   1347:     $key=substr($key,0,32);
                   1348:     my $cipherkey=pack("H32",$key);
                   1349:     $cipher=new IDEA $cipherkey;
1.387     albertel 1350:     &Reply($replyfd, \$buildkey, "$cmd:$tail"); 
1.216     foxr     1351:    
                   1352:     return 1;
                   1353: 
                   1354: }
                   1355: &register_handler("ekey", \&establish_key_handler, 0, 1,1);
                   1356: 
1.217     foxr     1357: #     Handler for the load command.  Returns the current system load average
                   1358: #     to the requestor.
                   1359: #
                   1360: # Parameters:
                   1361: #      $cmd    - the actual keyword that invoked us.
                   1362: #      $tail   - the tail of the request that invoked us.
                   1363: #      $replyfd- File descriptor connected to the client
                   1364: #  Implicit Inputs:
                   1365: #      $currenthostid - Global variable that carries the name of the host
                   1366: #                       known as.
1.448     raeburn  1367: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.217     foxr     1368: #  Returns:
                   1369: #      1       - Ok to continue processing.
                   1370: #      0       - Program should exit.
                   1371: #  Side effects:
                   1372: #      Reply information is sent to the client.
                   1373: sub load_handler {
                   1374:     my ($cmd, $tail, $replyfd) = @_;
                   1375: 
1.463     foxr     1376: 
                   1377: 
1.217     foxr     1378:    # Get the load average from /proc/loadavg and calculate it as a percentage of
                   1379:    # the allowed load limit as set by the perl global variable lonLoadLim
                   1380: 
                   1381:     my $loadavg;
                   1382:     my $loadfile=IO::File->new('/proc/loadavg');
                   1383:    
                   1384:     $loadavg=<$loadfile>;
                   1385:     $loadavg =~ s/\s.*//g;                      # Extract the first field only.
                   1386:    
                   1387:     my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
                   1388: 
1.387     albertel 1389:     &Reply( $replyfd, \$loadpercent, "$cmd:$tail");
1.217     foxr     1390:    
                   1391:     return 1;
                   1392: }
1.263     albertel 1393: &register_handler("load", \&load_handler, 0, 1, 0);
1.217     foxr     1394: 
                   1395: #
                   1396: #   Process the userload request.  This sub returns to the client the current
                   1397: #  user load average.  It can be invoked either by clients or managers.
                   1398: #
                   1399: # Parameters:
                   1400: #      $cmd    - the actual keyword that invoked us.
                   1401: #      $tail   - the tail of the request that invoked us.
                   1402: #      $replyfd- File descriptor connected to the client
                   1403: #  Implicit Inputs:
                   1404: #      $currenthostid - Global variable that carries the name of the host
                   1405: #                       known as.
1.448     raeburn  1406: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.217     foxr     1407: #  Returns:
                   1408: #      1       - Ok to continue processing.
                   1409: #      0       - Program should exit
                   1410: # Implicit inputs:
                   1411: #     whatever the userload() function requires.
                   1412: #  Implicit outputs:
                   1413: #     the reply is written to the client.
                   1414: #
                   1415: sub user_load_handler {
                   1416:     my ($cmd, $tail, $replyfd) = @_;
                   1417: 
1.365     albertel 1418:     my $userloadpercent=&Apache::lonnet::userload();
1.387     albertel 1419:     &Reply($replyfd, \$userloadpercent, "$cmd:$tail");
1.217     foxr     1420:     
                   1421:     return 1;
                   1422: }
1.263     albertel 1423: &register_handler("userload", \&user_load_handler, 0, 1, 0);
1.217     foxr     1424: 
1.218     foxr     1425: #   Process a request for the authorization type of a user:
                   1426: #   (userauth).
                   1427: #
                   1428: # Parameters:
                   1429: #      $cmd    - the actual keyword that invoked us.
                   1430: #      $tail   - the tail of the request that invoked us.
                   1431: #      $replyfd- File descriptor connected to the client
                   1432: #  Returns:
                   1433: #      1       - Ok to continue processing.
                   1434: #      0       - Program should exit
                   1435: # Implicit outputs:
                   1436: #    The user authorization type is written to the client.
                   1437: #
                   1438: sub user_authorization_type {
                   1439:     my ($cmd, $tail, $replyfd) = @_;
                   1440:    
                   1441:     my $userinput = "$cmd:$tail";
                   1442:    
                   1443:     #  Pull the domain and username out of the command tail.
1.222     foxr     1444:     # and call get_auth_type to determine the authentication type.
1.218     foxr     1445:    
                   1446:     my ($udom,$uname)=split(/:/,$tail);
1.222     foxr     1447:     my $result = &get_auth_type($udom, $uname);
1.218     foxr     1448:     if($result eq "nouser") {
                   1449: 	&Failure( $replyfd, "unknown_user\n", $userinput);
                   1450:     } else {
                   1451: 	#
1.222     foxr     1452: 	# We only want to pass the second field from get_auth_type
1.218     foxr     1453: 	# for ^krb.. otherwise we'll be handing out the encrypted
                   1454: 	# password for internals e.g.
                   1455: 	#
                   1456: 	my ($type,$otherinfo) = split(/:/,$result);
                   1457: 	if($type =~ /^krb/) {
                   1458: 	    $type = $result;
1.269     raeburn  1459: 	} else {
                   1460:             $type .= ':';
                   1461:         }
1.387     albertel 1462: 	&Reply( $replyfd, \$type, $userinput);
1.218     foxr     1463:     }
                   1464:   
                   1465:     return 1;
                   1466: }
                   1467: &register_handler("currentauth", \&user_authorization_type, 1, 1, 0);
                   1468: 
                   1469: #   Process a request by a manager to push a hosts or domain table 
                   1470: #   to us.  We pick apart the command and pass it on to the subs
                   1471: #   that already exist to do this.
                   1472: #
                   1473: # Parameters:
                   1474: #      $cmd    - the actual keyword that invoked us.
                   1475: #      $tail   - the tail of the request that invoked us.
                   1476: #      $client - File descriptor connected to the client
                   1477: #  Returns:
                   1478: #      1       - Ok to continue processing.
                   1479: #      0       - Program should exit
                   1480: # Implicit Output:
                   1481: #    a reply is written to the client.
                   1482: sub push_file_handler {
                   1483:     my ($cmd, $tail, $client) = @_;
1.412     foxr     1484:     &Debug("In push file handler");
1.218     foxr     1485:     my $userinput = "$cmd:$tail";
                   1486: 
                   1487:     # At this time we only know that the IP of our partner is a valid manager
                   1488:     # the code below is a hook to do further authentication (e.g. to resolve
                   1489:     # spoofing).
                   1490: 
                   1491:     my $cert = &GetCertificate($userinput);
1.412     foxr     1492:     if(&ValidManager($cert)) {
                   1493: 	&Debug("Valid manager: $client");
1.218     foxr     1494: 
                   1495: 	# Now presumably we have the bona fides of both the peer host and the
                   1496: 	# process making the request.
                   1497:       
                   1498: 	my $reply = &PushFile($userinput);
1.387     albertel 1499: 	&Reply($client, \$reply, $userinput);
1.218     foxr     1500: 
                   1501:     } else {
1.412     foxr     1502: 	&logthis("push_file_handler $client is not valid");
1.218     foxr     1503: 	&Failure( $client, "refused\n", $userinput);
                   1504:     } 
1.219     foxr     1505:     return 1;
1.218     foxr     1506: }
                   1507: &register_handler("pushfile", \&push_file_handler, 1, 0, 1);
                   1508: 
1.399     raeburn  1509: # The du_handler routine should be considered obsolete and is retained
                   1510: # for communication with legacy servers.  Please see the du2_handler.
1.243     banghart 1511: #
1.399     raeburn  1512: #   du  - list the disk usage of a directory recursively. 
1.243     banghart 1513: #    
                   1514: #   note: stolen code from the ls file handler
                   1515: #   under construction by Rick Banghart 
                   1516: #    .
                   1517: # Parameters:
                   1518: #    $cmd        - The command that dispatched us (du).
                   1519: #    $ududir     - The directory path to list... I'm not sure what this
                   1520: #                  is relative as things like ls:. return e.g.
                   1521: #                  no_such_dir.
                   1522: #    $client     - Socket open on the client.
                   1523: # Returns:
                   1524: #     1 - indicating that the daemon should not disconnect.
                   1525: # Side Effects:
                   1526: #   The reply is written to  $client.
                   1527: #
                   1528: sub du_handler {
                   1529:     my ($cmd, $ududir, $client) = @_;
1.339     albertel 1530:     ($ududir) = split(/:/,$ududir); # Make 'telnet' testing easier.
1.251     foxr     1531:     my $userinput = "$cmd:$ududir";
                   1532: 
1.245     albertel 1533:     if ($ududir=~/\.\./ || $ududir!~m|^/home/httpd/|) {
                   1534: 	&Failure($client,"refused\n","$cmd:$ududir");
                   1535: 	return 1;
                   1536:     }
1.249     foxr     1537:     #  Since $ududir could have some nasties in it,
                   1538:     #  we will require that ududir is a valid
                   1539:     #  directory.  Just in case someone tries to
                   1540:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
                   1541:     #  etc.
                   1542:     #
                   1543:     if (-d $ududir) {
1.292     albertel 1544: 	my $total_size=0;
                   1545: 	my $code=sub { 
                   1546: 	    if ($_=~/\.\d+\./) { return;} 
                   1547: 	    if ($_=~/\.meta$/) { return;}
1.362     albertel 1548: 	    if (-d $_)         { return;}
1.292     albertel 1549: 	    $total_size+=(stat($_))[7];
                   1550: 	};
1.295     raeburn  1551: 	chdir($ududir);
1.292     albertel 1552: 	find($code,$ududir);
                   1553: 	$total_size=int($total_size/1024);
1.387     albertel 1554: 	&Reply($client,\$total_size,"$cmd:$ududir");
1.249     foxr     1555:     } else {
1.251     foxr     1556: 	&Failure($client, "bad_directory:$ududir\n","$cmd:$ududir"); 
1.249     foxr     1557:     }
1.243     banghart 1558:     return 1;
                   1559: }
                   1560: &register_handler("du", \&du_handler, 0, 1, 0);
1.218     foxr     1561: 
1.399     raeburn  1562: # Please also see the du_handler, which is obsoleted by du2. 
                   1563: # du2_handler differs from du_handler in that required path to directory
                   1564: # provided by &propath() is prepended in the handler instead of on the 
                   1565: # client side.
1.239     foxr     1566: #
1.399     raeburn  1567: #   du2  - list the disk usage of a directory recursively.
                   1568: #
                   1569: # Parameters:
                   1570: #    $cmd        - The command that dispatched us (du).
                   1571: #    $tail       - The tail of the request that invoked us.
                   1572: #                  $tail is a : separated list of the following:
                   1573: #                   - $ududir - directory path to list (before prepending)
                   1574: #                   - $getpropath = 1 if &propath() should prepend
                   1575: #                   - $uname - username to use for &propath or user dir
                   1576: #                   - $udom - domain to use for &propath or user dir
                   1577: #                   All are escaped.
                   1578: #    $client     - Socket open on the client.
                   1579: # Returns:
                   1580: #     1 - indicating that the daemon should not disconnect.
                   1581: # Side Effects:
                   1582: #   The reply is written to $client.
                   1583: #
                   1584: 
                   1585: sub du2_handler {
                   1586:     my ($cmd, $tail, $client) = @_;
                   1587:     my ($ududir,$getpropath,$uname,$udom) = map { &unescape($_) } (split(/:/, $tail));
                   1588:     my $userinput = "$cmd:$tail";
                   1589:     if (($ududir=~/\.\./) || (($ududir!~m|^/home/httpd/|) && (!$getpropath))) {
                   1590:         &Failure($client,"refused\n","$cmd:$tail");
                   1591:         return 1;
                   1592:     }
                   1593:     if ($getpropath) {
                   1594:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
                   1595:             $ududir = &propath($udom,$uname).'/'.$ududir;
                   1596:         } else {
                   1597:             &Failure($client,"refused\n","$cmd:$tail");
                   1598:             return 1;
                   1599:         }
                   1600:     }
                   1601:     #  Since $ududir could have some nasties in it,
                   1602:     #  we will require that ududir is a valid
                   1603:     #  directory.  Just in case someone tries to
                   1604:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
                   1605:     #  etc.
                   1606:     #
                   1607:     if (-d $ududir) {
                   1608:         my $total_size=0;
                   1609:         my $code=sub {
                   1610:             if ($_=~/\.\d+\./) { return;}
                   1611:             if ($_=~/\.meta$/) { return;}
                   1612:             if (-d $_)         { return;}
                   1613:             $total_size+=(stat($_))[7];
                   1614:         };
                   1615:         chdir($ududir);
                   1616:         find($code,$ududir);
                   1617:         $total_size=int($total_size/1024);
                   1618:         &Reply($client,\$total_size,"$cmd:$ududir");
                   1619:     } else {
                   1620:         &Failure($client, "bad_directory:$ududir\n","$cmd:$tail");
                   1621:     }
                   1622:     return 1;
                   1623: }
                   1624: &register_handler("du2", \&du2_handler, 0, 1, 0);
                   1625: 
                   1626: #
                   1627: # The ls_handler routine should be considered obsolete and is retained
                   1628: # for communication with legacy servers.  Please see the ls3_handler.
1.280     matthew  1629: #
1.239     foxr     1630: #   ls  - list the contents of a directory.  For each file in the
                   1631: #    selected directory the filename followed by the full output of
                   1632: #    the stat function is returned.  The returned info for each
                   1633: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1634: #
                   1635: #    If the requested path contains /../ or is:
                   1636: #
                   1637: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1638: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1639: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1640: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
                   1641: #    or is:
                   1642: #
1.538     raeburn  1643: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1644: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1645: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1646: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
1.529     raeburn  1647: #
                   1648: #    the response will be "refused".
                   1649: #
1.239     foxr     1650: # Parameters:
                   1651: #    $cmd        - The command that dispatched us (ls).
                   1652: #    $ulsdir     - The directory path to list... I'm not sure what this
                   1653: #                  is relative as things like ls:. return e.g.
                   1654: #                  no_such_dir.
                   1655: #    $client     - Socket open on the client.
                   1656: # Returns:
                   1657: #     1 - indicating that the daemon should not disconnect.
                   1658: # Side Effects:
                   1659: #   The reply is written to  $client.
                   1660: #
                   1661: sub ls_handler {
1.280     matthew  1662:     # obsoleted by ls2_handler
1.239     foxr     1663:     my ($cmd, $ulsdir, $client) = @_;
                   1664: 
                   1665:     my $userinput = "$cmd:$ulsdir";
                   1666: 
                   1667:     my $obs;
                   1668:     my $rights;
                   1669:     my $ulsout='';
                   1670:     my $ulsfn;
1.529     raeburn  1671:     if ($ulsdir =~m{/\.\./}) {
                   1672:         &Failure($client,"refused\n",$userinput);
                   1673:         return 1;
                   1674:     }
1.239     foxr     1675:     if (-e $ulsdir) {
                   1676: 	if(-d $ulsdir) {
1.539     raeburn  1677:             unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1678:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
1.529     raeburn  1679:                 &Failure($client,"refused\n",$userinput);
                   1680:                 return 1;
                   1681:             }
1.239     foxr     1682: 	    if (opendir(LSDIR,$ulsdir)) {
                   1683: 		while ($ulsfn=readdir(LSDIR)) {
1.291     albertel 1684: 		    undef($obs);
                   1685: 		    undef($rights); 
1.239     foxr     1686: 		    my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1687: 		    #We do some obsolete checking here
                   1688: 		    if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   1689: 			open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1690: 			my @obsolete=<FILE>;
                   1691: 			foreach my $obsolete (@obsolete) {
1.301     www      1692: 			    if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
1.239     foxr     1693: 			    if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
                   1694: 			}
                   1695: 		    }
                   1696: 		    $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
                   1697: 		    if($obs eq '1') { $ulsout.="&1"; }
                   1698: 		    else { $ulsout.="&0"; }
                   1699: 		    if($rights eq '1') { $ulsout.="&1:"; }
                   1700: 		    else { $ulsout.="&0:"; }
                   1701: 		}
                   1702: 		closedir(LSDIR);
                   1703: 	    }
                   1704: 	} else {
1.539     raeburn  1705:             unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1706:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
1.529     raeburn  1707:                 &Failure($client,"refused\n",$userinput);
                   1708:                 return 1;
                   1709:             }
1.239     foxr     1710: 	    my @ulsstats=stat($ulsdir);
                   1711: 	    $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1712: 	}
                   1713:     } else {
                   1714: 	$ulsout='no_such_dir';
                   1715:     }
                   1716:     if ($ulsout eq '') { $ulsout='empty'; }
1.387     albertel 1717:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1.239     foxr     1718:     
                   1719:     return 1;
                   1720: 
                   1721: }
                   1722: &register_handler("ls", \&ls_handler, 0, 1, 0);
                   1723: 
1.399     raeburn  1724: # The ls2_handler routine should be considered obsolete and is retained
                   1725: # for communication with legacy servers.  Please see the ls3_handler.
                   1726: # Please also see the ls_handler, which was itself obsoleted by ls2.
1.280     matthew  1727: # ls2_handler differs from ls_handler in that it escapes its return 
                   1728: # values before concatenating them together with ':'s.
                   1729: #
                   1730: #   ls2  - list the contents of a directory.  For each file in the
                   1731: #    selected directory the filename followed by the full output of
                   1732: #    the stat function is returned.  The returned info for each
                   1733: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1734: #
                   1735: #    If the requested path contains /../ or is:
                   1736: #
                   1737: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1738: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1739: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1740: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
                   1741: #    or is:
                   1742: #
1.538     raeburn  1743: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1744: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1745: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1746: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
1.529     raeburn  1747: #
                   1748: #    the response will be "refused".
                   1749: #
1.280     matthew  1750: # Parameters:
                   1751: #    $cmd        - The command that dispatched us (ls).
                   1752: #    $ulsdir     - The directory path to list... I'm not sure what this
                   1753: #                  is relative as things like ls:. return e.g.
                   1754: #                  no_such_dir.
                   1755: #    $client     - Socket open on the client.
                   1756: # Returns:
                   1757: #     1 - indicating that the daemon should not disconnect.
                   1758: # Side Effects:
                   1759: #   The reply is written to  $client.
                   1760: #
                   1761: sub ls2_handler {
                   1762:     my ($cmd, $ulsdir, $client) = @_;
                   1763: 
                   1764:     my $userinput = "$cmd:$ulsdir";
                   1765: 
                   1766:     my $obs;
                   1767:     my $rights;
                   1768:     my $ulsout='';
                   1769:     my $ulsfn;
1.529     raeburn  1770:     if ($ulsdir =~m{/\.\./}) {
                   1771:         &Failure($client,"refused\n",$userinput);
                   1772:         return 1;
                   1773:     }
1.280     matthew  1774:     if (-e $ulsdir) {
                   1775:         if(-d $ulsdir) {
1.539     raeburn  1776:             unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1777:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
1.529     raeburn  1778:                 &Failure($client,"refused\n","$userinput");
                   1779:                 return 1;
                   1780:             }
1.280     matthew  1781:             if (opendir(LSDIR,$ulsdir)) {
                   1782:                 while ($ulsfn=readdir(LSDIR)) {
1.291     albertel 1783:                     undef($obs);
                   1784: 		    undef($rights); 
1.280     matthew  1785:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1786:                     #We do some obsolete checking here
                   1787:                     if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   1788:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1789:                         my @obsolete=<FILE>;
                   1790:                         foreach my $obsolete (@obsolete) {
1.301     www      1791:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
1.280     matthew  1792:                             if($obsolete =~ m|(<copyright>)(default)|) {
                   1793:                                 $rights = 1;
                   1794:                             }
                   1795:                         }
                   1796:                     }
                   1797:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
                   1798:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1799:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1800:                     $ulsout.= &escape($tmp).':';
                   1801:                 }
                   1802:                 closedir(LSDIR);
                   1803:             }
                   1804:         } else {
1.539     raeburn  1805:             unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1806:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
1.529     raeburn  1807:                 &Failure($client,"refused\n",$userinput);
                   1808:                 return 1;
                   1809:             }
1.280     matthew  1810:             my @ulsstats=stat($ulsdir);
                   1811:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1812:         }
                   1813:     } else {
                   1814:         $ulsout='no_such_dir';
                   1815:    }
                   1816:    if ($ulsout eq '') { $ulsout='empty'; }
1.387     albertel 1817:    &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1.280     matthew  1818:    return 1;
                   1819: }
                   1820: &register_handler("ls2", \&ls2_handler, 0, 1, 0);
1.399     raeburn  1821: #
                   1822: #   ls3  - list the contents of a directory.  For each file in the
                   1823: #    selected directory the filename followed by the full output of
                   1824: #    the stat function is returned.  The returned info for each
                   1825: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1826: #
                   1827: #    If the requested path (after prepending) contains /../ or is:
                   1828: #
                   1829: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1830: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1831: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1832: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
1.539     raeburn  1833: #        (d) /home/httpd/html/priv/<domain> and client is the homeserver
1.529     raeburn  1834: #
1.530     raeburn  1835: #    or is:
1.529     raeburn  1836: #
1.538     raeburn  1837: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1838: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1839: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1840: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
                   1841: #        (d) /home/httpd/html/priv/<domain>/<username>/ and client is the homeserver
1.529     raeburn  1842: #
                   1843: #    the response will be "refused".
                   1844: #
1.399     raeburn  1845: # Parameters:
                   1846: #    $cmd        - The command that dispatched us (ls).
                   1847: #    $tail       - The tail of the request that invoked us.
                   1848: #                  $tail is a : separated list of the following:
                   1849: #                   - $ulsdir - directory path to list (before prepending)
                   1850: #                   - $getpropath = 1 if &propath() should prepend
                   1851: #                   - $getuserdir = 1 if path to user dir in lonUsers should
                   1852: #                                     prepend
                   1853: #                   - $alternate_root - path to prepend
                   1854: #                   - $uname - username to use for &propath or user dir
                   1855: #                   - $udom - domain to use for &propath or user dir
                   1856: #            All of these except $getpropath and &getuserdir are escaped.    
                   1857: #                  no_such_dir.
                   1858: #    $client     - Socket open on the client.
                   1859: # Returns:
                   1860: #     1 - indicating that the daemon should not disconnect.
                   1861: # Side Effects:
                   1862: #   The reply is written to $client.
                   1863: #
                   1864: 
                   1865: sub ls3_handler {
                   1866:     my ($cmd, $tail, $client) = @_;
                   1867:     my $userinput = "$cmd:$tail";
                   1868:     my ($ulsdir,$getpropath,$getuserdir,$alternate_root,$uname,$udom) =
                   1869:         split(/:/,$tail);
                   1870:     if (defined($ulsdir)) {
                   1871:         $ulsdir = &unescape($ulsdir);
                   1872:     }
                   1873:     if (defined($alternate_root)) {
                   1874:         $alternate_root = &unescape($alternate_root);
                   1875:     }
                   1876:     if (defined($uname)) {
                   1877:         $uname = &unescape($uname);
                   1878:     }
                   1879:     if (defined($udom)) {
                   1880:         $udom = &unescape($udom);
                   1881:     }
                   1882: 
                   1883:     my $dir_root = $perlvar{'lonDocRoot'};
1.529     raeburn  1884:     if (($getpropath) || ($getuserdir)) {
1.399     raeburn  1885:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
                   1886:             $dir_root = &propath($udom,$uname);
                   1887:             $dir_root =~ s/\/$//;
                   1888:         } else {
1.529     raeburn  1889:             &Failure($client,"refused\n",$userinput);
1.399     raeburn  1890:             return 1;
                   1891:         }
1.400     raeburn  1892:     } elsif ($alternate_root ne '') {
1.399     raeburn  1893:         $dir_root = $alternate_root;
                   1894:     }
1.408     raeburn  1895:     if (($dir_root ne '') && ($dir_root ne '/')) {
1.400     raeburn  1896:         if ($ulsdir =~ /^\//) {
                   1897:             $ulsdir = $dir_root.$ulsdir;
                   1898:         } else {
                   1899:             $ulsdir = $dir_root.'/'.$ulsdir;
                   1900:         }
1.399     raeburn  1901:     }
1.529     raeburn  1902:     if ($ulsdir =~m{/\.\./}) {
                   1903:         &Failure($client,"refused\n",$userinput);
                   1904:         return 1;
                   1905:     }
                   1906:     my $islocal;
                   1907:     my @machine_ids = &Apache::lonnet::current_machine_ids();
                   1908:     if (grep(/^\Q$clientname\E$/,@machine_ids)) {
                   1909:         $islocal = 1;
                   1910:     }
1.399     raeburn  1911:     my $obs;
                   1912:     my $rights;
                   1913:     my $ulsout='';
                   1914:     my $ulsfn;
1.547     raeburn  1915: 
                   1916:     my ($crscheck,$toplevel,$currdom,$currnum,$skip);
                   1917:     unless ($islocal) {
                   1918:         my ($major,$minor) = split(/\./,$clientversion);
                   1919:         if (($major < 2) || ($major == 2 && $minor < 12)) {
                   1920:             $crscheck = 1;
                   1921:         }
                   1922:     }
1.399     raeburn  1923:     if (-e $ulsdir) {
                   1924:         if(-d $ulsdir) {
1.529     raeburn  1925:             unless (($getpropath) || ($getuserdir) ||
1.539     raeburn  1926:                     ($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1927:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles}) ||
                   1928:                     (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain}) && ($islocal))) {
1.529     raeburn  1929:                 &Failure($client,"refused\n",$userinput);
                   1930:                 return 1;
                   1931:             }
1.547     raeburn  1932:             if (($crscheck) &&
                   1933:                 ($ulsdir =~ m{^/home/httpd/html/res/($LONCAPA::match_domain)(/?$|/$LONCAPA::match_courseid)})) {
                   1934:                 ($currdom,my $posscnum) = ($1,$2);
                   1935:                 if (($posscnum eq '') || ($posscnum eq '/')) {
                   1936:                     $toplevel = 1;
                   1937:                 } else {
                   1938:                     $posscnum =~ s{^/+}{};
                   1939:                     if (&LONCAPA::Lond::is_course($currdom,$posscnum)) {
                   1940:                         $skip = 1;
                   1941:                     }
                   1942:                 }
                   1943:             }
                   1944:             if ((!$skip) && (opendir(LSDIR,$ulsdir))) {
1.399     raeburn  1945:                 while ($ulsfn=readdir(LSDIR)) {
1.547     raeburn  1946:                     if (($crscheck) && ($toplevel) && ($currdom ne '') &&
                   1947:                         ($ulsfn =~ /^$LONCAPA::match_courseid$/) && (-d "$ulsdir/$ulsfn")) {
                   1948:                         if (&LONCAPA::Lond::is_course($currdom,$ulsfn)) {
                   1949:                             next;
                   1950:                         }
                   1951:                     }
1.399     raeburn  1952:                     undef($obs);
                   1953:                     undef($rights);
                   1954:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1955:                     #We do some obsolete checking here
                   1956:                     if(-e $ulsdir.'/'.$ulsfn.".meta") {
                   1957:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1958:                         my @obsolete=<FILE>;
                   1959:                         foreach my $obsolete (@obsolete) {
                   1960:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; }
                   1961:                             if($obsolete =~ m|(<copyright>)(default)|) {
                   1962:                                 $rights = 1;
                   1963:                             }
                   1964:                         }
                   1965:                     }
                   1966:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
                   1967:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1968:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1969:                     $ulsout.= &escape($tmp).':';
                   1970:                 }
                   1971:                 closedir(LSDIR);
                   1972:             }
                   1973:         } else {
1.529     raeburn  1974:             unless (($getpropath) || ($getuserdir) ||
1.539     raeburn  1975:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1976:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/}) ||
                   1977:                     (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain/$LONCAPA::match_name/}) && ($islocal))) {
1.529     raeburn  1978:                 &Failure($client,"refused\n",$userinput);
                   1979:                 return 1;
                   1980:             }
1.399     raeburn  1981:             my @ulsstats=stat($ulsdir);
                   1982:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1983:         }
                   1984:     } else {
                   1985:         $ulsout='no_such_dir';
1.400     raeburn  1986:     }
                   1987:     if ($ulsout eq '') { $ulsout='empty'; }
                   1988:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
                   1989:     return 1;
1.399     raeburn  1990: }
                   1991: &register_handler("ls3", \&ls3_handler, 0, 1, 0);
1.280     matthew  1992: 
1.477     raeburn  1993: sub read_lonnet_global {
                   1994:     my ($cmd,$tail,$client) = @_;
                   1995:     my $userinput = "$cmd:$tail";
                   1996:     my $requested = &Apache::lonnet::thaw_unescape($tail);
                   1997:     my $result;
1.480     raeburn  1998:     my %packagevars = (
                   1999:                         spareid => \%Apache::lonnet::spareid,
                   2000:                         perlvar => \%Apache::lonnet::perlvar,
                   2001:                       );
                   2002:     my %limit_to = (
                   2003:                     perlvar => {
1.531     raeburn  2004:                                  lonOtherAuthen  => 1,
                   2005:                                  lonBalancer     => 1,
                   2006:                                  lonVersion      => 1,
                   2007:                                  lonAdmEMail     => 1,
                   2008:                                  lonSupportEMail => 1,  
                   2009:                                  lonSysEMail     => 1,
                   2010:                                  lonHostID       => 1,
                   2011:                                  lonRole         => 1,
                   2012:                                  lonDefDomain    => 1,
                   2013:                                  lonLoadLim      => 1,
                   2014:                                  lonUserLoadLim  => 1,
1.480     raeburn  2015:                                }
                   2016:                   );
1.477     raeburn  2017:     if (ref($requested) eq 'HASH') {
                   2018:         foreach my $what (keys(%{$requested})) {
                   2019:             my $response;
1.480     raeburn  2020:             my $items = {};
                   2021:             if (exists($packagevars{$what})) {
                   2022:                 if (ref($limit_to{$what}) eq 'HASH') {
                   2023:                     foreach my $varname (keys(%{$packagevars{$what}})) {
                   2024:                         if ($limit_to{$what}{$varname}) {
                   2025:                             $items->{$varname} = $packagevars{$what}{$varname};
                   2026:                         }
                   2027:                     }
                   2028:                 } else {
                   2029:                     $items = $packagevars{$what};
1.477     raeburn  2030:                 }
1.480     raeburn  2031:                 if ($what eq 'perlvar') {
                   2032:                     if (!exists($packagevars{$what}{'lonBalancer'})) {
                   2033:                         if ($dist =~ /^(centos|rhes|fedora|scientific)/) {
                   2034:                             my $othervarref=LONCAPA::Configuration::read_conf('httpd.conf');
                   2035:                             if (ref($othervarref) eq 'HASH') {
                   2036:                                 $items->{'lonBalancer'} = $othervarref->{'lonBalancer'};
                   2037:                             }
                   2038:                         }
                   2039:                     }
1.477     raeburn  2040:                 }
1.480     raeburn  2041:                 $response = &Apache::lonnet::freeze_escape($items);
1.477     raeburn  2042:             }
1.478     raeburn  2043:             $result .= &escape($what).'='.$response.'&';
1.477     raeburn  2044:         }
                   2045:     }
                   2046:     $result =~ s/\&$//;
                   2047:     &Reply($client,\$result,$userinput);
                   2048:     return 1;
                   2049: }
                   2050: &register_handler("readlonnetglobal", \&read_lonnet_global, 0, 1, 0);
                   2051: 
1.479     raeburn  2052: sub server_devalidatecache_handler {
                   2053:     my ($cmd,$tail,$client) = @_;
                   2054:     my $userinput = "$cmd:$tail";
1.503     raeburn  2055:     my $items = &unescape($tail);
                   2056:     my @cached = split(/\&/,$items);
                   2057:     foreach my $key (@cached) {
                   2058:         if ($key =~ /:/) {
                   2059:             my ($name,$id) = map { &unescape($_); } split(/:/,$key);
                   2060:             &Apache::lonnet::devalidate_cache_new($name,$id);
                   2061:         }
                   2062:     }
1.479     raeburn  2063:     my $result = 'ok';
                   2064:     &Reply($client,\$result,$userinput);
                   2065:     return 1;
                   2066: }
1.481     raeburn  2067: &register_handler("devalidatecache", \&server_devalidatecache_handler, 0, 1, 0);
1.479     raeburn  2068: 
1.410     raeburn  2069: sub server_timezone_handler {
                   2070:     my ($cmd,$tail,$client) = @_;
                   2071:     my $userinput = "$cmd:$tail";
                   2072:     my $timezone;
                   2073:     my $clockfile = '/etc/sysconfig/clock'; # Fedora/CentOS/SuSE
                   2074:     my $tzfile = '/etc/timezone'; # Debian/Ubuntu
                   2075:     if (-e $clockfile) {
                   2076:         if (open(my $fh,"<$clockfile")) {
                   2077:             while (<$fh>) {
                   2078:                 next if (/^[\#\s]/);
                   2079:                 if (/^(?:TIME)?ZONE\s*=\s*['"]?\s*([\w\/]+)/) {
                   2080:                     $timezone = $1;
                   2081:                     last;
                   2082:                 }
                   2083:             }
                   2084:             close($fh);
                   2085:         }
                   2086:     } elsif (-e $tzfile) {
                   2087:         if (open(my $fh,"<$tzfile")) {
                   2088:             $timezone = <$fh>;
                   2089:             close($fh);
                   2090:             chomp($timezone);
                   2091:             if ($timezone =~ m{^Etc/(\w+)$}) {
                   2092:                 $timezone = $1;
                   2093:             }
                   2094:         }
                   2095:     }
                   2096:     &Reply($client,\$timezone,$userinput); # This supports debug logging.
                   2097:     return 1;
                   2098: }
                   2099: &register_handler("servertimezone", \&server_timezone_handler, 0, 1, 0);
                   2100: 
1.413     raeburn  2101: sub server_loncaparev_handler {
                   2102:     my ($cmd,$tail,$client) = @_;
                   2103:     my $userinput = "$cmd:$tail";
                   2104:     &Reply($client,\$perlvar{'lonVersion'},$userinput);
                   2105:     return 1;
                   2106: }
                   2107: &register_handler("serverloncaparev", \&server_loncaparev_handler, 0, 1, 0);
                   2108: 
1.448     raeburn  2109: sub server_homeID_handler {
                   2110:     my ($cmd,$tail,$client) = @_;
                   2111:     my $userinput = "$cmd:$tail";
                   2112:     &Reply($client,\$perlvar{'lonHostID'},$userinput);
                   2113:     return 1;
                   2114: }
                   2115: &register_handler("serverhomeID", \&server_homeID_handler, 0, 1, 0);
                   2116: 
1.471     raeburn  2117: sub server_distarch_handler {
                   2118:     my ($cmd,$tail,$client) = @_;
                   2119:     my $userinput = "$cmd:$tail";
                   2120:     my $reply = &distro_and_arch();
                   2121:     &Reply($client,\$reply,$userinput);
                   2122:     return 1;
                   2123: }
                   2124: &register_handler("serverdistarch", \&server_distarch_handler, 0, 1, 0);
                   2125: 
1.523     raeburn  2126: sub server_certs_handler {
                   2127:     my ($cmd,$tail,$client) = @_;
                   2128:     my $userinput = "$cmd:$tail";
1.548     raeburn  2129:     my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
                   2130:     my $result = &LONCAPA::Lond::server_certs(\%perlvar,$perlvar{'lonHostID'},$hostname);
1.523     raeburn  2131:     &Reply($client,\$result,$userinput);
                   2132:     return;
                   2133: }
                   2134: &register_handler("servercerts", \&server_certs_handler, 0, 1, 0);
                   2135: 
1.218     foxr     2136: #   Process a reinit request.  Reinit requests that either
                   2137: #   lonc or lond be reinitialized so that an updated 
                   2138: #   host.tab or domain.tab can be processed.
                   2139: #
                   2140: # Parameters:
                   2141: #      $cmd    - the actual keyword that invoked us.
                   2142: #      $tail   - the tail of the request that invoked us.
                   2143: #      $client - File descriptor connected to the client
                   2144: #  Returns:
                   2145: #      1       - Ok to continue processing.
                   2146: #      0       - Program should exit
                   2147: #  Implicit output:
                   2148: #     a reply is sent to the client.
                   2149: #
                   2150: sub reinit_process_handler {
                   2151:     my ($cmd, $tail, $client) = @_;
                   2152:    
                   2153:     my $userinput = "$cmd:$tail";
                   2154:    
                   2155:     my $cert = &GetCertificate($userinput);
                   2156:     if(&ValidManager($cert)) {
                   2157: 	chomp($userinput);
                   2158: 	my $reply = &ReinitProcess($userinput);
1.387     albertel 2159: 	&Reply( $client,  \$reply, $userinput);
1.218     foxr     2160:     } else {
                   2161: 	&Failure( $client, "refused\n", $userinput);
                   2162:     }
                   2163:     return 1;
                   2164: }
                   2165: &register_handler("reinit", \&reinit_process_handler, 1, 0, 1);
                   2166: 
                   2167: #  Process the editing script for a table edit operation.
                   2168: #  the editing operation must be encrypted and requested by
                   2169: #  a manager host.
                   2170: #
                   2171: # Parameters:
                   2172: #      $cmd    - the actual keyword that invoked us.
                   2173: #      $tail   - the tail of the request that invoked us.
                   2174: #      $client - File descriptor connected to the client
                   2175: #  Returns:
                   2176: #      1       - Ok to continue processing.
                   2177: #      0       - Program should exit
                   2178: #  Implicit output:
                   2179: #     a reply is sent to the client.
                   2180: #
                   2181: sub edit_table_handler {
                   2182:     my ($command, $tail, $client) = @_;
                   2183:    
                   2184:     my $userinput = "$command:$tail";
                   2185: 
                   2186:     my $cert = &GetCertificate($userinput);
                   2187:     if(&ValidManager($cert)) {
                   2188: 	my($filetype, $script) = split(/:/, $tail);
                   2189: 	if (($filetype eq "hosts") || 
                   2190: 	    ($filetype eq "domain")) {
                   2191: 	    if($script ne "") {
                   2192: 		&Reply($client,              # BUGBUG - EditFile
                   2193: 		      &EditFile($userinput), #   could fail.
                   2194: 		      $userinput);
                   2195: 	    } else {
                   2196: 		&Failure($client,"refused\n",$userinput);
                   2197: 	    }
                   2198: 	} else {
                   2199: 	    &Failure($client,"refused\n",$userinput);
                   2200: 	}
                   2201:     } else {
                   2202: 	&Failure($client,"refused\n",$userinput);
                   2203:     }
                   2204:     return 1;
                   2205: }
1.263     albertel 2206: &register_handler("edit", \&edit_table_handler, 1, 0, 1);
1.218     foxr     2207: 
1.220     foxr     2208: #
                   2209: #   Authenticate a user against the LonCAPA authentication
                   2210: #   database.  Note that there are several authentication
                   2211: #   possibilities:
                   2212: #   - unix     - The user can be authenticated against the unix
                   2213: #                password file.
                   2214: #   - internal - The user can be authenticated against a purely 
                   2215: #                internal per user password file.
                   2216: #   - kerberos - The user can be authenticated against either a kerb4 or kerb5
                   2217: #                ticket granting authority.
                   2218: #   - user     - The person tailoring LonCAPA can supply a user authentication
                   2219: #                mechanism that is per system.
                   2220: #
                   2221: # Parameters:
                   2222: #    $cmd      - The command that got us here.
                   2223: #    $tail     - Tail of the command (remaining parameters).
                   2224: #    $client   - File descriptor connected to client.
                   2225: # Returns
                   2226: #     0        - Requested to exit, caller should shut down.
                   2227: #     1        - Continue processing.
                   2228: # Implicit inputs:
                   2229: #    The authentication systems describe above have their own forms of implicit
                   2230: #    input into the authentication process that are described above.
                   2231: #
                   2232: sub authenticate_handler {
                   2233:     my ($cmd, $tail, $client) = @_;
                   2234: 
                   2235:     
                   2236:     #  Regenerate the full input line 
                   2237:     
                   2238:     my $userinput  = $cmd.":".$tail;
                   2239:     
                   2240:     #  udom    - User's domain.
                   2241:     #  uname   - Username.
                   2242:     #  upass   - User's password.
1.396     raeburn  2243:     #  checkdefauth - Pass to validate_user() to try authentication
                   2244:     #                 with default auth type(s) if no user account.
1.447     raeburn  2245:     #  clientcancheckhost - Passed by clients with functionality in lonauth.pm
                   2246:     #                       to check if session can be hosted.
1.220     foxr     2247:     
1.447     raeburn  2248:     my ($udom, $uname, $upass, $checkdefauth, $clientcancheckhost)=split(/:/,$tail);
1.399     raeburn  2249:     &Debug(" Authenticate domain = $udom, user = $uname, password = $upass,  checkdefauth = $checkdefauth");
1.220     foxr     2250:     chomp($upass);
                   2251:     $upass=&unescape($upass);
                   2252: 
1.396     raeburn  2253:     my $pwdcorrect = &validate_user($udom,$uname,$upass,$checkdefauth);
1.220     foxr     2254:     if($pwdcorrect) {
1.447     raeburn  2255:         my $canhost = 1;
                   2256:         unless ($clientcancheckhost) {
1.448     raeburn  2257:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   2258:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.452     raeburn  2259:             my @intdoms;
                   2260:             my $internet_names = &Apache::lonnet::get_internet_names($clientname);
                   2261:             if (ref($internet_names) eq 'ARRAY') {
                   2262:                 @intdoms = @{$internet_names};
                   2263:             }
1.448     raeburn  2264:             unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
1.447     raeburn  2265:                 my ($remote,$hosted);
                   2266:                 my $remotesession = &get_usersession_config($udom,'remotesession');
                   2267:                 if (ref($remotesession) eq 'HASH') {
1.525     raeburn  2268:                     $remote = $remotesession->{'remote'};
1.447     raeburn  2269:                 }
1.448     raeburn  2270:                 my $hostedsession = &get_usersession_config($clienthomedom,'hostedsession');
1.447     raeburn  2271:                 if (ref($hostedsession) eq 'HASH') {
                   2272:                     $hosted = $hostedsession->{'hosted'};
                   2273:                 }
1.448     raeburn  2274:                 $canhost = &Apache::lonnet::can_host_session($udom,$clientname,
1.492     droeschl 2275:                                                              $clientversion,
1.447     raeburn  2276:                                                              $remote,$hosted);
                   2277:             }
                   2278:         }
                   2279:         if ($canhost) {               
                   2280:             &Reply( $client, "authorized\n", $userinput);
                   2281:         } else {
                   2282:             &Reply( $client, "not_allowed_to_host\n", $userinput);
                   2283:         }
1.220     foxr     2284: 	#
                   2285: 	#  Bad credentials: Failed to authorize
                   2286: 	#
                   2287:     } else {
                   2288: 	&Failure( $client, "non_authorized\n", $userinput);
                   2289:     }
                   2290: 
                   2291:     return 1;
                   2292: }
1.263     albertel 2293: &register_handler("auth", \&authenticate_handler, 1, 1, 0);
1.214     foxr     2294: 
1.222     foxr     2295: #
                   2296: #   Change a user's password.  Note that this function is complicated by
                   2297: #   the fact that a user may be authenticated in more than one way:
                   2298: #   At present, we are not able to change the password for all types of
                   2299: #   authentication methods.  Only for:
                   2300: #      unix    - unix password or shadow passoword style authentication.
                   2301: #      local   - Locally written authentication mechanism.
                   2302: #   For now, kerb4 and kerb5 password changes are not supported and result
                   2303: #   in an error.
                   2304: # FUTURE WORK:
                   2305: #    Support kerberos passwd changes?
                   2306: # Parameters:
                   2307: #    $cmd      - The command that got us here.
                   2308: #    $tail     - Tail of the command (remaining parameters).
                   2309: #    $client   - File descriptor connected to client.
                   2310: # Returns
                   2311: #     0        - Requested to exit, caller should shut down.
                   2312: #     1        - Continue processing.
                   2313: # Implicit inputs:
                   2314: #    The authentication systems describe above have their own forms of implicit
                   2315: #    input into the authentication process that are described above.
                   2316: sub change_password_handler {
                   2317:     my ($cmd, $tail, $client) = @_;
                   2318: 
                   2319:     my $userinput = $cmd.":".$tail;           # Reconstruct client's string.
                   2320: 
                   2321:     #
                   2322:     #  udom  - user's domain.
                   2323:     #  uname - Username.
                   2324:     #  upass - Current password.
                   2325:     #  npass - New password.
1.346     raeburn  2326:     #  context - Context in which this was called 
                   2327:     #            (preferences or reset_by_email).
1.428     raeburn  2328:     #  lonhost - HostID of server where request originated 
1.222     foxr     2329:    
1.428     raeburn  2330:     my ($udom,$uname,$upass,$npass,$context,$lonhost)=split(/:/,$tail);
1.222     foxr     2331: 
                   2332:     $upass=&unescape($upass);
                   2333:     $npass=&unescape($npass);
                   2334:     &Debug("Trying to change password for $uname");
                   2335: 
                   2336:     # First require that the user can be authenticated with their
1.346     raeburn  2337:     # old password unless context was 'reset_by_email':
                   2338:     
1.428     raeburn  2339:     my ($validated,$failure);
1.346     raeburn  2340:     if ($context eq 'reset_by_email') {
1.428     raeburn  2341:         if ($lonhost eq '') {
                   2342:             $failure = 'invalid_client';
                   2343:         } else {
                   2344:             $validated = 1;
                   2345:         }
1.346     raeburn  2346:     } else {
                   2347:         $validated = &validate_user($udom, $uname, $upass);
                   2348:     }
1.222     foxr     2349:     if($validated) {
                   2350: 	my $realpasswd  = &get_auth_type($udom, $uname); # Defined since authd.
                   2351: 	
                   2352: 	my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
                   2353: 	if ($howpwd eq 'internal') {
                   2354: 	    &Debug("internal auth");
1.518     raeburn  2355:             my $ncpass = &hash_passwd($udom,$npass);
1.222     foxr     2356: 	    if(&rewrite_password_file($udom, $uname, "internal:$ncpass")) {
1.428     raeburn  2357: 		my $msg="Result of password change for $uname: pwchange_success";
                   2358:                 if ($lonhost) {
                   2359:                     $msg .= " - request originated from: $lonhost";
                   2360:                 }
                   2361:                 &logthis($msg);
1.518     raeburn  2362:                 &update_passwd_history($uname,$udom,$howpwd,$context);
1.222     foxr     2363: 		&Reply($client, "ok\n", $userinput);
                   2364: 	    } else {
                   2365: 		&logthis("Unable to open $uname passwd "               
                   2366: 			 ."to change password");
                   2367: 		&Failure( $client, "non_authorized\n",$userinput);
                   2368: 	    }
1.346     raeburn  2369: 	} elsif ($howpwd eq 'unix' && $context ne 'reset_by_email') {
1.287     foxr     2370: 	    my $result = &change_unix_password($uname, $npass);
1.518     raeburn  2371:             if ($result eq 'ok') {
                   2372:                 &update_passwd_history($uname,$udom,$howpwd,$context);
                   2373:              }
1.222     foxr     2374: 	    &logthis("Result of password change for $uname: ".
1.287     foxr     2375: 		     $result);
1.387     albertel 2376: 	    &Reply($client, \$result, $userinput);
1.222     foxr     2377: 	} else {
                   2378: 	    # this just means that the current password mode is not
                   2379: 	    # one we know how to change (e.g the kerberos auth modes or
                   2380: 	    # locally written auth handler).
                   2381: 	    #
                   2382: 	    &Failure( $client, "auth_mode_error\n", $userinput);
                   2383: 	}  
                   2384: 	
1.224     foxr     2385:     } else {
1.428     raeburn  2386: 	if ($failure eq '') {
                   2387: 	    $failure = 'non_authorized';
                   2388: 	}
                   2389: 	&Failure( $client, "$failure\n", $userinput);
1.222     foxr     2390:     }
                   2391: 
                   2392:     return 1;
                   2393: }
1.263     albertel 2394: &register_handler("passwd", \&change_password_handler, 1, 1, 0);
1.222     foxr     2395: 
1.518     raeburn  2396: sub hash_passwd {
                   2397:     my ($domain,$plainpass,@rest) = @_;
                   2398:     my ($salt,$cost);
                   2399:     if (@rest) {
                   2400:         $cost = $rest[0];
                   2401:         # salt is first 22 characters, base-64 encoded by bcrypt
                   2402:         my $plainsalt = substr($rest[1],0,22);
                   2403:         $salt = Crypt::Eksblowfish::Bcrypt::de_base64($plainsalt);
                   2404:     } else {
1.533     raeburn  2405:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   2406:         my $defaultcost = $domdefaults{'intauth_cost'};
1.518     raeburn  2407:         if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
                   2408:             $cost = 10;
                   2409:         } else {
                   2410:             $cost = $defaultcost;
                   2411:         }
                   2412:         # Generate random 16-octet base64 salt
                   2413:         $salt = "";
                   2414:         $salt .= pack("C", int rand(256)) for 1..16;
                   2415:     }
                   2416:     my $hash = &Crypt::Eksblowfish::Bcrypt::bcrypt_hash({
                   2417:         key_nul => 1,
                   2418:         cost    => $cost,
                   2419:         salt    => $salt,
                   2420:     }, Digest::SHA::sha512(Encode::encode('UTF-8',$plainpass)));
                   2421: 
                   2422:     my $result = join("!", "", "bcrypt", sprintf("%02d",$cost),
                   2423:                 &Crypt::Eksblowfish::Bcrypt::en_base64($salt).
                   2424:                 &Crypt::Eksblowfish::Bcrypt::en_base64($hash));
                   2425:     return $result;
                   2426: }
                   2427: 
1.225     foxr     2428: #
                   2429: #   Create a new user.  User in this case means a lon-capa user.
                   2430: #   The user must either already exist in some authentication realm
                   2431: #   like kerberos or the /etc/passwd.  If not, a user completely local to
                   2432: #   this loncapa system is created.
                   2433: #
                   2434: # Parameters:
                   2435: #    $cmd      - The command that got us here.
                   2436: #    $tail     - Tail of the command (remaining parameters).
                   2437: #    $client   - File descriptor connected to client.
                   2438: # Returns
                   2439: #     0        - Requested to exit, caller should shut down.
                   2440: #     1        - Continue processing.
                   2441: # Implicit inputs:
                   2442: #    The authentication systems describe above have their own forms of implicit
                   2443: #    input into the authentication process that are described above.
                   2444: sub add_user_handler {
                   2445: 
                   2446:     my ($cmd, $tail, $client) = @_;
                   2447: 
                   2448: 
                   2449:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   2450:     my $userinput = $cmd.":".$tail; # Reconstruct the full request line.
                   2451: 
                   2452:     &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
                   2453: 
                   2454: 
                   2455:     if($udom eq $currentdomainid) { # Reject new users for other domains...
                   2456: 	
                   2457: 	my $oldumask=umask(0077);
                   2458: 	chomp($npass);
                   2459: 	$npass=&unescape($npass);
                   2460: 	my $passfilename  = &password_path($udom, $uname);
                   2461: 	&Debug("Password file created will be:".$passfilename);
                   2462: 	if (-e $passfilename) {
                   2463: 	    &Failure( $client, "already_exists\n", $userinput);
                   2464: 	} else {
                   2465: 	    my $fperror='';
1.264     albertel 2466: 	    if (!&mkpath($passfilename)) {
                   2467: 		$fperror="error: ".($!+0)." mkdir failed while attempting "
                   2468: 		    ."makeuser";
1.225     foxr     2469: 	    }
                   2470: 	    unless ($fperror) {
1.518     raeburn  2471: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
                   2472:                                              $passfilename,'makeuser');
1.390     raeburn  2473: 		&Reply($client,\$result, $userinput);     #BUGBUG - could be fail
1.225     foxr     2474: 	    } else {
1.387     albertel 2475: 		&Failure($client, \$fperror, $userinput);
1.225     foxr     2476: 	    }
                   2477: 	}
                   2478: 	umask($oldumask);
                   2479:     }  else {
                   2480: 	&Failure($client, "not_right_domain\n",
                   2481: 		$userinput);	# Even if we are multihomed.
                   2482:     
                   2483:     }
                   2484:     return 1;
                   2485: 
                   2486: }
                   2487: &register_handler("makeuser", \&add_user_handler, 1, 1, 0);
                   2488: 
                   2489: #
                   2490: #   Change the authentication method of a user.  Note that this may
                   2491: #   also implicitly change the user's password if, for example, the user is
                   2492: #   joining an existing authentication realm.  Known authentication realms at
                   2493: #   this time are:
                   2494: #    internal   - Purely internal password file (only loncapa knows this user)
                   2495: #    local      - Institutionally written authentication module.
                   2496: #    unix       - Unix user (/etc/passwd with or without /etc/shadow).
                   2497: #    kerb4      - kerberos version 4
                   2498: #    kerb5      - kerberos version 5
                   2499: #
                   2500: # Parameters:
                   2501: #    $cmd      - The command that got us here.
                   2502: #    $tail     - Tail of the command (remaining parameters).
                   2503: #    $client   - File descriptor connected to client.
                   2504: # Returns
                   2505: #     0        - Requested to exit, caller should shut down.
                   2506: #     1        - Continue processing.
                   2507: # Implicit inputs:
                   2508: #    The authentication systems describe above have their own forms of implicit
                   2509: #    input into the authentication process that are described above.
1.287     foxr     2510: # NOTE:
                   2511: #   This is also used to change the authentication credential values (e.g. passwd).
                   2512: #   
1.225     foxr     2513: #
                   2514: sub change_authentication_handler {
                   2515: 
                   2516:     my ($cmd, $tail, $client) = @_;
                   2517:    
                   2518:     my $userinput  = "$cmd:$tail";              # Reconstruct user input.
                   2519: 
                   2520:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   2521:     &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
                   2522:     if ($udom ne $currentdomainid) {
                   2523: 	&Failure( $client, "not_right_domain\n", $client);
                   2524:     } else {
                   2525: 	
                   2526: 	chomp($npass);
                   2527: 	
                   2528: 	$npass=&unescape($npass);
1.261     foxr     2529: 	my $oldauth = &get_auth_type($udom, $uname); # Get old auth info.
1.225     foxr     2530: 	my $passfilename = &password_path($udom, $uname);
                   2531: 	if ($passfilename) {	# Not allowed to create a new user!!
1.287     foxr     2532: 	    # If just changing the unix passwd. need to arrange to run
1.502     raeburn  2533: 	    # passwd since otherwise make_passwd_file will fail as 
                   2534: 	    # creation of unix authenticated users is no longer supported
                   2535:             # except from the command line, when running make_domain_coordinator.pl
1.287     foxr     2536: 
                   2537: 	    if(($oldauth =~/^unix/) && ($umode eq "unix")) {
                   2538: 		my $result = &change_unix_password($uname, $npass);
                   2539: 		&logthis("Result of password change for $uname: ".$result);
                   2540: 		if ($result eq "ok") {
1.518     raeburn  2541:                     &update_passwd_history($uname,$udom,$umode,'changeuserauth'); 
1.390     raeburn  2542: 		    &Reply($client, \$result);
1.288     albertel 2543: 		} else {
1.387     albertel 2544: 		    &Failure($client, \$result);
1.287     foxr     2545: 		}
1.288     albertel 2546: 	    } else {
1.518     raeburn  2547: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
                   2548:                                              $passfilename,'changeuserauth');
1.287     foxr     2549: 		#
                   2550: 		#  If the current auth mode is internal, and the old auth mode was
                   2551: 		#  unix, or krb*,  and the user is an author for this domain,
                   2552: 		#  re-run manage_permissions for that role in order to be able
                   2553: 		#  to take ownership of the construction space back to www:www
                   2554: 		#
1.502     raeburn  2555: 
                   2556: 
1.387     albertel 2557: 		&Reply($client, \$result, $userinput);
1.261     foxr     2558: 	    }
                   2559: 	       
                   2560: 
1.225     foxr     2561: 	} else {	       
1.251     foxr     2562: 	    &Failure($client, "non_authorized\n", $userinput); # Fail the user now.
1.225     foxr     2563: 	}
                   2564:     }
                   2565:     return 1;
                   2566: }
                   2567: &register_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
                   2568: 
1.518     raeburn  2569: sub update_passwd_history {
                   2570:     my ($uname,$udom,$umode,$context) = @_;
                   2571:     my $proname=&propath($udom,$uname);
                   2572:     my $now = time;
                   2573:     if (open(my $fh,">>$proname/passwd.log")) {
                   2574:         print $fh "$now:$umode:$context\n";
                   2575:         close($fh);
                   2576:     }
                   2577:     return;
                   2578: }
                   2579: 
1.225     foxr     2580: #
                   2581: #   Determines if this is the home server for a user.  The home server
                   2582: #   for a user will have his/her lon-capa passwd file.  Therefore all we need
                   2583: #   to do is determine if this file exists.
                   2584: #
                   2585: # Parameters:
                   2586: #    $cmd      - The command that got us here.
                   2587: #    $tail     - Tail of the command (remaining parameters).
                   2588: #    $client   - File descriptor connected to client.
                   2589: # Returns
                   2590: #     0        - Requested to exit, caller should shut down.
                   2591: #     1        - Continue processing.
                   2592: # Implicit inputs:
                   2593: #    The authentication systems describe above have their own forms of implicit
                   2594: #    input into the authentication process that are described above.
                   2595: #
                   2596: sub is_home_handler {
                   2597:     my ($cmd, $tail, $client) = @_;
                   2598:    
                   2599:     my $userinput  = "$cmd:$tail";
                   2600:    
                   2601:     my ($udom,$uname)=split(/:/,$tail);
                   2602:     chomp($uname);
                   2603:     my $passfile = &password_filename($udom, $uname);
                   2604:     if($passfile) {
                   2605: 	&Reply( $client, "found\n", $userinput);
                   2606:     } else {
                   2607: 	&Failure($client, "not_found\n", $userinput);
                   2608:     }
                   2609:     return 1;
                   2610: }
                   2611: &register_handler("home", \&is_home_handler, 0,1,0);
                   2612: 
                   2613: #
1.434     www      2614: #   Process an update request for a resource.
                   2615: #   A resource has been modified that we hold a subscription to.
1.225     foxr     2616: #   If the resource is not local, then we must update, or at least invalidate our
                   2617: #   cached copy of the resource. 
                   2618: # Parameters:
                   2619: #    $cmd      - The command that got us here.
                   2620: #    $tail     - Tail of the command (remaining parameters).
                   2621: #    $client   - File descriptor connected to client.
                   2622: # Returns
                   2623: #     0        - Requested to exit, caller should shut down.
                   2624: #     1        - Continue processing.
                   2625: # Implicit inputs:
                   2626: #    The authentication systems describe above have their own forms of implicit
                   2627: #    input into the authentication process that are described above.
                   2628: #
                   2629: sub update_resource_handler {
                   2630: 
                   2631:     my ($cmd, $tail, $client) = @_;
                   2632:    
                   2633:     my $userinput = "$cmd:$tail";
                   2634:    
                   2635:     my $fname= $tail;		# This allows interactive testing
                   2636: 
                   2637: 
                   2638:     my $ownership=ishome($fname);
                   2639:     if ($ownership eq 'not_owner') {
                   2640: 	if (-e $fname) {
1.434     www      2641:             # Delete preview file, if exists
                   2642:             unlink("$fname.tmp");
                   2643:             # Get usage stats
1.225     foxr     2644: 	    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
                   2645: 		$atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
                   2646: 	    my $now=time;
                   2647: 	    my $since=$now-$atime;
1.434     www      2648:             # If the file has not been used within lonExpire seconds,
                   2649:             # unsubscribe from it and delete local copy
1.225     foxr     2650: 	    if ($since>$perlvar{'lonExpire'}) {
1.365     albertel 2651: 		my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
1.308     albertel 2652: 		&devalidate_meta_cache($fname);
1.225     foxr     2653: 		unlink("$fname");
1.334     albertel 2654: 		unlink("$fname.meta");
1.225     foxr     2655: 	    } else {
1.434     www      2656:             # Yes, this is in active use. Get a fresh copy. Since it might be in
                   2657:             # very active use and huge (like a movie), copy it to "in.transfer" filename first.
1.225     foxr     2658: 		my $transname="$fname.in.transfer";
1.365     albertel 2659: 		my $remoteurl=&Apache::lonnet::reply("sub:$fname","$clientname");
1.225     foxr     2660: 		my $response;
1.537     raeburn  2661: # FIXME: cannot replicate files that take more than two minutes to transfer -- needs checking now 1200s timeout used
                   2662: # for LWP request.
                   2663: 		my $request=new HTTP::Request('GET',"$remoteurl");
                   2664:                 $response=&LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,0,1);
1.225     foxr     2665: 		if ($response->is_error()) {
1.541     raeburn  2666:                     my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
                   2667:                     &devalidate_meta_cache($fname);
                   2668:                     if (-e $transname) {
                   2669:                         unlink($transname);
                   2670:                     }
                   2671:                     unlink($fname);
1.225     foxr     2672: 		    my $message=$response->status_line;
                   2673: 		    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   2674: 		} else {
                   2675: 		    if ($remoteurl!~/\.meta$/) {
1.537     raeburn  2676: 			my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2677:                         my $mresponse = &LONCAPA::LWPReq::makerequest($clientname,$mrequest,$fname.'.meta',\%perlvar,120,0,1);
                   2678: 			if ($mresponse->is_error()) {
                   2679: 			    unlink($fname.'.meta');
1.225     foxr     2680: 			}
                   2681: 		    }
1.434     www      2682:                     # we successfully transfered, copy file over to real name
1.225     foxr     2683: 		    rename($transname,$fname);
1.308     albertel 2684: 		    &devalidate_meta_cache($fname);
1.225     foxr     2685: 		}
                   2686: 	    }
                   2687: 	    &Reply( $client, "ok\n", $userinput);
                   2688: 	} else {
                   2689: 	    &Failure($client, "not_found\n", $userinput);
                   2690: 	}
                   2691:     } else {
                   2692: 	&Failure($client, "rejected\n", $userinput);
                   2693:     }
                   2694:     return 1;
                   2695: }
                   2696: &register_handler("update", \&update_resource_handler, 0 ,1, 0);
                   2697: 
1.308     albertel 2698: sub devalidate_meta_cache {
                   2699:     my ($url) = @_;
                   2700:     use Cache::Memcached;
                   2701:     my $memcache = new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.365     albertel 2702:     $url = &Apache::lonnet::declutter($url);
1.308     albertel 2703:     $url =~ s-\.meta$--;
                   2704:     my $id = &escape('meta:'.$url);
                   2705:     $memcache->delete($id);
                   2706: }
                   2707: 
1.225     foxr     2708: #
1.226     foxr     2709: #   Fetch a user file from a remote server to the user's home directory
                   2710: #   userfiles subdir.
1.225     foxr     2711: # Parameters:
                   2712: #    $cmd      - The command that got us here.
                   2713: #    $tail     - Tail of the command (remaining parameters).
                   2714: #    $client   - File descriptor connected to client.
                   2715: # Returns
                   2716: #     0        - Requested to exit, caller should shut down.
                   2717: #     1        - Continue processing.
                   2718: #
                   2719: sub fetch_user_file_handler {
                   2720: 
                   2721:     my ($cmd, $tail, $client) = @_;
                   2722: 
                   2723:     my $userinput = "$cmd:$tail";
                   2724:     my $fname           = $tail;
1.232     foxr     2725:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
1.225     foxr     2726:     my $udir=&propath($udom,$uname).'/userfiles';
                   2727:     unless (-e $udir) {
                   2728: 	mkdir($udir,0770); 
                   2729:     }
1.232     foxr     2730:     Debug("fetch user file for $fname");
1.225     foxr     2731:     if (-e $udir) {
                   2732: 	$ufile=~s/^[\.\~]+//;
1.232     foxr     2733: 
                   2734: 	# IF necessary, create the path right down to the file.
                   2735: 	# Note that any regular files in the way of this path are
                   2736: 	# wiped out to deal with some earlier folly of mine.
                   2737: 
1.267     raeburn  2738: 	if (!&mkpath($udir.'/'.$ufile)) {
1.264     albertel 2739: 	    &Failure($client, "unable_to_create\n", $userinput);	    
1.232     foxr     2740: 	}
                   2741: 
1.225     foxr     2742: 	my $destname=$udir.'/'.$ufile;
                   2743: 	my $transname=$udir.'/'.$ufile.'.in.transit';
1.476     raeburn  2744:         my $clientprotocol=$Apache::lonnet::protocol{$clientname};
                   2745:         $clientprotocol = 'http' if ($clientprotocol ne 'https');
1.486     raeburn  2746: 	my $clienthost = &Apache::lonnet::hostname($clientname);
                   2747: 	my $remoteurl=$clientprotocol.'://'.$clienthost.'/userfiles/'.$fname;
1.225     foxr     2748: 	my $response;
1.232     foxr     2749: 	Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
1.537     raeburn  2750: 	my $request=new HTTP::Request('GET',"$remoteurl");
                   2751:         my $verifycert = 1;
                   2752:         my @machine_ids = &Apache::lonnet::current_machine_ids();
                   2753:         if (grep(/^\Q$clientname\E$/,@machine_ids)) {
                   2754:             $verifycert = 0;
                   2755:         }
                   2756:         $response = &LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,$verifycert);
1.225     foxr     2757: 	if ($response->is_error()) {
                   2758: 	    unlink($transname);
                   2759: 	    my $message=$response->status_line;
                   2760: 	    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   2761: 	    &Failure($client, "failed\n", $userinput);
                   2762: 	} else {
1.232     foxr     2763: 	    Debug("Renaming $transname to $destname");
1.225     foxr     2764: 	    if (!rename($transname,$destname)) {
                   2765: 		&logthis("Unable to move $transname to $destname");
                   2766: 		unlink($transname);
                   2767: 		&Failure($client, "failed\n", $userinput);
                   2768: 	    } else {
1.495     raeburn  2769:                 if ($fname =~ /^default.+\.(page|sequence)$/) {
                   2770:                     my ($major,$minor) = split(/\./,$clientversion);
                   2771:                     if (($major < 2) || ($major == 2 && $minor < 11)) {
                   2772:                         my $now = time;
                   2773:                         &Apache::lonnet::do_cache_new('crschange',$udom.'_'.$uname,$now,600);
                   2774:                         my $key = &escape('internal.contentchange');
                   2775:                         my $what = "$key=$now";
                   2776:                         my $hashref = &tie_user_hash($udom,$uname,'environment',
                   2777:                                                      &GDBM_WRCREAT(),"P",$what);
                   2778:                         if ($hashref) {
                   2779:                             $hashref->{$key}=$now;
                   2780:                             if (!&untie_user_hash($hashref)) {
                   2781:                                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
                   2782:                                          "when updating internal.contentchange");
                   2783:                             }
                   2784:                         }
                   2785:                     }
                   2786:                 }
1.225     foxr     2787: 		&Reply($client, "ok\n", $userinput);
                   2788: 	    }
                   2789: 	}   
                   2790:     } else {
                   2791: 	&Failure($client, "not_home\n", $userinput);
                   2792:     }
                   2793:     return 1;
                   2794: }
                   2795: &register_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
                   2796: 
1.226     foxr     2797: #
                   2798: #   Remove a file from a user's home directory userfiles subdirectory.
                   2799: # Parameters:
                   2800: #    cmd   - the Lond request keyword that got us here.
                   2801: #    tail  - the part of the command past the keyword.
                   2802: #    client- File descriptor connected with the client.
                   2803: #
                   2804: # Returns:
                   2805: #    1    - Continue processing.
                   2806: sub remove_user_file_handler {
                   2807:     my ($cmd, $tail, $client) = @_;
                   2808: 
                   2809:     my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2810: 
                   2811:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2812:     if ($ufile =~m|/\.\./|) {
                   2813: 	# any files paths with /../ in them refuse 
                   2814: 	# to deal with
                   2815: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2816:     } else {
                   2817: 	my $udir = &propath($udom,$uname);
                   2818: 	if (-e $udir) {
                   2819: 	    my $file=$udir.'/userfiles/'.$ufile;
                   2820: 	    if (-e $file) {
1.253     foxr     2821: 		#
                   2822: 		#   If the file is a regular file unlink is fine...
1.520     raeburn  2823: 		#   However it's possible the client wants a dir 
                   2824: 		#   removed, in which case rmdir is more appropriate.
                   2825: 		#   Note: rmdir will only remove an empty directory.
1.253     foxr     2826: 		#
1.240     banghart 2827: 	        if (-f $file){
1.241     albertel 2828: 		    unlink($file);
1.520     raeburn  2829:                     # for html files remove the associated .bak file 
                   2830:                     # which may have been created by the editor.
                   2831:                     if ($ufile =~ m{^((docs|supplemental)/(?:\d+|default)/\d+(?:|/.+)/)[^/]+\.x?html?$}i) {
                   2832:                         my $path = $1;
                   2833:                         if (-e $file.'.bak') {
                   2834:                             unlink($file.'.bak');
                   2835:                         }
                   2836:                     }
1.241     albertel 2837: 		} elsif(-d $file) {
                   2838: 		    rmdir($file);
1.240     banghart 2839: 		}
1.226     foxr     2840: 		if (-e $file) {
1.253     foxr     2841: 		    #  File is still there after we deleted it ?!?
                   2842: 
1.226     foxr     2843: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2844: 		} else {
                   2845: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2846: 		}
                   2847: 	    } else {
                   2848: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2849: 	    }
                   2850: 	} else {
                   2851: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2852: 	}
                   2853:     }
                   2854:     return 1;
                   2855: }
                   2856: &register_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
                   2857: 
1.236     albertel 2858: #
                   2859: #   make a directory in a user's home directory userfiles subdirectory.
                   2860: # Parameters:
                   2861: #    cmd   - the Lond request keyword that got us here.
                   2862: #    tail  - the part of the command past the keyword.
                   2863: #    client- File descriptor connected with the client.
                   2864: #
                   2865: # Returns:
                   2866: #    1    - Continue processing.
                   2867: sub mkdir_user_file_handler {
                   2868:     my ($cmd, $tail, $client) = @_;
                   2869: 
                   2870:     my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2871:     $dir=&unescape($dir);
                   2872:     my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2873:     if ($ufile =~m|/\.\./|) {
                   2874: 	# any files paths with /../ in them refuse 
                   2875: 	# to deal with
                   2876: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2877:     } else {
                   2878: 	my $udir = &propath($udom,$uname);
                   2879: 	if (-e $udir) {
1.264     albertel 2880: 	    my $newdir=$udir.'/userfiles/'.$ufile.'/';
                   2881: 	    if (!&mkpath($newdir)) {
                   2882: 		&Failure($client, "failed\n", "$cmd:$tail");
1.236     albertel 2883: 	    }
1.264     albertel 2884: 	    &Reply($client, "ok\n", "$cmd:$tail");
1.236     albertel 2885: 	} else {
                   2886: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2887: 	}
                   2888:     }
                   2889:     return 1;
                   2890: }
                   2891: &register_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
                   2892: 
1.237     albertel 2893: #
                   2894: #   rename a file in a user's home directory userfiles subdirectory.
                   2895: # Parameters:
                   2896: #    cmd   - the Lond request keyword that got us here.
                   2897: #    tail  - the part of the command past the keyword.
                   2898: #    client- File descriptor connected with the client.
                   2899: #
                   2900: # Returns:
                   2901: #    1    - Continue processing.
                   2902: sub rename_user_file_handler {
                   2903:     my ($cmd, $tail, $client) = @_;
                   2904: 
                   2905:     my ($udom,$uname,$old,$new) = split(/:/, $tail);
                   2906:     $old=&unescape($old);
                   2907:     $new=&unescape($new);
                   2908:     if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
                   2909: 	# any files paths with /../ in them refuse to deal with
                   2910: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2911:     } else {
                   2912: 	my $udir = &propath($udom,$uname);
                   2913: 	if (-e $udir) {
                   2914: 	    my $oldfile=$udir.'/userfiles/'.$old;
                   2915: 	    my $newfile=$udir.'/userfiles/'.$new;
                   2916: 	    if (-e $newfile) {
                   2917: 		&Failure($client, "exists\n", "$cmd:$tail");
                   2918: 	    } elsif (! -e $oldfile) {
                   2919: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2920: 	    } else {
                   2921: 		if (!rename($oldfile,$newfile)) {
                   2922: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2923: 		} else {
                   2924: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2925: 		}
                   2926: 	    }
                   2927: 	} else {
                   2928: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2929: 	}
                   2930:     }
                   2931:     return 1;
                   2932: }
                   2933: &register_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
                   2934: 
1.227     foxr     2935: #
1.382     albertel 2936: #  Checks if the specified user has an active session on the server
                   2937: #  return ok if so, not_found if not
                   2938: #
                   2939: # Parameters:
                   2940: #   cmd      - The request keyword that dispatched to tus.
                   2941: #   tail     - The tail of the request (colon separated parameters).
                   2942: #   client   - Filehandle open on the client.
                   2943: # Return:
                   2944: #    1.
                   2945: sub user_has_session_handler {
                   2946:     my ($cmd, $tail, $client) = @_;
                   2947: 
                   2948:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
                   2949:     
                   2950:     opendir(DIR,$perlvar{'lonIDsDir'});
                   2951:     my $filename;
                   2952:     while ($filename=readdir(DIR)) {
                   2953: 	last if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/);
                   2954:     }
                   2955:     if ($filename) {
                   2956: 	&Reply($client, "ok\n", "$cmd:$tail");
                   2957:     } else {
                   2958: 	&Failure($client, "not_found\n", "$cmd:$tail");
                   2959:     }
                   2960:     return 1;
                   2961: 
                   2962: }
                   2963: &register_handler("userhassession", \&user_has_session_handler, 0,1,0);
                   2964: 
                   2965: #
1.263     albertel 2966: #  Authenticate access to a user file by checking that the token the user's 
                   2967: #  passed also exists in their session file
1.227     foxr     2968: #
                   2969: # Parameters:
                   2970: #   cmd      - The request keyword that dispatched to tus.
                   2971: #   tail     - The tail of the request (colon separated parameters).
                   2972: #   client   - Filehandle open on the client.
                   2973: # Return:
                   2974: #    1.
                   2975: sub token_auth_user_file_handler {
                   2976:     my ($cmd, $tail, $client) = @_;
                   2977: 
                   2978:     my ($fname, $session) = split(/:/, $tail);
                   2979:     
                   2980:     chomp($session);
1.393     raeburn  2981:     my $reply="non_auth";
1.343     albertel 2982:     my $file = $perlvar{'lonIDsDir'}.'/'.$session.'.id';
                   2983:     if (open(ENVIN,"$file")) {
1.332     albertel 2984: 	flock(ENVIN,LOCK_SH);
1.343     albertel 2985: 	tie(my %disk_env,'GDBM_File',"$file",&GDBM_READER(),0640);
                   2986: 	if (exists($disk_env{"userfile.$fname"})) {
1.393     raeburn  2987: 	    $reply="ok";
1.343     albertel 2988: 	} else {
                   2989: 	    foreach my $envname (keys(%disk_env)) {
                   2990: 		if ($envname=~ m|^userfile\.\Q$fname\E|) {
1.393     raeburn  2991: 		    $reply="ok";
1.343     albertel 2992: 		    last;
                   2993: 		}
                   2994: 	    }
1.227     foxr     2995: 	}
1.343     albertel 2996: 	untie(%disk_env);
1.227     foxr     2997: 	close(ENVIN);
1.387     albertel 2998: 	&Reply($client, \$reply, "$cmd:$tail");
1.227     foxr     2999:     } else {
                   3000: 	&Failure($client, "invalid_token\n", "$cmd:$tail");
                   3001:     }
                   3002:     return 1;
                   3003: 
                   3004: }
                   3005: &register_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
1.229     foxr     3006: 
                   3007: #
                   3008: #   Unsubscribe from a resource.
                   3009: #
                   3010: # Parameters:
                   3011: #    $cmd      - The command that got us here.
                   3012: #    $tail     - Tail of the command (remaining parameters).
                   3013: #    $client   - File descriptor connected to client.
                   3014: # Returns
                   3015: #     0        - Requested to exit, caller should shut down.
                   3016: #     1        - Continue processing.
                   3017: #
                   3018: sub unsubscribe_handler {
                   3019:     my ($cmd, $tail, $client) = @_;
                   3020: 
                   3021:     my $userinput= "$cmd:$tail";
                   3022:     
                   3023:     my ($fname) = split(/:/,$tail); # Split in case there's extrs.
                   3024: 
                   3025:     &Debug("Unsubscribing $fname");
                   3026:     if (-e $fname) {
                   3027: 	&Debug("Exists");
                   3028: 	&Reply($client, &unsub($fname,$clientip), $userinput);
                   3029:     } else {
                   3030: 	&Failure($client, "not_found\n", $userinput);
                   3031:     }
                   3032:     return 1;
                   3033: }
                   3034: &register_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
1.263     albertel 3035: 
1.230     foxr     3036: #   Subscribe to a resource
                   3037: #
                   3038: # Parameters:
                   3039: #    $cmd      - The command that got us here.
                   3040: #    $tail     - Tail of the command (remaining parameters).
                   3041: #    $client   - File descriptor connected to client.
                   3042: # Returns
                   3043: #     0        - Requested to exit, caller should shut down.
                   3044: #     1        - Continue processing.
                   3045: #
                   3046: sub subscribe_handler {
                   3047:     my ($cmd, $tail, $client)= @_;
                   3048: 
                   3049:     my $userinput  = "$cmd:$tail";
                   3050: 
                   3051:     &Reply( $client, &subscribe($userinput,$clientip), $userinput);
                   3052: 
                   3053:     return 1;
                   3054: }
                   3055: &register_handler("sub", \&subscribe_handler, 0, 1, 0);
                   3056: 
                   3057: #
1.379     albertel 3058: #   Determine the latest version of a resource (it looks for the highest
                   3059: #   past version and then returns that +1)
1.230     foxr     3060: #
                   3061: # Parameters:
                   3062: #    $cmd      - The command that got us here.
                   3063: #    $tail     - Tail of the command (remaining parameters).
1.379     albertel 3064: #                 (Should consist of an absolute path to a file)
1.230     foxr     3065: #    $client   - File descriptor connected to client.
                   3066: # Returns
                   3067: #     0        - Requested to exit, caller should shut down.
                   3068: #     1        - Continue processing.
                   3069: #
                   3070: sub current_version_handler {
                   3071:     my ($cmd, $tail, $client) = @_;
                   3072: 
                   3073:     my $userinput= "$cmd:$tail";
                   3074:    
                   3075:     my $fname   = $tail;
                   3076:     &Reply( $client, &currentversion($fname)."\n", $userinput);
                   3077:     return 1;
                   3078: 
                   3079: }
                   3080: &register_handler("currentversion", \&current_version_handler, 0, 1, 0);
                   3081: 
                   3082: #  Make an entry in a user's activity log.
                   3083: #
                   3084: # Parameters:
                   3085: #    $cmd      - The command that got us here.
                   3086: #    $tail     - Tail of the command (remaining parameters).
                   3087: #    $client   - File descriptor connected to client.
                   3088: # Returns
                   3089: #     0        - Requested to exit, caller should shut down.
                   3090: #     1        - Continue processing.
                   3091: #
                   3092: sub activity_log_handler {
                   3093:     my ($cmd, $tail, $client) = @_;
                   3094: 
                   3095: 
                   3096:     my $userinput= "$cmd:$tail";
                   3097: 
                   3098:     my ($udom,$uname,$what)=split(/:/,$tail);
                   3099:     chomp($what);
                   3100:     my $proname=&propath($udom,$uname);
                   3101:     my $now=time;
                   3102:     my $hfh;
                   3103:     if ($hfh=IO::File->new(">>$proname/activity.log")) { 
                   3104: 	print $hfh "$now:$clientname:$what\n";
                   3105: 	&Reply( $client, "ok\n", $userinput); 
                   3106:     } else {
                   3107: 	&Failure($client, "error: ".($!+0)." IO::File->new Failed "
                   3108: 		 ."while attempting log\n", 
                   3109: 		 $userinput);
                   3110:     }
                   3111: 
                   3112:     return 1;
                   3113: }
1.263     albertel 3114: &register_handler("log", \&activity_log_handler, 0, 1, 0);
1.230     foxr     3115: 
                   3116: #
                   3117: #   Put a namespace entry in a user profile hash.
                   3118: #   My druthers would be for this to be an encrypted interaction too.
                   3119: #   anything that might be an inadvertent covert channel about either
                   3120: #   user authentication or user personal information....
                   3121: #
                   3122: # Parameters:
                   3123: #    $cmd      - The command that got us here.
                   3124: #    $tail     - Tail of the command (remaining parameters).
                   3125: #    $client   - File descriptor connected to client.
                   3126: # Returns
                   3127: #     0        - Requested to exit, caller should shut down.
                   3128: #     1        - Continue processing.
                   3129: #
                   3130: sub put_user_profile_entry {
                   3131:     my ($cmd, $tail, $client)  = @_;
1.229     foxr     3132: 
1.230     foxr     3133:     my $userinput = "$cmd:$tail";
                   3134:     
1.242     raeburn  3135:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
1.230     foxr     3136:     if ($namespace ne 'roles') {
                   3137: 	chomp($what);
                   3138: 	my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3139: 				  &GDBM_WRCREAT(),"P",$what);
                   3140: 	if($hashref) {
                   3141: 	    my @pairs=split(/\&/,$what);
                   3142: 	    foreach my $pair (@pairs) {
                   3143: 		my ($key,$value)=split(/=/,$pair);
                   3144: 		$hashref->{$key}=$value;
                   3145: 	    }
1.311     albertel 3146: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     3147: 		&Reply( $client, "ok\n", $userinput);
                   3148: 	    } else {
                   3149: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3150: 			"while attempting put\n", 
                   3151: 			$userinput);
                   3152: 	    }
                   3153: 	} else {
1.316     albertel 3154: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.230     foxr     3155: 		     "while attempting put\n", $userinput);
                   3156: 	}
                   3157:     } else {
                   3158:         &Failure( $client, "refused\n", $userinput);
                   3159:     }
                   3160:     
                   3161:     return 1;
                   3162: }
                   3163: &register_handler("put", \&put_user_profile_entry, 0, 1, 0);
                   3164: 
1.283     albertel 3165: #   Put a piece of new data in hash, returns error if entry already exists
                   3166: # Parameters:
                   3167: #    $cmd      - The command that got us here.
                   3168: #    $tail     - Tail of the command (remaining parameters).
                   3169: #    $client   - File descriptor connected to client.
                   3170: # Returns
                   3171: #     0        - Requested to exit, caller should shut down.
                   3172: #     1        - Continue processing.
                   3173: #
                   3174: sub newput_user_profile_entry {
                   3175:     my ($cmd, $tail, $client)  = @_;
                   3176: 
                   3177:     my $userinput = "$cmd:$tail";
                   3178: 
                   3179:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
                   3180:     if ($namespace eq 'roles') {
                   3181:         &Failure( $client, "refused\n", $userinput);
                   3182: 	return 1;
                   3183:     }
                   3184: 
                   3185:     chomp($what);
                   3186: 
                   3187:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3188: 				 &GDBM_WRCREAT(),"N",$what);
                   3189:     if(!$hashref) {
1.316     albertel 3190: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.283     albertel 3191: 		  "while attempting put\n", $userinput);
                   3192: 	return 1;
                   3193:     }
                   3194: 
                   3195:     my @pairs=split(/\&/,$what);
                   3196:     foreach my $pair (@pairs) {
                   3197: 	my ($key,$value)=split(/=/,$pair);
                   3198: 	if (exists($hashref->{$key})) {
1.513     raeburn  3199:             if (!&untie_user_hash($hashref)) {
                   3200:                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
                   3201:                          "while attempting newput - early out as key exists");
                   3202:             }
                   3203:             &Failure($client, "key_exists: ".$key."\n",$userinput);
                   3204:             return 1;
1.283     albertel 3205: 	}
                   3206:     }
                   3207: 
                   3208:     foreach my $pair (@pairs) {
                   3209: 	my ($key,$value)=split(/=/,$pair);
                   3210: 	$hashref->{$key}=$value;
                   3211:     }
                   3212: 
1.311     albertel 3213:     if (&untie_user_hash($hashref)) {
1.283     albertel 3214: 	&Reply( $client, "ok\n", $userinput);
                   3215:     } else {
                   3216: 	&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3217: 		 "while attempting put\n", 
                   3218: 		 $userinput);
                   3219:     }
                   3220:     return 1;
                   3221: }
                   3222: &register_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
                   3223: 
1.230     foxr     3224: # 
                   3225: #   Increment a profile entry in the user history file.
                   3226: #   The history contains keyword value pairs.  In this case,
                   3227: #   The value itself is a pair of numbers.  The first, the current value
                   3228: #   the second an increment that this function applies to the current
                   3229: #   value.
                   3230: #
                   3231: # Parameters:
                   3232: #    $cmd      - The command that got us here.
                   3233: #    $tail     - Tail of the command (remaining parameters).
                   3234: #    $client   - File descriptor connected to client.
                   3235: # Returns
                   3236: #     0        - Requested to exit, caller should shut down.
                   3237: #     1        - Continue processing.
                   3238: #
                   3239: sub increment_user_value_handler {
                   3240:     my ($cmd, $tail, $client) = @_;
                   3241:     
                   3242:     my $userinput   = "$cmd:$tail";
                   3243:     
                   3244:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
                   3245:     if ($namespace ne 'roles') {
                   3246:         chomp($what);
                   3247: 	my $hashref = &tie_user_hash($udom, $uname,
                   3248: 				     $namespace, &GDBM_WRCREAT(),
                   3249: 				     "P",$what);
                   3250: 	if ($hashref) {
                   3251: 	    my @pairs=split(/\&/,$what);
                   3252: 	    foreach my $pair (@pairs) {
                   3253: 		my ($key,$value)=split(/=/,$pair);
1.284     raeburn  3254:                 $value = &unescape($value);
1.230     foxr     3255: 		# We could check that we have a number...
                   3256: 		if (! defined($value) || $value eq '') {
                   3257: 		    $value = 1;
                   3258: 		}
                   3259: 		$hashref->{$key}+=$value;
1.284     raeburn  3260:                 if ($namespace eq 'nohist_resourcetracker') {
                   3261:                     if ($hashref->{$key} < 0) {
                   3262:                         $hashref->{$key} = 0;
                   3263:                     }
                   3264:                 }
1.230     foxr     3265: 	    }
1.311     albertel 3266: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     3267: 		&Reply( $client, "ok\n", $userinput);
                   3268: 	    } else {
                   3269: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3270: 			 "while attempting inc\n", $userinput);
                   3271: 	    }
                   3272: 	} else {
                   3273: 	    &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3274: 		     "while attempting inc\n", $userinput);
                   3275: 	}
                   3276:     } else {
                   3277: 	&Failure($client, "refused\n", $userinput);
                   3278:     }
                   3279:     
                   3280:     return 1;
                   3281: }
                   3282: &register_handler("inc", \&increment_user_value_handler, 0, 1, 0);
                   3283: 
                   3284: #
                   3285: #   Put a new role for a user.  Roles are LonCAPA's packaging of permissions.
                   3286: #   Each 'role' a user has implies a set of permissions.  Adding a new role
                   3287: #   for a person grants the permissions packaged with that role
                   3288: #   to that user when the role is selected.
                   3289: #
                   3290: # Parameters:
                   3291: #    $cmd       - The command string (rolesput).
                   3292: #    $tail      - The remainder of the request line.  For rolesput this
                   3293: #                 consists of a colon separated list that contains:
                   3294: #                 The domain and user that is granting the role (logged).
                   3295: #                 The domain and user that is getting the role.
                   3296: #                 The roles being granted as a set of & separated pairs.
                   3297: #                 each pair a key value pair.
                   3298: #    $client    - File descriptor connected to the client.
                   3299: # Returns:
                   3300: #     0         - If the daemon should exit
                   3301: #     1         - To continue processing.
                   3302: #
                   3303: #
                   3304: sub roles_put_handler {
                   3305:     my ($cmd, $tail, $client) = @_;
                   3306: 
                   3307:     my $userinput  = "$cmd:$tail";
                   3308: 
                   3309:     my ( $exedom, $exeuser, $udom, $uname,  $what) = split(/:/,$tail);
                   3310:     
                   3311: 
                   3312:     my $namespace='roles';
                   3313:     chomp($what);
                   3314:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3315: 				 &GDBM_WRCREAT(), "P",
                   3316: 				 "$exedom:$exeuser:$what");
                   3317:     #
                   3318:     #  Log the attempt to set a role.  The {}'s here ensure that the file 
                   3319:     #  handle is open for the minimal amount of time.  Since the flush
                   3320:     #  is done on close this improves the chances the log will be an un-
                   3321:     #  corrupted ordered thing.
                   3322:     if ($hashref) {
1.261     foxr     3323: 	my $pass_entry = &get_auth_type($udom, $uname);
                   3324: 	my ($auth_type,$pwd)  = split(/:/, $pass_entry);
                   3325: 	$auth_type = $auth_type.":";
1.230     foxr     3326: 	my @pairs=split(/\&/,$what);
                   3327: 	foreach my $pair (@pairs) {
                   3328: 	    my ($key,$value)=split(/=/,$pair);
                   3329: 	    &manage_permissions($key, $udom, $uname,
1.260     foxr     3330: 			       $auth_type);
1.230     foxr     3331: 	    $hashref->{$key}=$value;
                   3332: 	}
1.311     albertel 3333: 	if (&untie_user_hash($hashref)) {
1.230     foxr     3334: 	    &Reply($client, "ok\n", $userinput);
                   3335: 	} else {
                   3336: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3337: 		     "while attempting rolesput\n", $userinput);
                   3338: 	}
                   3339:     } else {
                   3340: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3341: 		 "while attempting rolesput\n", $userinput);
                   3342:     }
                   3343:     return 1;
                   3344: }
                   3345: &register_handler("rolesput", \&roles_put_handler, 1,1,0);  # Encoded client only.
                   3346: 
                   3347: #
1.231     foxr     3348: #   Deletes (removes) a role for a user.   This is equivalent to removing
                   3349: #  a permissions package associated with the role from the user's profile.
                   3350: #
                   3351: # Parameters:
                   3352: #     $cmd                 - The command (rolesdel)
                   3353: #     $tail                - The remainder of the request line. This consists
                   3354: #                             of:
                   3355: #                             The domain and user requesting the change (logged)
                   3356: #                             The domain and user being changed.
                   3357: #                             The roles being revoked.  These are shipped to us
                   3358: #                             as a bunch of & separated role name keywords.
                   3359: #     $client              - The file handle open on the client.
                   3360: # Returns:
                   3361: #     1                    - Continue processing
                   3362: #     0                    - Exit.
                   3363: #
                   3364: sub roles_delete_handler {
                   3365:     my ($cmd, $tail, $client)  = @_;
                   3366: 
                   3367:     my $userinput    = "$cmd:$tail";
                   3368:    
                   3369:     my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
                   3370:     &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
                   3371: 	   "what = ".$what);
                   3372:     my $namespace='roles';
                   3373:     chomp($what);
                   3374:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3375: 				 &GDBM_WRCREAT(), "D",
                   3376: 				 "$exedom:$exeuser:$what");
                   3377:     
                   3378:     if ($hashref) {
                   3379: 	my @rolekeys=split(/\&/,$what);
                   3380: 	
                   3381: 	foreach my $key (@rolekeys) {
                   3382: 	    delete $hashref->{$key};
                   3383: 	}
1.315     albertel 3384: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3385: 	    &Reply($client, "ok\n", $userinput);
                   3386: 	} else {
                   3387: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3388: 		     "while attempting rolesdel\n", $userinput);
                   3389: 	}
                   3390:     } else {
                   3391:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3392: 		 "while attempting rolesdel\n", $userinput);
                   3393:     }
                   3394:     
                   3395:     return 1;
                   3396: }
                   3397: &register_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
                   3398: 
                   3399: # Unencrypted get from a user's profile database.  See 
                   3400: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
                   3401: # This function retrieves a keyed item from a specific named database in the
                   3402: # user's directory.
                   3403: #
                   3404: # Parameters:
                   3405: #   $cmd             - Command request keyword (get).
                   3406: #   $tail            - Tail of the command.  This is a colon separated list
                   3407: #                      consisting of the domain and username that uniquely
                   3408: #                      identifies the profile,
                   3409: #                      The 'namespace' which selects the gdbm file to 
                   3410: #                      do the lookup in, 
                   3411: #                      & separated list of keys to lookup.  Note that
                   3412: #                      the values are returned as an & separated list too.
                   3413: #   $client          - File descriptor open on the client.
                   3414: # Returns:
                   3415: #   1       - Continue processing.
                   3416: #   0       - Exit.
                   3417: #
                   3418: sub get_profile_entry {
                   3419:     my ($cmd, $tail, $client) = @_;
                   3420: 
                   3421:     my $userinput= "$cmd:$tail";
                   3422:    
                   3423:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   3424:     chomp($what);
1.255     foxr     3425: 
1.390     raeburn  3426: 
1.255     foxr     3427:     my $replystring = read_profile($udom, $uname, $namespace, $what);
                   3428:     my ($first) = split(/:/,$replystring);
                   3429:     if($first ne "error") {
1.387     albertel 3430: 	&Reply($client, \$replystring, $userinput);
1.231     foxr     3431:     } else {
1.255     foxr     3432: 	&Failure($client, $replystring." while attempting get\n", $userinput);
1.231     foxr     3433:     }
                   3434:     return 1;
1.255     foxr     3435: 
                   3436: 
1.231     foxr     3437: }
                   3438: &register_handler("get", \&get_profile_entry, 0,1,0);
                   3439: 
                   3440: #
                   3441: #  Process the encrypted get request.  Note that the request is sent
                   3442: #  in clear, but the reply is encrypted.  This is a small covert channel:
                   3443: #  information about the sensitive keys is given to the snooper.  Just not
                   3444: #  information about the values of the sensitive key.  Hmm if I wanted to
                   3445: #  know these I'd snoop for the egets. Get the profile item names from them
                   3446: #  and then issue a get for them since there's no enforcement of the
                   3447: #  requirement of an encrypted get for particular profile items.  If I
                   3448: #  were re-doing this, I'd force the request to be encrypted as well as the
                   3449: #  reply.  I'd also just enforce encrypted transactions for all gets since
                   3450: #  that would prevent any covert channel snooping.
                   3451: #
                   3452: #  Parameters:
                   3453: #     $cmd               - Command keyword of request (eget).
1.536     raeburn  3454: #     $tail              - Tail of the command.  See GetProfileEntry
                   3455: #                          for more information about this.
1.231     foxr     3456: #     $client            - File open on the client.
                   3457: #  Returns:
                   3458: #     1      - Continue processing
                   3459: #     0      - server should exit.
                   3460: sub get_profile_entry_encrypted {
                   3461:     my ($cmd, $tail, $client) = @_;
                   3462: 
                   3463:     my $userinput = "$cmd:$tail";
                   3464:    
1.339     albertel 3465:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
1.231     foxr     3466:     chomp($what);
1.255     foxr     3467:     my $qresult = read_profile($udom, $uname, $namespace, $what);
                   3468:     my ($first) = split(/:/, $qresult);
                   3469:     if($first ne "error") {
                   3470: 	
                   3471: 	if ($cipher) {
                   3472: 	    my $cmdlength=length($qresult);
                   3473: 	    $qresult.="         ";
                   3474: 	    my $encqresult='';
                   3475: 	    for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   3476: 		$encqresult.= unpack("H16", 
                   3477: 				     $cipher->encrypt(substr($qresult,
                   3478: 							     $encidx,
                   3479: 							     8)));
                   3480: 	    }
                   3481: 	    &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
                   3482: 	} else {
1.231     foxr     3483: 		&Failure( $client, "error:no_key\n", $userinput);
                   3484: 	    }
                   3485:     } else {
1.255     foxr     3486: 	&Failure($client, "$qresult while attempting eget\n", $userinput);
                   3487: 
1.231     foxr     3488:     }
                   3489:     
                   3490:     return 1;
                   3491: }
1.255     foxr     3492: &register_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
1.263     albertel 3493: 
1.231     foxr     3494: #
                   3495: #   Deletes a key in a user profile database.
                   3496: #   
                   3497: #   Parameters:
                   3498: #       $cmd                  - Command keyword (del).
                   3499: #       $tail                 - Command tail.  IN this case a colon
                   3500: #                               separated list containing:
                   3501: #                               The domain and user that identifies uniquely
                   3502: #                               the identity of the user.
                   3503: #                               The profile namespace (name of the profile
                   3504: #                               database file).
                   3505: #                               & separated list of keywords to delete.
                   3506: #       $client              - File open on client socket.
                   3507: # Returns:
                   3508: #     1   - Continue processing
                   3509: #     0   - Exit server.
                   3510: #
                   3511: #
                   3512: sub delete_profile_entry {
                   3513:     my ($cmd, $tail, $client) = @_;
                   3514: 
                   3515:     my $userinput = "cmd:$tail";
                   3516: 
                   3517:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   3518:     chomp($what);
                   3519:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3520: 				 &GDBM_WRCREAT(),
                   3521: 				 "D",$what);
                   3522:     if ($hashref) {
                   3523:         my @keys=split(/\&/,$what);
                   3524: 	foreach my $key (@keys) {
                   3525: 	    delete($hashref->{$key});
                   3526: 	}
1.315     albertel 3527: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3528: 	    &Reply($client, "ok\n", $userinput);
                   3529: 	} else {
                   3530: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3531: 		    "while attempting del\n", $userinput);
                   3532: 	}
                   3533:     } else {
                   3534: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3535: 		 "while attempting del\n", $userinput);
                   3536:     }
                   3537:     return 1;
                   3538: }
                   3539: &register_handler("del", \&delete_profile_entry, 0, 1, 0);
1.263     albertel 3540: 
1.231     foxr     3541: #
                   3542: #  List the set of keys that are defined in a profile database file.
                   3543: #  A successful reply from this will contain an & separated list of
                   3544: #  the keys. 
                   3545: # Parameters:
                   3546: #     $cmd              - Command request (keys).
                   3547: #     $tail             - Remainder of the request, a colon separated
                   3548: #                         list containing domain/user that identifies the
                   3549: #                         user being queried, and the database namespace
                   3550: #                         (database filename essentially).
                   3551: #     $client           - File open on the client.
                   3552: #  Returns:
                   3553: #    1    - Continue processing.
                   3554: #    0    - Exit the server.
                   3555: #
                   3556: sub get_profile_keys {
                   3557:     my ($cmd, $tail, $client) = @_;
                   3558: 
                   3559:     my $userinput = "$cmd:$tail";
                   3560: 
                   3561:     my ($udom,$uname,$namespace)=split(/:/,$tail);
                   3562:     my $qresult='';
                   3563:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3564: 				  &GDBM_READER());
                   3565:     if ($hashref) {
                   3566: 	foreach my $key (keys %$hashref) {
                   3567: 	    $qresult.="$key&";
                   3568: 	}
1.315     albertel 3569: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3570: 	    $qresult=~s/\&$//;
1.387     albertel 3571: 	    &Reply($client, \$qresult, $userinput);
1.231     foxr     3572: 	} else {
                   3573: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3574: 		    "while attempting keys\n", $userinput);
                   3575: 	}
                   3576:     } else {
                   3577: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3578: 		 "while attempting keys\n", $userinput);
                   3579:     }
                   3580:    
                   3581:     return 1;
                   3582: }
                   3583: &register_handler("keys", \&get_profile_keys, 0, 1, 0);
                   3584: 
                   3585: #
                   3586: #   Dump the contents of a user profile database.
                   3587: #   Note that this constitutes a very large covert channel too since
                   3588: #   the dump will return sensitive information that is not encrypted.
                   3589: #   The naive security assumption is that the session negotiation ensures
                   3590: #   our client is trusted and I don't believe that's assured at present.
                   3591: #   Sure want badly to go to ssl or tls.  Of course if my peer isn't really
                   3592: #   a LonCAPA node they could have negotiated an encryption key too so >sigh<.
                   3593: # 
                   3594: #  Parameters:
                   3595: #     $cmd           - The command request keyword (currentdump).
                   3596: #     $tail          - Remainder of the request, consisting of a colon
                   3597: #                      separated list that has the domain/username and
                   3598: #                      the namespace to dump (database file).
                   3599: #     $client        - file open on the remote client.
                   3600: # Returns:
                   3601: #     1    - Continue processing.
                   3602: #     0    - Exit the server.
                   3603: #
                   3604: sub dump_profile_database {
                   3605:     my ($cmd, $tail, $client) = @_;
                   3606: 
1.494     droeschl 3607:     my $res = LONCAPA::Lond::dump_profile_database($tail);
                   3608: 
                   3609:     if ($res =~ /^error:/) {
                   3610:         Failure($client, \$res, "$cmd:$tail");
                   3611:     } else {
                   3612:         Reply($client, \$res, "$cmd:$tail");
                   3613:     }
                   3614: 
                   3615:     return 1;  
                   3616: 
                   3617:     #TODO remove 
1.231     foxr     3618:     my $userinput = "$cmd:$tail";
                   3619:    
                   3620:     my ($udom,$uname,$namespace) = split(/:/,$tail);
                   3621:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3622: 				 &GDBM_READER());
                   3623:     if ($hashref) {
                   3624: 	# Structure of %data:
                   3625: 	# $data{$symb}->{$parameter}=$value;
                   3626: 	# $data{$symb}->{'v.'.$parameter}=$version;
                   3627: 	# since $parameter will be unescaped, we do not
                   3628:  	# have to worry about silly parameter names...
                   3629: 	
                   3630:         my $qresult='';
                   3631: 	my %data = ();                     # A hash of anonymous hashes..
                   3632: 	while (my ($key,$value) = each(%$hashref)) {
                   3633: 	    my ($v,$symb,$param) = split(/:/,$key);
                   3634: 	    next if ($v eq 'version' || $symb eq 'keys');
                   3635: 	    next if (exists($data{$symb}) && 
                   3636: 		     exists($data{$symb}->{$param}) &&
                   3637: 		     $data{$symb}->{'v.'.$param} > $v);
                   3638: 	    $data{$symb}->{$param}=$value;
                   3639: 	    $data{$symb}->{'v.'.$param}=$v;
                   3640: 	}
1.311     albertel 3641: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3642: 	    while (my ($symb,$param_hash) = each(%data)) {
                   3643: 		while(my ($param,$value) = each (%$param_hash)){
                   3644: 		    next if ($param =~ /^v\./);       # Ignore versions...
                   3645: 		    #
                   3646: 		    #   Just dump the symb=value pairs separated by &
                   3647: 		    #
                   3648: 		    $qresult.=$symb.':'.$param.'='.$value.'&';
                   3649: 		}
                   3650: 	    }
                   3651: 	    chop($qresult);
1.387     albertel 3652: 	    &Reply($client , \$qresult, $userinput);
1.231     foxr     3653: 	} else {
                   3654: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3655: 		     "while attempting currentdump\n", $userinput);
                   3656: 	}
                   3657:     } else {
                   3658: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3659: 		"while attempting currentdump\n", $userinput);
                   3660:     }
                   3661: 
                   3662:     return 1;
                   3663: }
                   3664: &register_handler("currentdump", \&dump_profile_database, 0, 1, 0);
                   3665: 
                   3666: #
                   3667: #   Dump a profile database with an optional regular expression
                   3668: #   to match against the keys.  In this dump, no effort is made
                   3669: #   to separate symb from version information. Presumably the
                   3670: #   databases that are dumped by this command are of a different
                   3671: #   structure.  Need to look at this and improve the documentation of
                   3672: #   both this and the currentdump handler.
                   3673: # Parameters:
                   3674: #    $cmd                     - The command keyword.
                   3675: #    $tail                    - All of the characters after the $cmd:
                   3676: #                               These are expected to be a colon
                   3677: #                               separated list containing:
                   3678: #                               domain/user - identifying the user.
                   3679: #                               namespace   - identifying the database.
                   3680: #                               regexp      - optional regular expression
                   3681: #                                             that is matched against
                   3682: #                                             database keywords to do
                   3683: #                                             selective dumps.
1.488     raeburn  3684: #                               range       - optional range of entries
                   3685: #                                             e.g., 10-20 would return the
                   3686: #                                             10th to 19th items, etc.  
1.231     foxr     3687: #   $client                   - Channel open on the client.
                   3688: # Returns:
                   3689: #    1    - Continue processing.
                   3690: # Side effects:
                   3691: #    response is written to $client.
                   3692: #
                   3693: sub dump_with_regexp {
                   3694:     my ($cmd, $tail, $client) = @_;
                   3695: 
1.494     droeschl 3696:     my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
1.490     droeschl 3697:     
                   3698:     if ($res =~ /^error:/) {
                   3699:         Failure($client, \$res, "$cmd:$tail");
                   3700:     } else {
                   3701:         Reply($client, \$res, "$cmd:$tail");
                   3702:     }
1.231     foxr     3703: 
                   3704:     return 1;
                   3705: }
                   3706: &register_handler("dump", \&dump_with_regexp, 0, 1, 0);
                   3707: 
                   3708: #  Store a set of key=value pairs associated with a versioned name.
                   3709: #
                   3710: #  Parameters:
                   3711: #    $cmd                - Request command keyword.
                   3712: #    $tail               - Tail of the request.  This is a colon
                   3713: #                          separated list containing:
                   3714: #                          domain/user - User and authentication domain.
                   3715: #                          namespace   - Name of the database being modified
                   3716: #                          rid         - Resource keyword to modify.
                   3717: #                          what        - new value associated with rid.
1.512     raeburn  3718: #                          laststore   - (optional) version=timestamp
                   3719: #                                        for most recent transaction for rid
                   3720: #                                        in namespace, when cstore was called
1.231     foxr     3721: #
                   3722: #    $client             - Socket open on the client.
                   3723: #
                   3724: #
                   3725: #  Returns:
                   3726: #      1 (keep on processing).
                   3727: #  Side-Effects:
                   3728: #    Writes to the client
1.512     raeburn  3729: #    Successful storage will cause either 'ok', or, if $laststore was included
                   3730: #    in the tail of the request, and the version number for the last transaction
                   3731: #    is larger than the version in $laststore, delay:$numtrans , where $numtrans
                   3732: #    is the number of store evevnts recorded for rid in namespace since
                   3733: #    lonnet::store() was called by the client.
                   3734: #
1.231     foxr     3735: sub store_handler {
                   3736:     my ($cmd, $tail, $client) = @_;
                   3737:  
                   3738:     my $userinput = "$cmd:$tail";
1.512     raeburn  3739:     chomp($tail);
                   3740:     my ($udom,$uname,$namespace,$rid,$what,$laststore) =split(/:/,$tail);
1.231     foxr     3741:     if ($namespace ne 'roles') {
                   3742: 
                   3743: 	my @pairs=split(/\&/,$what);
                   3744: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
1.268     albertel 3745: 				       &GDBM_WRCREAT(), "S",
1.231     foxr     3746: 				       "$rid:$what");
                   3747: 	if ($hashref) {
                   3748: 	    my $now = time;
1.512     raeburn  3749:             my $numtrans;
                   3750:             if ($laststore) {
                   3751:                 my ($previousversion,$previoustime) = split(/\=/,$laststore);
                   3752:                 my ($lastversion,$lasttime) = (0,0);
                   3753:                 $lastversion = $hashref->{"version:$rid"};
                   3754:                 if ($lastversion) {
                   3755:                     $lasttime = $hashref->{"$lastversion:$rid:timestamp"};
                   3756:                 }
                   3757:                 if (($previousversion) && ($previousversion !~ /\D/)) {
                   3758:                     if (($lastversion > $previousversion) && ($lasttime >= $previoustime)) {
                   3759:                         $numtrans = $lastversion - $previousversion;
                   3760:                     }
                   3761:                 } elsif ($lastversion) {
                   3762:                     $numtrans = $lastversion;
                   3763:                 }
                   3764:                 if ($numtrans) {
                   3765:                     $numtrans =~ s/D//g;
                   3766:                 }
                   3767:             }
1.231     foxr     3768: 	    $hashref->{"version:$rid"}++;
                   3769: 	    my $version=$hashref->{"version:$rid"};
                   3770: 	    my $allkeys=''; 
                   3771: 	    foreach my $pair (@pairs) {
                   3772: 		my ($key,$value)=split(/=/,$pair);
                   3773: 		$allkeys.=$key.':';
                   3774: 		$hashref->{"$version:$rid:$key"}=$value;
                   3775: 	    }
                   3776: 	    $hashref->{"$version:$rid:timestamp"}=$now;
                   3777: 	    $allkeys.='timestamp';
                   3778: 	    $hashref->{"$version:keys:$rid"}=$allkeys;
1.311     albertel 3779: 	    if (&untie_user_hash($hashref)) {
1.512     raeburn  3780:                 my $msg = 'ok';
                   3781:                 if ($numtrans) {
                   3782:                     $msg = 'delay:'.$numtrans;
                   3783:                 }
                   3784: 		&Reply($client, "$msg\n", $userinput);
1.231     foxr     3785: 	    } else {
                   3786: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3787: 			"while attempting store\n", $userinput);
                   3788: 	    }
                   3789: 	} else {
                   3790: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3791: 		     "while attempting store\n", $userinput);
                   3792: 	}
                   3793:     } else {
                   3794: 	&Failure($client, "refused\n", $userinput);
                   3795:     }
                   3796: 
                   3797:     return 1;
                   3798: }
                   3799: &register_handler("store", \&store_handler, 0, 1, 0);
1.263     albertel 3800: 
1.323     albertel 3801: #  Modify a set of key=value pairs associated with a versioned name.
                   3802: #
                   3803: #  Parameters:
                   3804: #    $cmd                - Request command keyword.
                   3805: #    $tail               - Tail of the request.  This is a colon
                   3806: #                          separated list containing:
                   3807: #                          domain/user - User and authentication domain.
                   3808: #                          namespace   - Name of the database being modified
                   3809: #                          rid         - Resource keyword to modify.
                   3810: #                          v           - Version item to modify
                   3811: #                          what        - new value associated with rid.
                   3812: #
                   3813: #    $client             - Socket open on the client.
                   3814: #
                   3815: #
                   3816: #  Returns:
                   3817: #      1 (keep on processing).
                   3818: #  Side-Effects:
                   3819: #    Writes to the client
                   3820: sub putstore_handler {
                   3821:     my ($cmd, $tail, $client) = @_;
                   3822:  
                   3823:     my $userinput = "$cmd:$tail";
                   3824: 
                   3825:     my ($udom,$uname,$namespace,$rid,$v,$what) =split(/:/,$tail);
                   3826:     if ($namespace ne 'roles') {
                   3827: 
                   3828: 	chomp($what);
                   3829: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
                   3830: 				       &GDBM_WRCREAT(), "M",
                   3831: 				       "$rid:$v:$what");
                   3832: 	if ($hashref) {
                   3833: 	    my $now = time;
                   3834: 	    my %data = &hash_extract($what);
                   3835: 	    my @allkeys;
                   3836: 	    while (my($key,$value) = each(%data)) {
                   3837: 		push(@allkeys,$key);
                   3838: 		$hashref->{"$v:$rid:$key"} = $value;
                   3839: 	    }
                   3840: 	    my $allkeys = join(':',@allkeys);
                   3841: 	    $hashref->{"$v:keys:$rid"}=$allkeys;
                   3842: 
                   3843: 	    if (&untie_user_hash($hashref)) {
                   3844: 		&Reply($client, "ok\n", $userinput);
                   3845: 	    } else {
                   3846: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3847: 			"while attempting store\n", $userinput);
                   3848: 	    }
                   3849: 	} else {
                   3850: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3851: 		     "while attempting store\n", $userinput);
                   3852: 	}
                   3853:     } else {
                   3854: 	&Failure($client, "refused\n", $userinput);
                   3855:     }
                   3856: 
                   3857:     return 1;
                   3858: }
                   3859: &register_handler("putstore", \&putstore_handler, 0, 1, 0);
                   3860: 
                   3861: sub hash_extract {
                   3862:     my ($str)=@_;
                   3863:     my %hash;
                   3864:     foreach my $pair (split(/\&/,$str)) {
                   3865: 	my ($key,$value)=split(/=/,$pair);
                   3866: 	$hash{$key}=$value;
                   3867:     }
                   3868:     return (%hash);
                   3869: }
                   3870: sub hash_to_str {
                   3871:     my ($hash_ref)=@_;
                   3872:     my $str;
                   3873:     foreach my $key (keys(%$hash_ref)) {
                   3874: 	$str.=$key.'='.$hash_ref->{$key}.'&';
                   3875:     }
                   3876:     $str=~s/\&$//;
                   3877:     return $str;
                   3878: }
                   3879: 
1.231     foxr     3880: #
                   3881: #  Dump out all versions of a resource that has key=value pairs associated
                   3882: # with it for each version.  These resources are built up via the store
                   3883: # command.
                   3884: #
                   3885: #  Parameters:
                   3886: #     $cmd               - Command keyword.
                   3887: #     $tail              - Remainder of the request which consists of:
                   3888: #                          domain/user   - User and auth. domain.
                   3889: #                          namespace     - name of resource database.
                   3890: #                          rid           - Resource id.
                   3891: #    $client             - socket open on the client.
                   3892: #
                   3893: # Returns:
                   3894: #      1  indicating the caller should not yet exit.
                   3895: # Side-effects:
                   3896: #   Writes a reply to the client.
                   3897: #   The reply is a string of the following shape:
                   3898: #   version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
                   3899: #    Where the 1 above represents version 1.
                   3900: #    this continues for all pairs of keys in all versions.
                   3901: #
                   3902: #
                   3903: #    
                   3904: #
                   3905: sub restore_handler {
                   3906:     my ($cmd, $tail, $client) = @_;
                   3907: 
                   3908:     my $userinput = "$cmd:$tail";	# Only used for logging purposes.
1.351     banghart 3909:     my ($udom,$uname,$namespace,$rid) = split(/:/,$tail);
1.352     albertel 3910:     $namespace=~s/\//\_/g;
1.350     albertel 3911:     $namespace = &LONCAPA::clean_username($namespace);
1.349     albertel 3912: 
1.231     foxr     3913:     chomp($rid);
                   3914:     my $qresult='';
1.309     albertel 3915:     my $hashref = &tie_user_hash($udom, $uname, $namespace, &GDBM_READER());
                   3916:     if ($hashref) {
                   3917: 	my $version=$hashref->{"version:$rid"};
1.231     foxr     3918: 	$qresult.="version=$version&";
                   3919: 	my $scope;
                   3920: 	for ($scope=1;$scope<=$version;$scope++) {
1.309     albertel 3921: 	    my $vkeys=$hashref->{"$scope:keys:$rid"};
1.231     foxr     3922: 	    my @keys=split(/:/,$vkeys);
                   3923: 	    my $key;
                   3924: 	    $qresult.="$scope:keys=$vkeys&";
                   3925: 	    foreach $key (@keys) {
1.309     albertel 3926: 		$qresult.="$scope:$key=".$hashref->{"$scope:$rid:$key"}."&";
1.231     foxr     3927: 	    }                                  
                   3928: 	}
1.311     albertel 3929: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3930: 	    $qresult=~s/\&$//;
1.387     albertel 3931: 	    &Reply( $client, \$qresult, $userinput);
1.231     foxr     3932: 	} else {
                   3933: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3934: 		    "while attempting restore\n", $userinput);
                   3935: 	}
                   3936:     } else {
                   3937: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3938: 		"while attempting restore\n", $userinput);
                   3939:     }
                   3940:   
                   3941:     return 1;
                   3942: 
                   3943: 
                   3944: }
                   3945: &register_handler("restore", \&restore_handler, 0,1,0);
1.234     foxr     3946: 
                   3947: #
1.324     raeburn  3948: #   Add a chat message to a synchronous discussion board.
1.234     foxr     3949: #
                   3950: # Parameters:
                   3951: #    $cmd                - Request keyword.
                   3952: #    $tail               - Tail of the command. A colon separated list
                   3953: #                          containing:
                   3954: #                          cdom    - Domain on which the chat board lives
1.324     raeburn  3955: #                          cnum    - Course containing the chat board.
                   3956: #                          newpost - Body of the posting.
                   3957: #                          group   - Optional group, if chat board is only 
                   3958: #                                    accessible in a group within the course 
1.234     foxr     3959: #   $client              - Socket open on the client.
                   3960: # Returns:
                   3961: #   1    - Indicating caller should keep on processing.
                   3962: #
                   3963: # Side-effects:
                   3964: #   writes a reply to the client.
                   3965: #
                   3966: #
                   3967: sub send_chat_handler {
                   3968:     my ($cmd, $tail, $client) = @_;
                   3969: 
                   3970:     
                   3971:     my $userinput = "$cmd:$tail";
                   3972: 
1.324     raeburn  3973:     my ($cdom,$cnum,$newpost,$group)=split(/\:/,$tail);
                   3974:     &chat_add($cdom,$cnum,$newpost,$group);
1.234     foxr     3975:     &Reply($client, "ok\n", $userinput);
                   3976: 
                   3977:     return 1;
                   3978: }
                   3979: &register_handler("chatsend", \&send_chat_handler, 0, 1, 0);
1.263     albertel 3980: 
1.234     foxr     3981: #
1.324     raeburn  3982: #   Retrieve the set of chat messages from a discussion board.
1.234     foxr     3983: #
                   3984: #  Parameters:
                   3985: #    $cmd             - Command keyword that initiated the request.
                   3986: #    $tail            - Remainder of the request after the command
                   3987: #                       keyword.  In this case a colon separated list of
                   3988: #                       chat domain    - Which discussion board.
                   3989: #                       chat id        - Discussion thread(?)
                   3990: #                       domain/user    - Authentication domain and username
                   3991: #                                        of the requesting person.
1.324     raeburn  3992: #                       group          - Optional course group containing
                   3993: #                                        the board.      
1.234     foxr     3994: #   $client           - Socket open on the client program.
                   3995: # Returns:
                   3996: #    1     - continue processing
                   3997: # Side effects:
                   3998: #    Response is written to the client.
                   3999: #
                   4000: sub retrieve_chat_handler {
                   4001:     my ($cmd, $tail, $client) = @_;
                   4002: 
                   4003: 
                   4004:     my $userinput = "$cmd:$tail";
                   4005: 
1.324     raeburn  4006:     my ($cdom,$cnum,$udom,$uname,$group)=split(/\:/,$tail);
1.234     foxr     4007:     my $reply='';
1.324     raeburn  4008:     foreach (&get_chat($cdom,$cnum,$udom,$uname,$group)) {
1.234     foxr     4009: 	$reply.=&escape($_).':';
                   4010:     }
                   4011:     $reply=~s/\:$//;
1.387     albertel 4012:     &Reply($client, \$reply, $userinput);
1.234     foxr     4013: 
                   4014: 
                   4015:     return 1;
                   4016: }
                   4017: &register_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
                   4018: 
                   4019: #
                   4020: #  Initiate a query of an sql database.  SQL query repsonses get put in
                   4021: #  a file for later retrieval.  This prevents sql query results from
                   4022: #  bottlenecking the system.  Note that with loncnew, perhaps this is
                   4023: #  less of an issue since multiple outstanding requests can be concurrently
                   4024: #  serviced.
                   4025: #
                   4026: #  Parameters:
1.535     raeburn  4027: #     $cmd       - Command keyword that initiated the request.
1.234     foxr     4028: #     $tail      - Remainder of the command after the keyword.
                   4029: #                  For this function, this consists of a query and
                   4030: #                  3 arguments that are self-documentingly labelled
                   4031: #                  in the original arg1, arg2, arg3.
                   4032: #     $client    - Socket open on the client.
                   4033: # Return:
                   4034: #    1   - Indicating processing should continue.
                   4035: # Side-effects:
                   4036: #    a reply is written to $client.
                   4037: #
                   4038: sub send_query_handler {
                   4039:     my ($cmd, $tail, $client) = @_;
                   4040: 
                   4041:     my $userinput = "$cmd:$tail";
                   4042: 
                   4043:     my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
                   4044:     $query=~s/\n*$//g;
1.534     raeburn  4045:     if (($query eq 'usersearch') || ($query eq 'instdirsearch')) {
                   4046:         my $usersearchconf = &get_usersearch_config($currentdomainid,'directorysrch');
                   4047:         my $earlyout;
                   4048:         if (ref($usersearchconf) eq 'HASH') {
                   4049:             if ($currentdomainid eq $clienthomedom) {
                   4050:                 if ($query eq 'usersearch') {
                   4051:                     if ($usersearchconf->{'lcavailable'} eq '0') {
                   4052:                         $earlyout = 1;
                   4053:                     }
                   4054:                 } else {
                   4055:                     if ($usersearchconf->{'available'} eq '0') {
                   4056:                         $earlyout = 1;
                   4057:                     }
                   4058:                 }
                   4059:             } else {
                   4060:                 if ($query eq 'usersearch') {
                   4061:                     if ($usersearchconf->{'lclocalonly'}) {
                   4062:                         $earlyout = 1;
                   4063:                     }
                   4064:                 } else {
                   4065:                     if ($usersearchconf->{'localonly'}) {
                   4066:                         $earlyout = 1;
                   4067:                     }
                   4068:                 }
                   4069:             }
                   4070:         }
                   4071:         if ($earlyout) {
                   4072:             &Reply($client, "query_not_authorized\n");
                   4073:             return 1;
                   4074:         }
                   4075:     }
1.234     foxr     4076:     &Reply($client, "". &sql_reply("$clientname\&$query".
                   4077: 				"\&$arg1"."\&$arg2"."\&$arg3")."\n",
                   4078: 	  $userinput);
                   4079:     
                   4080:     return 1;
                   4081: }
                   4082: &register_handler("querysend", \&send_query_handler, 0, 1, 0);
                   4083: 
                   4084: #
                   4085: #   Add a reply to an sql query.  SQL queries are done asyncrhonously.
                   4086: #   The query is submitted via a "querysend" transaction.
                   4087: #   There it is passed on to the lonsql daemon, queued and issued to
                   4088: #   mysql.
                   4089: #     This transaction is invoked when the sql transaction is complete
                   4090: #   it stores the query results in flie and indicates query completion.
                   4091: #   presumably local software then fetches this response... I'm guessing
                   4092: #   the sequence is: lonc does a querysend, we ask lonsql to do it.
                   4093: #   lonsql on completion of the query interacts with the lond of our
                   4094: #   client to do a query reply storing two files:
                   4095: #    - id     - The results of the query.
                   4096: #    - id.end - Indicating the transaction completed. 
                   4097: #    NOTE: id is a unique id assigned to the query and querysend time.
                   4098: # Parameters:
                   4099: #    $cmd        - Command keyword that initiated this request.
                   4100: #    $tail       - Remainder of the tail.  In this case that's a colon
                   4101: #                  separated list containing the query Id and the 
                   4102: #                  results of the query.
                   4103: #    $client     - Socket open on the client.
                   4104: # Return:
                   4105: #    1           - Indicating that we should continue processing.
                   4106: # Side effects:
                   4107: #    ok written to the client.
                   4108: #
                   4109: sub reply_query_handler {
                   4110:     my ($cmd, $tail, $client) = @_;
                   4111: 
                   4112: 
                   4113:     my $userinput = "$cmd:$tail";
                   4114: 
1.339     albertel 4115:     my ($id,$reply)=split(/:/,$tail); 
1.234     foxr     4116:     my $store;
                   4117:     my $execdir=$perlvar{'lonDaemons'};
                   4118:     if ($store=IO::File->new(">$execdir/tmp/$id")) {
                   4119: 	$reply=~s/\&/\n/g;
                   4120: 	print $store $reply;
                   4121: 	close $store;
                   4122: 	my $store2=IO::File->new(">$execdir/tmp/$id.end");
                   4123: 	print $store2 "done\n";
                   4124: 	close $store2;
                   4125: 	&Reply($client, "ok\n", $userinput);
                   4126:     } else {
                   4127: 	&Failure($client, "error: ".($!+0)
                   4128: 		." IO::File->new Failed ".
                   4129: 		"while attempting queryreply\n", $userinput);
                   4130:     }
                   4131:  
                   4132: 
                   4133:     return 1;
                   4134: }
                   4135: &register_handler("queryreply", \&reply_query_handler, 0, 1, 0);
                   4136: 
                   4137: #
                   4138: #  Process the courseidput request.  Not quite sure what this means
                   4139: #  at the system level sense.  It appears a gdbm file in the 
                   4140: #  /home/httpd/lonUsers/$domain/nohist_courseids is tied and
                   4141: #  a set of entries made in that database.
                   4142: #
                   4143: # Parameters:
                   4144: #   $cmd      - The command keyword that initiated this request.
                   4145: #   $tail     - Tail of the command.  In this case consists of a colon
                   4146: #               separated list contaning the domain to apply this to and
                   4147: #               an ampersand separated list of keyword=value pairs.
1.272     raeburn  4148: #               Each value is a colon separated list that includes:  
                   4149: #               description, institutional code and course owner.
                   4150: #               For backward compatibility with versions included
                   4151: #               in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
                   4152: #               code and/or course owner are preserved from the existing 
                   4153: #               record when writing a new record in response to 1.1 or 
                   4154: #               1.2 implementations of lonnet::flushcourselogs().   
                   4155: #                      
1.234     foxr     4156: #   $client   - Socket open on the client.
                   4157: # Returns:
                   4158: #   1    - indicating that processing should continue
                   4159: #
                   4160: # Side effects:
                   4161: #   reply is written to the client.
                   4162: #
                   4163: sub put_course_id_handler {
                   4164:     my ($cmd, $tail, $client) = @_;
                   4165: 
                   4166: 
                   4167:     my $userinput = "$cmd:$tail";
                   4168: 
1.266     raeburn  4169:     my ($udom, $what) = split(/:/, $tail,2);
1.234     foxr     4170:     chomp($what);
                   4171:     my $now=time;
                   4172:     my @pairs=split(/\&/,$what);
                   4173: 
                   4174:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   4175:     if ($hashref) {
                   4176: 	foreach my $pair (@pairs) {
1.271     raeburn  4177:             my ($key,$courseinfo) = split(/=/,$pair,2);
                   4178:             $courseinfo =~ s/=/:/g;
1.384     raeburn  4179:             if (defined($hashref->{$key})) {
                   4180:                 my $value = &Apache::lonnet::thaw_unescape($hashref->{$key});
                   4181:                 if (ref($value) eq 'HASH') {
                   4182:                     my @items = ('description','inst_code','owner','type');
                   4183:                     my @new_items = split(/:/,$courseinfo,-1);
                   4184:                     my %storehash; 
                   4185:                     for (my $i=0; $i<@new_items; $i++) {
1.391     raeburn  4186:                         $storehash{$items[$i]} = &unescape($new_items[$i]);
1.384     raeburn  4187:                     }
                   4188:                     $hashref->{$key} = 
                   4189:                         &Apache::lonnet::freeze_escape(\%storehash);
                   4190:                     my $unesc_key = &unescape($key);
                   4191:                     $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
                   4192:                     next;
1.383     raeburn  4193:                 }
1.384     raeburn  4194:             }
                   4195:             my @current_items = split(/:/,$hashref->{$key},-1);
                   4196:             shift(@current_items); # remove description
                   4197:             pop(@current_items);   # remove last access
                   4198:             my $numcurrent = scalar(@current_items);
                   4199:             if ($numcurrent > 3) {
                   4200:                 $numcurrent = 3;
                   4201:             }
                   4202:             my @new_items = split(/:/,$courseinfo,-1);
                   4203:             my $numnew = scalar(@new_items);
                   4204:             if ($numcurrent > 0) {
                   4205:                 if ($numnew <= $numcurrent) { # flushcourselogs() from pre 2.2 
                   4206:                     for (my $j=$numcurrent-$numnew; $j>=0; $j--) {
                   4207:                         $courseinfo .= ':'.$current_items[$numcurrent-$j-1];
1.333     raeburn  4208:                     }
1.272     raeburn  4209:                 }
                   4210:             }
1.384     raeburn  4211:             $hashref->{$key}=$courseinfo.':'.$now;
1.234     foxr     4212: 	}
1.311     albertel 4213: 	if (&untie_domain_hash($hashref)) {
1.253     foxr     4214: 	    &Reply( $client, "ok\n", $userinput);
1.234     foxr     4215: 	} else {
1.253     foxr     4216: 	    &Failure($client, "error: ".($!+0)
1.234     foxr     4217: 		     ." untie(GDBM) Failed ".
                   4218: 		     "while attempting courseidput\n", $userinput);
                   4219: 	}
                   4220:     } else {
1.253     foxr     4221: 	&Failure($client, "error: ".($!+0)
1.234     foxr     4222: 		 ." tie(GDBM) Failed ".
                   4223: 		 "while attempting courseidput\n", $userinput);
                   4224:     }
                   4225: 
                   4226:     return 1;
                   4227: }
                   4228: &register_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
                   4229: 
1.383     raeburn  4230: sub put_course_id_hash_handler {
                   4231:     my ($cmd, $tail, $client) = @_;
                   4232:     my $userinput = "$cmd:$tail";
1.384     raeburn  4233:     my ($udom,$mode,$what) = split(/:/, $tail,3);
1.383     raeburn  4234:     chomp($what);
                   4235:     my $now=time;
                   4236:     my @pairs=split(/\&/,$what);
1.384     raeburn  4237:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
1.383     raeburn  4238:     if ($hashref) {
                   4239:         foreach my $pair (@pairs) {
                   4240:             my ($key,$value)=split(/=/,$pair);
1.384     raeburn  4241:             my $unesc_key = &unescape($key);
                   4242:             if ($mode ne 'timeonly') {
                   4243:                 if (!defined($hashref->{&escape('lasttime:'.$unesc_key)})) {
                   4244:                     my $curritems = &Apache::lonnet::thaw_unescape($key); 
                   4245:                     if (ref($curritems) ne 'HASH') {
                   4246:                         my @current_items = split(/:/,$hashref->{$key},-1);
                   4247:                         my $lasttime = pop(@current_items);
                   4248:                         $hashref->{&escape('lasttime:'.$unesc_key)} = $lasttime;
                   4249:                     } else {
                   4250:                         $hashref->{&escape('lasttime:'.$unesc_key)} = '';
                   4251:                     }
                   4252:                 } 
                   4253:                 $hashref->{$key} = $value;
                   4254:             }
                   4255:             if ($mode ne 'notime') {
                   4256:                 $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
                   4257:             }
1.383     raeburn  4258:         }
                   4259:         if (&untie_domain_hash($hashref)) {
                   4260:             &Reply($client, "ok\n", $userinput);
                   4261:         } else {
                   4262:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4263:                      "while attempting courseidputhash\n", $userinput);
                   4264:         }
                   4265:     } else {
                   4266:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4267:                   "while attempting courseidputhash\n", $userinput);
                   4268:     }
                   4269:     return 1;
                   4270: }
                   4271: &register_handler("courseidputhash", \&put_course_id_hash_handler, 0, 1, 0);
                   4272: 
1.234     foxr     4273: #  Retrieves the value of a course id resource keyword pattern
                   4274: #  defined since a starting date.  Both the starting date and the
                   4275: #  keyword pattern are optional.  If the starting date is not supplied it
                   4276: #  is treated as the beginning of time.  If the pattern is not found,
                   4277: #  it is treatred as "." matching everything.
                   4278: #
                   4279: #  Parameters:
                   4280: #     $cmd     - Command keyword that resulted in us being dispatched.
                   4281: #     $tail    - The remainder of the command that, in this case, consists
                   4282: #                of a colon separated list of:
                   4283: #                 domain   - The domain in which the course database is 
                   4284: #                            defined.
                   4285: #                 since    - Optional parameter describing the minimum
                   4286: #                            time of definition(?) of the resources that
                   4287: #                            will match the dump.
                   4288: #                 description - regular expression that is used to filter
                   4289: #                            the dump.  Only keywords matching this regexp
                   4290: #                            will be used.
1.272     raeburn  4291: #                 institutional code - optional supplied code to filter 
                   4292: #                            the dump. Only courses with an institutional code 
                   4293: #                            that match the supplied code will be returned.
1.336     raeburn  4294: #                 owner    - optional supplied username and domain of owner to
                   4295: #                            filter the dump.  Only courses for which the course
                   4296: #                            owner matches the supplied username and/or domain
                   4297: #                            will be returned. Pre-2.2.0 legacy entries from 
                   4298: #                            nohist_courseiddump will only contain usernames.
1.384     raeburn  4299: #                 type     - optional parameter for selection 
1.418     raeburn  4300: #                 regexp_ok - if 1 or -1 allow the supplied institutional code
                   4301: #                            filter to behave as a regular expression:
                   4302: #	                      1 will not exclude the course if the instcode matches the RE 
                   4303: #                            -1 will exclude the course if the instcode matches the RE
1.384     raeburn  4304: #                 rtn_as_hash - whether to return the information available for
                   4305: #                            each matched item as a frozen hash of all 
                   4306: #                            key, value pairs in the item's hash, or as a 
                   4307: #                            colon-separated list of (in order) description,
                   4308: #                            institutional code, and course owner.
1.404     raeburn  4309: #                 selfenrollonly - filter by courses allowing self-enrollment  
                   4310: #                                  now or in the future (selfenrollonly = 1).
                   4311: #                 catfilter - filter by course category, assigned to a course 
                   4312: #                             using manually defined categories (i.e., not
1.407     raeburn  4313: #                             self-cataloging based on on institutional code).   
1.404     raeburn  4314: #                 showhidden - include course in results even if course  
1.407     raeburn  4315: #                              was set to be excluded from course catalog (DC only).
1.404     raeburn  4316: #                 caller -  if set to 'coursecatalog', courses set to be hidden
                   4317: #                           from course catalog will be excluded from results (unless
                   4318: #                           overridden by "showhidden".
1.427     raeburn  4319: #                 cloner - escaped username:domain of course cloner (if picking course to
1.419     raeburn  4320: #                          clone).
                   4321: #                 cc_clone_list - escaped comma separated list of courses for which 
                   4322: #                                 course cloner has active CC role (and so can clone
                   4323: #                                 automatically).
1.427     raeburn  4324: #                 cloneonly - filter by courses for which cloner has rights to clone.
                   4325: #                 createdbefore - include courses for which creation date preceeded this date.
                   4326: #                 createdafter - include courses for which creation date followed this date.
                   4327: #                 creationcontext - include courses created in specified context 
1.404     raeburn  4328: #
1.445     raeburn  4329: #                 domcloner - flag to indicate if user can create CCs in course's domain.
1.505     raeburn  4330: #                             If so, ability to clone course is automatic.
                   4331: #                 hasuniquecode - filter by courses for which a six character unique code has 
                   4332: #                                 been set.
1.445     raeburn  4333: #
1.234     foxr     4334: #     $client  - The socket open on the client.
                   4335: # Returns:
                   4336: #    1     - Continue processing.
                   4337: # Side Effects:
                   4338: #   a reply is written to $client.
                   4339: sub dump_course_id_handler {
                   4340:     my ($cmd, $tail, $client) = @_;
1.494     droeschl 4341: 
                   4342:     my $res = LONCAPA::Lond::dump_course_id_handler($tail);
                   4343:     if ($res =~ /^error:/) {
                   4344:         Failure($client, \$res, "$cmd:$tail");
                   4345:     } else {
                   4346:         Reply($client, \$res, "$cmd:$tail");
                   4347:     }
                   4348: 
                   4349:     return 1;  
                   4350: 
                   4351:     #TODO remove
1.234     foxr     4352:     my $userinput = "$cmd:$tail";
                   4353: 
1.333     raeburn  4354:     my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter,
1.404     raeburn  4355:         $typefilter,$regexp_ok,$rtn_as_hash,$selfenrollonly,$catfilter,$showhidden,
1.427     raeburn  4356:         $caller,$cloner,$cc_clone_list,$cloneonly,$createdbefore,$createdafter,
1.505     raeburn  4357:         $creationcontext,$domcloner,$hasuniquecode) =split(/:/,$tail);
1.397     raeburn  4358:     my $now = time;
1.419     raeburn  4359:     my ($cloneruname,$clonerudom,%cc_clone);
1.234     foxr     4360:     if (defined($description)) {
                   4361: 	$description=&unescape($description);
                   4362:     } else {
                   4363: 	$description='.';
                   4364:     }
1.266     raeburn  4365:     if (defined($instcodefilter)) {
                   4366:         $instcodefilter=&unescape($instcodefilter);
                   4367:     } else {
                   4368:         $instcodefilter='.';
                   4369:     }
1.336     raeburn  4370:     my ($ownerunamefilter,$ownerdomfilter);
1.266     raeburn  4371:     if (defined($ownerfilter)) {
                   4372:         $ownerfilter=&unescape($ownerfilter);
1.336     raeburn  4373:         if ($ownerfilter ne '.' && defined($ownerfilter)) {
                   4374:             if ($ownerfilter =~ /^([^:]*):([^:]*)$/) {
                   4375:                  $ownerunamefilter = $1;
                   4376:                  $ownerdomfilter = $2;
                   4377:             } else {
                   4378:                 $ownerunamefilter = $ownerfilter;
                   4379:                 $ownerdomfilter = '';
                   4380:             }
                   4381:         }
1.266     raeburn  4382:     } else {
                   4383:         $ownerfilter='.';
                   4384:     }
1.336     raeburn  4385: 
1.282     raeburn  4386:     if (defined($coursefilter)) {
                   4387:         $coursefilter=&unescape($coursefilter);
                   4388:     } else {
                   4389:         $coursefilter='.';
                   4390:     }
1.333     raeburn  4391:     if (defined($typefilter)) {
                   4392:         $typefilter=&unescape($typefilter);
                   4393:     } else {
                   4394:         $typefilter='.';
                   4395:     }
1.344     raeburn  4396:     if (defined($regexp_ok)) {
                   4397:         $regexp_ok=&unescape($regexp_ok);
                   4398:     }
1.401     raeburn  4399:     if (defined($catfilter)) {
                   4400:         $catfilter=&unescape($catfilter);
                   4401:     }
1.419     raeburn  4402:     if (defined($cloner)) {
                   4403:         $cloner = &unescape($cloner);
                   4404:         ($cloneruname,$clonerudom) = ($cloner =~ /^($LONCAPA::match_username):($LONCAPA::match_domain)$/); 
                   4405:     }
                   4406:     if (defined($cc_clone_list)) {
                   4407:         $cc_clone_list = &unescape($cc_clone_list);
                   4408:         my @cc_cloners = split('&',$cc_clone_list);
                   4409:         foreach my $cid (@cc_cloners) {
                   4410:             my ($clonedom,$clonenum) = split(':',$cid);
                   4411:             next if ($clonedom ne $udom); 
                   4412:             $cc_clone{$clonedom.'_'.$clonenum} = 1;
                   4413:         } 
                   4414:     }
1.431     raeburn  4415:     if ($createdbefore ne '') {
1.427     raeburn  4416:         $createdbefore = &unescape($createdbefore);
                   4417:     } else {
                   4418:        $createdbefore = 0;
                   4419:     }
1.431     raeburn  4420:     if ($createdafter ne '') {
1.427     raeburn  4421:         $createdafter = &unescape($createdafter);
                   4422:     } else {
                   4423:         $createdafter = 0;
                   4424:     }
1.431     raeburn  4425:     if ($creationcontext ne '') {
1.427     raeburn  4426:         $creationcontext = &unescape($creationcontext);
                   4427:     } else {
                   4428:         $creationcontext = '.';
                   4429:     }
1.505     raeburn  4430:     unless ($hasuniquecode) {
                   4431:         $hasuniquecode = '.';
                   4432:     }
1.384     raeburn  4433:     my $unpack = 1;
1.485     raeburn  4434:     if ($description eq '.' && $instcodefilter eq '.' && $ownerfilter eq '.' && 
1.384     raeburn  4435:         $typefilter eq '.') {
                   4436:         $unpack = 0;
                   4437:     }
                   4438:     if (!defined($since)) { $since=0; }
1.234     foxr     4439:     my $qresult='';
                   4440:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   4441:     if ($hashref) {
1.384     raeburn  4442: 	while (my ($key,$value) = each(%$hashref)) {
1.397     raeburn  4443:             my ($unesc_key,$lasttime_key,$lasttime,$is_hash,%val,
1.427     raeburn  4444:                 %unesc_val,$selfenroll_end,$selfenroll_types,$created,
                   4445:                 $context);
1.384     raeburn  4446:             $unesc_key = &unescape($key);
                   4447:             if ($unesc_key =~ /^lasttime:/) {
                   4448:                 next;
                   4449:             } else {
                   4450:                 $lasttime_key = &escape('lasttime:'.$unesc_key);
                   4451:             }
                   4452:             if ($hashref->{$lasttime_key} ne '') {
                   4453:                 $lasttime = $hashref->{$lasttime_key};
                   4454:                 next if ($lasttime<$since);
                   4455:             }
1.419     raeburn  4456:             my ($canclone,$valchange);
1.384     raeburn  4457:             my $items = &Apache::lonnet::thaw_unescape($value);
                   4458:             if (ref($items) eq 'HASH') {
1.429     raeburn  4459:                 if ($hashref->{$lasttime_key} eq '') {
1.430     raeburn  4460:                     next if ($since > 1);
1.429     raeburn  4461:                 }
1.384     raeburn  4462:                 $is_hash =  1;
1.445     raeburn  4463:                 if ($domcloner) {
                   4464:                     $canclone = 1;
                   4465:                 } elsif (defined($clonerudom)) {
1.419     raeburn  4466:                     if ($items->{'cloners'}) {
                   4467:                         my @cloneable = split(',',$items->{'cloners'});
                   4468:                         if (@cloneable) {
                   4469:                             if (grep(/^\*$/,@cloneable))  {
                   4470:                                 $canclone = 1;
                   4471:                             } elsif (grep(/^\*:\Q$clonerudom\E$/,@cloneable)) {
                   4472:                                 $canclone = 1;
                   4473:                             } elsif (grep(/^\Q$cloneruname\E:\Q$clonerudom\E$/,@cloneable)) {
                   4474:                                 $canclone = 1;
                   4475:                             }
                   4476:                         }
                   4477:                         unless ($canclone) {
                   4478:                             if ($cloneruname ne '' && $clonerudom ne '') {
                   4479:                                 if ($cc_clone{$unesc_key}) {
                   4480:                                     $canclone = 1;
                   4481:                                     $items->{'cloners'} .= ','.$cloneruname.':'.
                   4482:                                                            $clonerudom;
                   4483:                                     $valchange = 1;
                   4484:                                 }
                   4485:                             }
                   4486:                         }
                   4487:                     } elsif (defined($cloneruname)) {
                   4488:                         if ($cc_clone{$unesc_key}) {
                   4489:                             $canclone = 1;
                   4490:                             $items->{'cloners'} = $cloneruname.':'.$clonerudom;
                   4491:                             $valchange = 1;
                   4492:                         }
1.437     raeburn  4493:                         unless ($canclone) {
                   4494:                             if ($items->{'owner'} =~ /:/) {
                   4495:                                 if ($items->{'owner'} eq $cloner) {
                   4496:                                     $canclone = 1;
                   4497:                                 }
1.444     raeburn  4498:                             } elsif ($cloner eq $items->{'owner'}.':'.$udom) {
1.437     raeburn  4499:                                 $canclone = 1;
                   4500:                             }
                   4501:                             if ($canclone) {
                   4502:                                 $items->{'cloners'} = $cloneruname.':'.$clonerudom;
                   4503:                                 $valchange = 1;
                   4504:                             }
                   4505:                         }
1.419     raeburn  4506:                     }
                   4507:                 }
1.384     raeburn  4508:                 if ($unpack || !$rtn_as_hash) {
                   4509:                     $unesc_val{'descr'} = $items->{'description'};
                   4510:                     $unesc_val{'inst_code'} = $items->{'inst_code'};
                   4511:                     $unesc_val{'owner'} = $items->{'owner'};
                   4512:                     $unesc_val{'type'} = $items->{'type'};
1.419     raeburn  4513:                     $unesc_val{'cloners'} = $items->{'cloners'};
1.427     raeburn  4514:                     $unesc_val{'created'} = $items->{'created'};
                   4515:                     $unesc_val{'context'} = $items->{'context'};
1.404     raeburn  4516:                 }
                   4517:                 $selfenroll_types = $items->{'selfenroll_types'};
                   4518:                 $selfenroll_end = $items->{'selfenroll_end_date'};
1.427     raeburn  4519:                 $created = $items->{'created'};
                   4520:                 $context = $items->{'context'};
1.505     raeburn  4521:                 if ($hasuniquecode ne '.') {
                   4522:                     next unless ($items->{'uniquecode'});
                   4523:                 }
1.404     raeburn  4524:                 if ($selfenrollonly) {
                   4525:                     next if (!$selfenroll_types);
                   4526:                     if (($selfenroll_end > 0) && ($selfenroll_end <= $now)) {
                   4527:                         next;
1.397     raeburn  4528:                     }
1.404     raeburn  4529:                 }
1.427     raeburn  4530:                 if ($creationcontext ne '.') {
                   4531:                     next if (($context ne '') && ($context ne $creationcontext));  
                   4532:                 }
                   4533:                 if ($createdbefore > 0) {
                   4534:                     next if (($created eq '') || ($created > $createdbefore));   
                   4535:                 }
                   4536:                 if ($createdafter > 0) {
                   4537:                     next if (($created eq '') || ($created <= $createdafter)); 
                   4538:                 }
1.404     raeburn  4539:                 if ($catfilter ne '') {
1.406     raeburn  4540:                     next if ($items->{'categories'} eq '');
                   4541:                     my @categories = split('&',$items->{'categories'}); 
1.407     raeburn  4542:                     next if (@categories == 0);
                   4543:                     my @subcats = split('&',$catfilter);
                   4544:                     my $matchcat = 0;
                   4545:                     foreach my $cat (@categories) {
                   4546:                         if (grep(/^\Q$cat\E$/,@subcats)) {
                   4547:                             $matchcat = 1;
                   4548:                             last;
                   4549:                         }
                   4550:                     }
                   4551:                     next if (!$matchcat);
1.404     raeburn  4552:                 }
                   4553:                 if ($caller eq 'coursecatalog') {
1.405     raeburn  4554:                     if ($items->{'hidefromcat'} eq 'yes') {
                   4555:                         next if !$showhidden;
1.401     raeburn  4556:                     }
1.384     raeburn  4557:                 }
1.383     raeburn  4558:             } else {
1.401     raeburn  4559:                 next if ($catfilter ne '');
1.419     raeburn  4560:                 next if ($selfenrollonly);
1.427     raeburn  4561:                 next if ($createdbefore || $createdafter);
                   4562:                 next if ($creationcontext ne '.');
1.419     raeburn  4563:                 if ((defined($clonerudom)) && (defined($cloneruname)))  {
                   4564:                     if ($cc_clone{$unesc_key}) {
                   4565:                         $canclone = 1;
                   4566:                         $val{'cloners'} = &escape($cloneruname.':'.$clonerudom);
                   4567:                     }
                   4568:                 }
1.384     raeburn  4569:                 $is_hash =  0;
1.388     raeburn  4570:                 my @courseitems = split(/:/,$value);
1.403     raeburn  4571:                 $lasttime = pop(@courseitems);
1.402     raeburn  4572:                 if ($hashref->{$lasttime_key} eq '') {
                   4573:                     next if ($lasttime<$since);
                   4574:                 }
1.384     raeburn  4575: 	        ($val{'descr'},$val{'inst_code'},$val{'owner'},$val{'type'}) = @courseitems;
1.383     raeburn  4576:             }
1.419     raeburn  4577:             if ($cloneonly) {
                   4578:                next unless ($canclone);
                   4579:             }
1.266     raeburn  4580:             my $match = 1;
1.384     raeburn  4581: 	    if ($description ne '.') {
                   4582:                 if (!$is_hash) {
                   4583:                     $unesc_val{'descr'} = &unescape($val{'descr'});
                   4584:                 }
                   4585:                 if (eval{$unesc_val{'descr'} !~ /\Q$description\E/i}) {
1.266     raeburn  4586:                     $match = 0;
1.384     raeburn  4587:                 }
1.266     raeburn  4588:             }
1.384     raeburn  4589:             if ($instcodefilter ne '.') {
                   4590:                 if (!$is_hash) {
                   4591:                     $unesc_val{'inst_code'} = &unescape($val{'inst_code'});
                   4592:                 }
1.418     raeburn  4593:                 if ($regexp_ok == 1) {
1.384     raeburn  4594:                     if (eval{$unesc_val{'inst_code'} !~ /$instcodefilter/}) {
1.344     raeburn  4595:                         $match = 0;
                   4596:                     }
1.418     raeburn  4597:                 } elsif ($regexp_ok == -1) {
                   4598:                     if (eval{$unesc_val{'inst_code'} =~ /$instcodefilter/}) {
                   4599:                         $match = 0;
                   4600:                     }
1.344     raeburn  4601:                 } else {
1.384     raeburn  4602:                     if (eval{$unesc_val{'inst_code'} !~ /\Q$instcodefilter\E/i}) {
1.344     raeburn  4603:                         $match = 0;
                   4604:                     }
1.266     raeburn  4605:                 }
1.234     foxr     4606: 	    }
1.384     raeburn  4607:             if ($ownerfilter ne '.') {
                   4608:                 if (!$is_hash) {
                   4609:                     $unesc_val{'owner'} = &unescape($val{'owner'});
                   4610:                 }
1.336     raeburn  4611:                 if (($ownerunamefilter ne '') && ($ownerdomfilter ne '')) {
1.384     raeburn  4612:                     if ($unesc_val{'owner'} =~ /:/) {
                   4613:                         if (eval{$unesc_val{'owner'} !~ 
                   4614:                              /\Q$ownerunamefilter\E:\Q$ownerdomfilter\E$/i}) {
1.336     raeburn  4615:                             $match = 0;
                   4616:                         } 
                   4617:                     } else {
1.384     raeburn  4618:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336     raeburn  4619:                             $match = 0;
                   4620:                         }
                   4621:                     }
                   4622:                 } elsif ($ownerunamefilter ne '') {
1.384     raeburn  4623:                     if ($unesc_val{'owner'} =~ /:/) {
                   4624:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E:[^:]+$/i}) {
1.336     raeburn  4625:                              $match = 0;
                   4626:                         }
                   4627:                     } else {
1.384     raeburn  4628:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336     raeburn  4629:                             $match = 0;
                   4630:                         }
                   4631:                     }
                   4632:                 } elsif ($ownerdomfilter ne '') {
1.384     raeburn  4633:                     if ($unesc_val{'owner'} =~ /:/) {
                   4634:                         if (eval{$unesc_val{'owner'} !~ /^[^:]+:\Q$ownerdomfilter\E/}) {
1.336     raeburn  4635:                              $match = 0;
                   4636:                         }
                   4637:                     } else {
                   4638:                         if ($ownerdomfilter ne $udom) {
                   4639:                             $match = 0;
                   4640:                         }
                   4641:                     }
1.266     raeburn  4642:                 }
                   4643:             }
1.384     raeburn  4644:             if ($coursefilter ne '.') {
                   4645:                 if (eval{$unesc_key !~ /^$udom(_)\Q$coursefilter\E$/}) {
1.282     raeburn  4646:                     $match = 0;
                   4647:                 }
                   4648:             }
1.384     raeburn  4649:             if ($typefilter ne '.') {
                   4650:                 if (!$is_hash) {
                   4651:                     $unesc_val{'type'} = &unescape($val{'type'});
                   4652:                 }
                   4653:                 if ($unesc_val{'type'} eq '') {
1.333     raeburn  4654:                     if ($typefilter ne 'Course') {
                   4655:                         $match = 0;
                   4656:                     }
1.383     raeburn  4657:                 } else {
1.384     raeburn  4658:                     if (eval{$unesc_val{'type'} !~ /^\Q$typefilter\E$/}) {
1.333     raeburn  4659:                         $match = 0;
                   4660:                     }
                   4661:                 }
                   4662:             }
1.266     raeburn  4663:             if ($match == 1) {
1.384     raeburn  4664:                 if ($rtn_as_hash) {
                   4665:                     if ($is_hash) {
1.419     raeburn  4666:                         if ($valchange) {
                   4667:                             my $newvalue = &Apache::lonnet::freeze_escape($items);
                   4668:                             $qresult.=$key.'='.$newvalue.'&';
                   4669:                         } else {
                   4670:                             $qresult.=$key.'='.$value.'&';
                   4671:                         }
1.384     raeburn  4672:                     } else {
1.388     raeburn  4673:                         my %rtnhash = ( 'description' => &unescape($val{'descr'}),
                   4674:                                         'inst_code' => &unescape($val{'inst_code'}),
                   4675:                                         'owner'     => &unescape($val{'owner'}),
                   4676:                                         'type'      => &unescape($val{'type'}),
1.419     raeburn  4677:                                         'cloners'   => &unescape($val{'cloners'}),
1.384     raeburn  4678:                                       );
                   4679:                         my $items = &Apache::lonnet::freeze_escape(\%rtnhash);
                   4680:                         $qresult.=$key.'='.$items.'&';
                   4681:                     }
1.383     raeburn  4682:                 } else {
1.384     raeburn  4683:                     if ($is_hash) {
                   4684:                         $qresult .= $key.'='.&escape($unesc_val{'descr'}).':'.
                   4685:                                     &escape($unesc_val{'inst_code'}).':'.
                   4686:                                     &escape($unesc_val{'owner'}).'&';
                   4687:                     } else {
                   4688:                         $qresult .= $key.'='.$val{'descr'}.':'.$val{'inst_code'}.
                   4689:                                     ':'.$val{'owner'}.'&';
                   4690:                     }
1.383     raeburn  4691:                 }
1.266     raeburn  4692:             }
1.234     foxr     4693: 	}
1.311     albertel 4694: 	if (&untie_domain_hash($hashref)) {
1.234     foxr     4695: 	    chop($qresult);
1.387     albertel 4696: 	    &Reply($client, \$qresult, $userinput);
1.234     foxr     4697: 	} else {
                   4698: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4699: 		    "while attempting courseiddump\n", $userinput);
                   4700: 	}
                   4701:     } else {
                   4702: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4703: 		"while attempting courseiddump\n", $userinput);
                   4704:     }
                   4705:     return 1;
                   4706: }
                   4707: &register_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
1.238     foxr     4708: 
1.438     raeburn  4709: sub course_lastaccess_handler {
                   4710:     my ($cmd, $tail, $client) = @_;
                   4711:     my $userinput = "$cmd:$tail";
                   4712:     my ($cdom,$cnum) = split(':',$tail); 
                   4713:     my (%lastaccess,$qresult);
                   4714:     my $hashref = &tie_domain_hash($cdom, "nohist_courseids", &GDBM_WRCREAT());
                   4715:     if ($hashref) {
                   4716:         while (my ($key,$value) = each(%$hashref)) {
                   4717:             my ($unesc_key,$lasttime);
                   4718:             $unesc_key = &unescape($key);
                   4719:             if ($cnum) {
                   4720:                 next unless ($unesc_key =~ /\Q$cdom\E_\Q$cnum\E$/);
                   4721:             }
                   4722:             if ($unesc_key =~ /^lasttime:($LONCAPA::match_domain\_$LONCAPA::match_courseid)/) {
                   4723:                 $lastaccess{$1} = $value;
                   4724:             } else {
                   4725:                 my $items = &Apache::lonnet::thaw_unescape($value);
                   4726:                 if (ref($items) eq 'HASH') {
                   4727:                     unless ($lastaccess{$unesc_key}) {
                   4728:                         $lastaccess{$unesc_key} = '';
                   4729:                     }
                   4730:                 } else {
                   4731:                     my @courseitems = split(':',$value);
                   4732:                     $lastaccess{$unesc_key} = pop(@courseitems);
                   4733:                 }
                   4734:             }
                   4735:         }
                   4736:         foreach my $cid (sort(keys(%lastaccess))) {
                   4737:             $qresult.=&escape($cid).'='.$lastaccess{$cid}.'&'; 
                   4738:         }
                   4739:         if (&untie_domain_hash($hashref)) {
                   4740:             if ($qresult) {
                   4741:                 chop($qresult);
                   4742:             }
                   4743:             &Reply($client, \$qresult, $userinput);
                   4744:         } else {
                   4745:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4746:                     "while attempting lastacourseaccess\n", $userinput);
                   4747:         }
                   4748:     } else {
                   4749:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4750:                 "while attempting lastcourseaccess\n", $userinput);
                   4751:     }
                   4752:     return 1;
                   4753: }
                   4754: &register_handler("courselastaccess",\&course_lastaccess_handler, 0, 1, 0);
                   4755: 
1.238     foxr     4756: #
1.348     raeburn  4757: # Puts an unencrypted entry in a namespace db file at the domain level 
                   4758: #
                   4759: # Parameters:
                   4760: #    $cmd      - The command that got us here.
                   4761: #    $tail     - Tail of the command (remaining parameters).
                   4762: #    $client   - File descriptor connected to client.
                   4763: # Returns
                   4764: #     0        - Requested to exit, caller should shut down.
                   4765: #     1        - Continue processing.
                   4766: #  Side effects:
                   4767: #     reply is written to $client.
                   4768: #
                   4769: sub put_domain_handler {
                   4770:     my ($cmd,$tail,$client) = @_;
                   4771: 
                   4772:     my $userinput = "$cmd:$tail";
                   4773: 
                   4774:     my ($udom,$namespace,$what) =split(/:/,$tail,3);
                   4775:     chomp($what);
                   4776:     my @pairs=split(/\&/,$what);
                   4777:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_WRCREAT(),
                   4778:                                    "P", $what);
                   4779:     if ($hashref) {
                   4780:         foreach my $pair (@pairs) {
                   4781:             my ($key,$value)=split(/=/,$pair);
                   4782:             $hashref->{$key}=$value;
                   4783:         }
                   4784:         if (&untie_domain_hash($hashref)) {
                   4785:             &Reply($client, "ok\n", $userinput);
                   4786:         } else {
                   4787:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4788:                      "while attempting putdom\n", $userinput);
                   4789:         }
                   4790:     } else {
                   4791:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4792:                   "while attempting putdom\n", $userinput);
                   4793:     }
                   4794: 
                   4795:     return 1;
                   4796: }
                   4797: &register_handler("putdom", \&put_domain_handler, 0, 1, 0);
                   4798: 
1.517     raeburn  4799: # Updates one or more entries in clickers.db file at the domain level
                   4800: #
                   4801: # Parameters:
                   4802: #    $cmd      - The command that got us here.
                   4803: #    $tail     - Tail of the command (remaining parameters).
                   4804: #                In this case a colon separated list containing:
                   4805: #                (a) the domain for which we are updating the entries,
                   4806: #                (b) the action required -- add or del -- and
                   4807: #                (c) a &-separated list of entries to add or delete.
                   4808: #    $client   - File descriptor connected to client.
                   4809: # Returns
                   4810: #     1        - Continue processing.
                   4811: #     0        - Requested to exit, caller should shut down.
                   4812: #  Side effects:
                   4813: #     reply is written to $client.
                   4814: #
                   4815: 
                   4816: 
                   4817: sub update_clickers {
                   4818:     my ($cmd, $tail, $client)  = @_;
                   4819: 
                   4820:     my $userinput = "$cmd:$tail";
                   4821:     my ($udom,$action,$what) =split(/:/,$tail,3);
                   4822:     chomp($what);
                   4823: 
                   4824:     my $hashref = &tie_domain_hash($udom, "clickers", &GDBM_WRCREAT(),
                   4825:                                  "U","$action:$what");
                   4826: 
                   4827:     if (!$hashref) {
                   4828:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4829:                   "while attempting updateclickers\n", $userinput);
                   4830:         return 1;
                   4831:     }
                   4832: 
                   4833:     my @pairs=split(/\&/,$what);
                   4834:     foreach my $pair (@pairs) {
                   4835:         my ($key,$value)=split(/=/,$pair);
                   4836:         if ($action eq 'add') {
                   4837:             if (exists($hashref->{$key})) {
                   4838:                 my @newvals = split(/,/,&unescape($value));
                   4839:                 my @currvals = split(/,/,&unescape($hashref->{$key}));
                   4840:                 my @merged = sort(keys(%{{map { $_ => 1 } (@newvals,@currvals)}}));
                   4841:                 $hashref->{$key}=&escape(join(',',@merged));
                   4842:             } else {
                   4843:                 $hashref->{$key}=$value;
                   4844:             }
                   4845:         } elsif ($action eq 'del') {
                   4846:             if (exists($hashref->{$key})) {
                   4847:                 my %current;
                   4848:                 map { $current{$_} = 1; } split(/,/,&unescape($hashref->{$key}));
                   4849:                 map { delete($current{$_}); } split(/,/,&unescape($value));
                   4850:                 if (keys(%current)) {
                   4851:                     $hashref->{$key}=&escape(join(',',sort(keys(%current))));
                   4852:                 } else {
                   4853:                     delete($hashref->{$key});
                   4854:                 }
                   4855:             }
                   4856:         }
                   4857:     }
                   4858:     if (&untie_user_hash($hashref)) {
                   4859:         &Reply( $client, "ok\n", $userinput);
                   4860:     } else {
                   4861:         &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   4862:                  "while attempting put\n",
                   4863:                  $userinput);
                   4864:     }
                   4865:     return 1;
                   4866: }
                   4867: &register_handler("updateclickers", \&update_clickers, 0, 1, 0);
                   4868: 
                   4869: 
                   4870: # Deletes one or more entries in a namespace db file at the domain level
                   4871: #
                   4872: # Parameters:
                   4873: #    $cmd      - The command that got us here.
                   4874: #    $tail     - Tail of the command (remaining parameters).
                   4875: #                In this case a colon separated list containing:
                   4876: #                (a) the domain for which we are deleting the entries,
                   4877: #                (b) &-separated list of keys to delete.  
                   4878: #    $client   - File descriptor connected to client.
                   4879: # Returns
                   4880: #     1        - Continue processing.
                   4881: #     0        - Requested to exit, caller should shut down.
                   4882: #  Side effects:
                   4883: #     reply is written to $client.
                   4884: #
                   4885: 
                   4886: sub del_domain_handler {
                   4887:     my ($cmd,$tail,$client) = @_;
                   4888: 
                   4889:     my $userinput = "$cmd:$tail";
                   4890: 
                   4891:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   4892:     chomp($what);
                   4893:     my $hashref = &tie_domain_hash($udom,$namespace,&GDBM_WRCREAT(),
                   4894:                                    "D", $what);
                   4895:     if ($hashref) {
                   4896:         my @keys=split(/\&/,$what);
                   4897:         foreach my $key (@keys) {
                   4898:             delete($hashref->{$key});
                   4899:         }
                   4900:         if (&untie_user_hash($hashref)) {
                   4901:             &Reply($client, "ok\n", $userinput);
                   4902:         } else {
                   4903:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4904:                     "while attempting deldom\n", $userinput);
                   4905:         }
                   4906:     } else {
                   4907:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4908:                  "while attempting deldom\n", $userinput);
                   4909:     }
                   4910:     return 1;
                   4911: }
                   4912: &register_handler("deldom", \&del_domain_handler, 0, 1, 0);
                   4913: 
                   4914: 
1.348     raeburn  4915: # Unencrypted get from the namespace database file at the domain level.
                   4916: # This function retrieves a keyed item from a specific named database in the
                   4917: # domain directory.
                   4918: #
                   4919: # Parameters:
                   4920: #   $cmd             - Command request keyword (get).
                   4921: #   $tail            - Tail of the command.  This is a colon separated list
                   4922: #                      consisting of the domain and the 'namespace' 
                   4923: #                      which selects the gdbm file to do the lookup in,
                   4924: #                      & separated list of keys to lookup.  Note that
                   4925: #                      the values are returned as an & separated list too.
                   4926: #   $client          - File descriptor open on the client.
                   4927: # Returns:
                   4928: #   1       - Continue processing.
                   4929: #   0       - Exit.
                   4930: #  Side effects:
                   4931: #     reply is written to $client.
                   4932: #
                   4933: 
                   4934: sub get_domain_handler {
                   4935:     my ($cmd, $tail, $client) = @_;
                   4936: 
1.461     foxr     4937: 
1.536     raeburn  4938:     my $userinput = "$cmd:$tail";
                   4939: 
                   4940:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   4941:     chomp($what);
                   4942:     if ($namespace =~ /^enc/) {
                   4943:         &Failure( $client, "refused\n", $userinput);
                   4944:     } else {
                   4945:         my @queries=split(/\&/,$what);
                   4946:         my $qresult='';
                   4947:         my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_READER());
                   4948:         if ($hashref) {
                   4949:             for (my $i=0;$i<=$#queries;$i++) {
                   4950:                 $qresult.="$hashref->{$queries[$i]}&";
                   4951:             }
                   4952:             if (&untie_domain_hash($hashref)) {
                   4953:                 $qresult=~s/\&$//;
                   4954:                 &Reply($client, \$qresult, $userinput);
                   4955:             } else {
                   4956:                 &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4957:                           "while attempting getdom\n",$userinput);
                   4958:             }
                   4959:         } else {
                   4960:             &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4961:                      "while attempting getdom\n",$userinput);
                   4962:         }
                   4963:     }
                   4964: 
                   4965:     return 1;
                   4966: }
                   4967: &register_handler("getdom", \&get_domain_handler, 0, 1, 0);
                   4968: 
                   4969: sub encrypted_get_domain_handler {
                   4970:     my ($cmd, $tail, $client) = @_;
                   4971: 
                   4972:     my $userinput = "$cmd:$tail";
1.348     raeburn  4973: 
                   4974:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   4975:     chomp($what);
                   4976:     my @queries=split(/\&/,$what);
                   4977:     my $qresult='';
                   4978:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_READER());
                   4979:     if ($hashref) {
                   4980:         for (my $i=0;$i<=$#queries;$i++) {
                   4981:             $qresult.="$hashref->{$queries[$i]}&";
                   4982:         }
                   4983:         if (&untie_domain_hash($hashref)) {
                   4984:             $qresult=~s/\&$//;
1.536     raeburn  4985:             if ($cipher) {
                   4986:                 my $cmdlength=length($qresult);
                   4987:                 $qresult.="         ";
                   4988:                 my $encqresult='';
                   4989:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   4990:                     $encqresult.= unpack("H16",
                   4991:                                          $cipher->encrypt(substr($qresult,
                   4992:                                                                  $encidx,
                   4993:                                                                  8)));
                   4994:                 }
                   4995:                 &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
                   4996:             } else {
                   4997:                 &Failure( $client, "error:no_key\n", $userinput);
                   4998:             }
1.348     raeburn  4999:         } else {
                   5000:             &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
1.536     raeburn  5001:                       "while attempting egetdom\n",$userinput);
1.348     raeburn  5002:         }
                   5003:     } else {
                   5004:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
1.536     raeburn  5005:                  "while attempting egetdom\n",$userinput);
1.348     raeburn  5006:     }
                   5007:     return 1;
                   5008: }
1.536     raeburn  5009: &register_handler("egetdom", \&encrypted_get_domain_handler, 1, 1, 0);
1.348     raeburn  5010: 
1.420     raeburn  5011: #
1.238     foxr     5012: #  Puts an id to a domains id database. 
                   5013: #
                   5014: #  Parameters:
                   5015: #   $cmd     - The command that triggered us.
                   5016: #   $tail    - Remainder of the request other than the command. This is a 
                   5017: #              colon separated list containing:
                   5018: #              $domain  - The domain for which we are writing the id.
                   5019: #              $pairs  - The id info to write... this is and & separated list
                   5020: #                        of keyword=value.
                   5021: #   $client  - Socket open on the client.
                   5022: #  Returns:
                   5023: #    1   - Continue processing.
                   5024: #  Side effects:
                   5025: #     reply is written to $client.
                   5026: #
                   5027: sub put_id_handler {
                   5028:     my ($cmd,$tail,$client) = @_;
                   5029: 
                   5030: 
                   5031:     my $userinput = "$cmd:$tail";
                   5032: 
                   5033:     my ($udom,$what)=split(/:/,$tail);
                   5034:     chomp($what);
                   5035:     my @pairs=split(/\&/,$what);
                   5036:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   5037: 				   "P", $what);
                   5038:     if ($hashref) {
                   5039: 	foreach my $pair (@pairs) {
                   5040: 	    my ($key,$value)=split(/=/,$pair);
                   5041: 	    $hashref->{$key}=$value;
                   5042: 	}
1.311     albertel 5043: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     5044: 	    &Reply($client, "ok\n", $userinput);
                   5045: 	} else {
                   5046: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5047: 		     "while attempting idput\n", $userinput);
                   5048: 	}
                   5049:     } else {
                   5050: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5051: 		  "while attempting idput\n", $userinput);
                   5052:     }
                   5053: 
                   5054:     return 1;
                   5055: }
1.263     albertel 5056: &register_handler("idput", \&put_id_handler, 0, 1, 0);
1.238     foxr     5057: 
                   5058: #
                   5059: #  Retrieves a set of id values from the id database.
                   5060: #  Returns an & separated list of results, one for each requested id to the
                   5061: #  client.
                   5062: #
                   5063: # Parameters:
                   5064: #   $cmd       - Command keyword that caused us to be dispatched.
                   5065: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5066: #               domain - the domain whose id table we dump
                   5067: #               ids      Consists of an & separated list of
                   5068: #                        id keywords whose values will be fetched.
                   5069: #                        nonexisting keywords will have an empty value.
                   5070: #   $client    - Socket open on the client.
                   5071: #
                   5072: # Returns:
                   5073: #    1 - indicating processing should continue.
                   5074: # Side effects:
                   5075: #   An & separated list of results is written to $client.
                   5076: #
                   5077: sub get_id_handler {
                   5078:     my ($cmd, $tail, $client) = @_;
                   5079: 
                   5080:     
                   5081:     my $userinput = "$client:$tail";
                   5082:     
                   5083:     my ($udom,$what)=split(/:/,$tail);
                   5084:     chomp($what);
                   5085:     my @queries=split(/\&/,$what);
                   5086:     my $qresult='';
                   5087:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
                   5088:     if ($hashref) {
                   5089: 	for (my $i=0;$i<=$#queries;$i++) {
                   5090: 	    $qresult.="$hashref->{$queries[$i]}&";
                   5091: 	}
1.311     albertel 5092: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     5093: 	    $qresult=~s/\&$//;
1.387     albertel 5094: 	    &Reply($client, \$qresult, $userinput);
1.238     foxr     5095: 	} else {
                   5096: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5097: 		      "while attempting idget\n",$userinput);
                   5098: 	}
                   5099:     } else {
                   5100: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5101: 		 "while attempting idget\n",$userinput);
                   5102:     }
                   5103:     
                   5104:     return 1;
                   5105: }
1.263     albertel 5106: &register_handler("idget", \&get_id_handler, 0, 1, 0);
1.238     foxr     5107: 
1.501     raeburn  5108: #   Deletes one or more ids in a domain's id database.
                   5109: #
                   5110: #   Parameters:
                   5111: #       $cmd                  - Command keyword (iddel).
                   5112: #       $tail                 - Command tail.  In this case a colon
                   5113: #                               separated list containing:
                   5114: #                               The domain for which we are deleting the id(s).
                   5115: #                               &-separated list of id(s) to delete.
                   5116: #       $client               - File open on client socket.
                   5117: # Returns:
                   5118: #     1   - Continue processing
                   5119: #     0   - Exit server.
                   5120: #     
                   5121: #
                   5122: 
                   5123: sub del_id_handler {
                   5124:     my ($cmd,$tail,$client) = @_;
                   5125: 
                   5126:     my $userinput = "$cmd:$tail";
                   5127: 
                   5128:     my ($udom,$what)=split(/:/,$tail);
                   5129:     chomp($what);
                   5130:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   5131:                                    "D", $what);
                   5132:     if ($hashref) {
                   5133:         my @keys=split(/\&/,$what);
                   5134:         foreach my $key (@keys) {
                   5135:             delete($hashref->{$key});
                   5136:         }
                   5137:         if (&untie_user_hash($hashref)) {
                   5138:             &Reply($client, "ok\n", $userinput);
                   5139:         } else {
                   5140:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5141:                     "while attempting iddel\n", $userinput);
                   5142:         }
                   5143:     } else {
                   5144:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5145:                  "while attempting iddel\n", $userinput);
                   5146:     }
                   5147:     return 1;
                   5148: }
                   5149: &register_handler("iddel", \&del_id_handler, 0, 1, 0);
                   5150: 
1.238     foxr     5151: #
1.299     raeburn  5152: # Puts broadcast e-mail sent by Domain Coordinator in nohist_dcmail database 
                   5153: #
                   5154: # Parameters
                   5155: #   $cmd       - Command keyword that caused us to be dispatched.
                   5156: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5157: #               domain - the domain whose dcmail we are recording
                   5158: #               email    Consists of key=value pair 
                   5159: #                        where key is unique msgid
                   5160: #                        and value is message (in XML)
                   5161: #   $client    - Socket open on the client.
                   5162: #
                   5163: # Returns:
                   5164: #    1 - indicating processing should continue.
                   5165: # Side effects
                   5166: #     reply is written to $client.
                   5167: #
                   5168: sub put_dcmail_handler {
                   5169:     my ($cmd,$tail,$client) = @_;
                   5170:     my $userinput = "$cmd:$tail";
1.463     foxr     5171: 
                   5172: 
1.299     raeburn  5173:     my ($udom,$what)=split(/:/,$tail);
                   5174:     chomp($what);
                   5175:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   5176:     if ($hashref) {
                   5177:         my ($key,$value)=split(/=/,$what);
                   5178:         $hashref->{$key}=$value;
                   5179:     }
1.311     albertel 5180:     if (&untie_domain_hash($hashref)) {
1.299     raeburn  5181:         &Reply($client, "ok\n", $userinput);
                   5182:     } else {
                   5183:         &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5184:                  "while attempting dcmailput\n", $userinput);
                   5185:     }
                   5186:     return 1;
                   5187: }
                   5188: &register_handler("dcmailput", \&put_dcmail_handler, 0, 1, 0);
                   5189: 
                   5190: #
                   5191: # Retrieves broadcast e-mail from nohist_dcmail database
                   5192: # Returns to client an & separated list of key=value pairs,
                   5193: # where key is msgid and value is message information.
                   5194: #
                   5195: # Parameters
                   5196: #   $cmd       - Command keyword that caused us to be dispatched.
                   5197: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5198: #               domain - the domain whose dcmail table we dump
                   5199: #               startfilter - beginning of time window 
                   5200: #               endfilter - end of time window
                   5201: #               sendersfilter - & separated list of username:domain 
                   5202: #                 for senders to search for.
                   5203: #   $client    - Socket open on the client.
                   5204: #
                   5205: # Returns:
                   5206: #    1 - indicating processing should continue.
                   5207: # Side effects
                   5208: #     reply (& separated list of msgid=messageinfo pairs) is 
                   5209: #     written to $client.
                   5210: #
                   5211: sub dump_dcmail_handler {
                   5212:     my ($cmd, $tail, $client) = @_;
                   5213:                                                                                 
                   5214:     my $userinput = "$cmd:$tail";
                   5215:     my ($udom,$startfilter,$endfilter,$sendersfilter) = split(/:/,$tail);
                   5216:     chomp($sendersfilter);
                   5217:     my @senders = ();
                   5218:     if (defined($startfilter)) {
                   5219:         $startfilter=&unescape($startfilter);
                   5220:     } else {
                   5221:         $startfilter='.';
                   5222:     }
                   5223:     if (defined($endfilter)) {
                   5224:         $endfilter=&unescape($endfilter);
                   5225:     } else {
                   5226:         $endfilter='.';
                   5227:     }
                   5228:     if (defined($sendersfilter)) {
                   5229:         $sendersfilter=&unescape($sendersfilter);
1.300     albertel 5230: 	@senders = map { &unescape($_) } split(/\&/,$sendersfilter);
1.299     raeburn  5231:     }
                   5232: 
                   5233:     my $qresult='';
                   5234:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   5235:     if ($hashref) {
                   5236:         while (my ($key,$value) = each(%$hashref)) {
                   5237:             my $match = 1;
1.303     albertel 5238:             my ($timestamp,$subj,$uname,$udom) = 
                   5239: 		split(/:/,&unescape(&unescape($key)),5); # yes, twice really
1.299     raeburn  5240:             $subj = &unescape($subj);
                   5241:             unless ($startfilter eq '.' || !defined($startfilter)) {
                   5242:                 if ($timestamp < $startfilter) {
                   5243:                     $match = 0;
                   5244:                 }
                   5245:             }
                   5246:             unless ($endfilter eq '.' || !defined($endfilter)) {
                   5247:                 if ($timestamp > $endfilter) {
                   5248:                     $match = 0;
                   5249:                 }
                   5250:             }
                   5251:             unless (@senders < 1) {
                   5252:                 unless (grep/^$uname:$udom$/,@senders) {
                   5253:                     $match = 0;
                   5254:                 }
                   5255:             }
                   5256:             if ($match == 1) {
                   5257:                 $qresult.=$key.'='.$value.'&';
                   5258:             }
                   5259:         }
1.311     albertel 5260:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5261:             chop($qresult);
1.387     albertel 5262:             &Reply($client, \$qresult, $userinput);
1.299     raeburn  5263:         } else {
                   5264:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5265:                     "while attempting dcmaildump\n", $userinput);
                   5266:         }
                   5267:     } else {
                   5268:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5269:                 "while attempting dcmaildump\n", $userinput);
                   5270:     }
                   5271:     return 1;
                   5272: }
                   5273: 
                   5274: &register_handler("dcmaildump", \&dump_dcmail_handler, 0, 1, 0);
                   5275: 
                   5276: #
                   5277: # Puts domain roles in nohist_domainroles database
                   5278: #
                   5279: # Parameters
                   5280: #   $cmd       - Command keyword that caused us to be dispatched.
                   5281: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5282: #               domain - the domain whose roles we are recording  
                   5283: #               role -   Consists of key=value pair
                   5284: #                        where key is unique role
                   5285: #                        and value is start/end date information
                   5286: #   $client    - Socket open on the client.
                   5287: #
                   5288: # Returns:
                   5289: #    1 - indicating processing should continue.
                   5290: # Side effects
                   5291: #     reply is written to $client.
                   5292: #
                   5293: 
                   5294: sub put_domainroles_handler {
                   5295:     my ($cmd,$tail,$client) = @_;
                   5296: 
                   5297:     my $userinput = "$cmd:$tail";
                   5298:     my ($udom,$what)=split(/:/,$tail);
                   5299:     chomp($what);
                   5300:     my @pairs=split(/\&/,$what);
                   5301:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   5302:     if ($hashref) {
                   5303:         foreach my $pair (@pairs) {
                   5304:             my ($key,$value)=split(/=/,$pair);
                   5305:             $hashref->{$key}=$value;
                   5306:         }
1.311     albertel 5307:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5308:             &Reply($client, "ok\n", $userinput);
                   5309:         } else {
                   5310:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5311:                      "while attempting domroleput\n", $userinput);
                   5312:         }
                   5313:     } else {
                   5314:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5315:                   "while attempting domroleput\n", $userinput);
                   5316:     }
                   5317:                                                                                   
                   5318:     return 1;
                   5319: }
                   5320: 
                   5321: &register_handler("domroleput", \&put_domainroles_handler, 0, 1, 0);
                   5322: 
                   5323: #
                   5324: # Retrieves domain roles from nohist_domainroles database
                   5325: # Returns to client an & separated list of key=value pairs,
                   5326: # where key is role and value is start and end date information.
                   5327: #
                   5328: # Parameters
                   5329: #   $cmd       - Command keyword that caused us to be dispatched.
                   5330: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5331: #               domain - the domain whose domain roles table we dump
                   5332: #   $client    - Socket open on the client.
                   5333: #
                   5334: # Returns:
                   5335: #    1 - indicating processing should continue.
                   5336: # Side effects
                   5337: #     reply (& separated list of role=start/end info pairs) is
                   5338: #     written to $client.
                   5339: #
                   5340: sub dump_domainroles_handler {
                   5341:     my ($cmd, $tail, $client) = @_;
                   5342:                                                                                            
                   5343:     my $userinput = "$cmd:$tail";
                   5344:     my ($udom,$startfilter,$endfilter,$rolesfilter) = split(/:/,$tail);
                   5345:     chomp($rolesfilter);
                   5346:     my @roles = ();
                   5347:     if (defined($startfilter)) {
                   5348:         $startfilter=&unescape($startfilter);
                   5349:     } else {
                   5350:         $startfilter='.';
                   5351:     }
                   5352:     if (defined($endfilter)) {
                   5353:         $endfilter=&unescape($endfilter);
                   5354:     } else {
                   5355:         $endfilter='.';
                   5356:     }
                   5357:     if (defined($rolesfilter)) {
                   5358:         $rolesfilter=&unescape($rolesfilter);
1.300     albertel 5359: 	@roles = split(/\&/,$rolesfilter);
1.299     raeburn  5360:     }
1.421     raeburn  5361: 
1.299     raeburn  5362:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   5363:     if ($hashref) {
                   5364:         my $qresult = '';
                   5365:         while (my ($key,$value) = each(%$hashref)) {
                   5366:             my $match = 1;
1.421     raeburn  5367:             my ($end,$start) = split(/:/,&unescape($value));
1.299     raeburn  5368:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,&unescape($key));
1.421     raeburn  5369:             unless (@roles < 1) {
                   5370:                 unless (grep/^\Q$trole\E$/,@roles) {
                   5371:                     $match = 0;
                   5372:                     next;
                   5373:                 }
                   5374:             }
1.299     raeburn  5375:             unless ($startfilter eq '.' || !defined($startfilter)) {
1.415     raeburn  5376:                 if ((defined($start)) && ($start >= $startfilter)) {
1.299     raeburn  5377:                     $match = 0;
1.421     raeburn  5378:                     next;
1.299     raeburn  5379:                 }
                   5380:             }
                   5381:             unless ($endfilter eq '.' || !defined($endfilter)) {
1.421     raeburn  5382:                 if ((defined($end)) && (($end > 0) && ($end <= $endfilter))) {
1.299     raeburn  5383:                     $match = 0;
1.421     raeburn  5384:                     next;
1.299     raeburn  5385:                 }
                   5386:             }
                   5387:             if ($match == 1) {
                   5388:                 $qresult.=$key.'='.$value.'&';
                   5389:             }
                   5390:         }
1.311     albertel 5391:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5392:             chop($qresult);
1.387     albertel 5393:             &Reply($client, \$qresult, $userinput);
1.299     raeburn  5394:         } else {
                   5395:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5396:                     "while attempting domrolesdump\n", $userinput);
                   5397:         }
                   5398:     } else {
                   5399:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5400:                 "while attempting domrolesdump\n", $userinput);
                   5401:     }
                   5402:     return 1;
                   5403: }
                   5404: 
                   5405: &register_handler("domrolesdump", \&dump_domainroles_handler, 0, 1, 0);
                   5406: 
                   5407: 
1.238     foxr     5408: #  Process the tmpput command I'm not sure what this does.. Seems to
                   5409: #  create a file in the lonDaemons/tmp directory of the form $id.tmp
                   5410: # where Id is the client's ip concatenated with a sequence number.
                   5411: # The file will contain some value that is passed in.  Is this e.g.
                   5412: # a login token?
                   5413: #
                   5414: # Parameters:
                   5415: #    $cmd     - The command that got us dispatched.
                   5416: #    $tail    - The remainder of the request following $cmd:
                   5417: #               In this case this will be the contents of the file.
                   5418: #    $client  - Socket connected to the client.
                   5419: # Returns:
                   5420: #    1 indicating processing can continue.
                   5421: # Side effects:
                   5422: #   A file is created in the local filesystem.
                   5423: #   A reply is sent to the client.
                   5424: sub tmp_put_handler {
                   5425:     my ($cmd, $what, $client) = @_;
                   5426: 
                   5427:     my $userinput = "$cmd:$what";	# Reconstruct for logging.
                   5428: 
1.347     raeburn  5429:     my ($record,$context) = split(/:/,$what);
                   5430:     if ($context ne '') {
                   5431:         chomp($context);
                   5432:         $context = &unescape($context);
                   5433:     }
                   5434:     my ($id,$store);
1.238     foxr     5435:     $tmpsnum++;
1.454     raeburn  5436:     if (($context eq 'resetpw') || ($context eq 'createaccount')) {
1.347     raeburn  5437:         $id = &md5_hex(&md5_hex(time.{}.rand().$$));
                   5438:     } else {
                   5439:         $id = $$.'_'.$clientip.'_'.$tmpsnum;
                   5440:     }
1.238     foxr     5441:     $id=~s/\W/\_/g;
1.347     raeburn  5442:     $record=~s/\n//g;
1.238     foxr     5443:     my $execdir=$perlvar{'lonDaemons'};
                   5444:     if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
1.347     raeburn  5445: 	print $store $record;
1.238     foxr     5446: 	close $store;
1.387     albertel 5447: 	&Reply($client, \$id, $userinput);
1.238     foxr     5448:     } else {
                   5449: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   5450: 		  "while attempting tmpput\n", $userinput);
                   5451:     }
                   5452:     return 1;
                   5453:   
                   5454: }
                   5455: &register_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
1.263     albertel 5456: 
1.238     foxr     5457: #   Processes the tmpget command.  This command returns the contents
                   5458: #  of a temporary resource file(?) created via tmpput.
                   5459: #
                   5460: # Paramters:
                   5461: #    $cmd      - Command that got us dispatched.
                   5462: #    $id       - Tail of the command, contain the id of the resource
                   5463: #                we want to fetch.
                   5464: #    $client   - socket open on the client.
                   5465: # Return:
                   5466: #    1         - Inidcating processing can continue.
                   5467: # Side effects:
                   5468: #   A reply is sent to the client.
                   5469: #
                   5470: sub tmp_get_handler {
                   5471:     my ($cmd, $id, $client) = @_;
                   5472: 
                   5473:     my $userinput = "$cmd:$id"; 
                   5474:     
                   5475: 
                   5476:     $id=~s/\W/\_/g;
                   5477:     my $store;
                   5478:     my $execdir=$perlvar{'lonDaemons'};
                   5479:     if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
                   5480: 	my $reply=<$store>;
1.387     albertel 5481: 	&Reply( $client, \$reply, $userinput);
1.238     foxr     5482: 	close $store;
                   5483:     } else {
                   5484: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   5485: 		  "while attempting tmpget\n", $userinput);
                   5486:     }
                   5487: 
                   5488:     return 1;
                   5489: }
                   5490: &register_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
1.263     albertel 5491: 
1.238     foxr     5492: #
                   5493: #  Process the tmpdel command.  This command deletes a temp resource
                   5494: #  created by the tmpput command.
                   5495: #
                   5496: # Parameters:
                   5497: #   $cmd      - Command that got us here.
                   5498: #   $id       - Id of the temporary resource created.
                   5499: #   $client   - socket open on the client process.
                   5500: #
                   5501: # Returns:
                   5502: #   1     - Indicating processing should continue.
                   5503: # Side Effects:
                   5504: #   A file is deleted
                   5505: #   A reply is sent to the client.
                   5506: sub tmp_del_handler {
                   5507:     my ($cmd, $id, $client) = @_;
                   5508:     
                   5509:     my $userinput= "$cmd:$id";
                   5510:     
                   5511:     chomp($id);
                   5512:     $id=~s/\W/\_/g;
                   5513:     my $execdir=$perlvar{'lonDaemons'};
                   5514:     if (unlink("$execdir/tmp/$id.tmp")) {
                   5515: 	&Reply($client, "ok\n", $userinput);
                   5516:     } else {
                   5517: 	&Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
                   5518: 		  "while attempting tmpdel\n", $userinput);
                   5519:     }
                   5520:     
                   5521:     return 1;
                   5522: 
                   5523: }
                   5524: &register_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
1.263     albertel 5525: 
1.238     foxr     5526: #
1.551     raeburn  5527: #  Process the delbalcookie command. This command deletes a balancer
                   5528: #  cookie in the lonBalancedir directory created by switchserver
                   5529: #
                   5530: # Parameters:
                   5531: #   $cmd      - Command that got us here.
                   5532: #   $cookie   - Cookie to be deleted.
                   5533: #   $client   - socket open on the client process.
                   5534: #
                   5535: # Returns:
                   5536: #   1     - Indicating processing should continue.
                   5537: # Side Effects:
                   5538: #   A cookie file is deleted from the lonBalancedir directory
                   5539: #   A reply is sent to the client.
                   5540: sub del_balcookie_handler {
                   5541:     my ($cmd, $cookie, $client) = @_;
                   5542: 
                   5543:     my $userinput= "$cmd:$cookie";
                   5544: 
                   5545:     chomp($cookie);
                   5546:     my $deleted = '';
                   5547:     if ($cookie =~ /^$LONCAPA::match_domain\_$LONCAPA::match_username\_[a-f0-9]{32}$/) {
                   5548:         my $execdir=$perlvar{'lonBalanceDir'};
                   5549:         if (-e "$execdir/$cookie.id") {
                   5550:             if (open(my $fh,'<',"$execdir/$cookie.id")) {
                   5551:                 my $dodelete;
                   5552:                 while (my $line = <$fh>) {
                   5553:                     chomp($line);
                   5554:                     if ($line eq $clientname) {
                   5555:                         $dodelete = 1;
1.554     raeburn  5556:                         last;
1.551     raeburn  5557:                     }
                   5558:                 }
1.554     raeburn  5559:                 close($fh);
1.551     raeburn  5560:                 if ($dodelete) {
                   5561:                     if (unlink("$execdir/$cookie.id")) {
                   5562:                         $deleted = 1;
                   5563:                     }
                   5564:                 }
                   5565:             }
                   5566:         }
                   5567:     }
                   5568:     if ($deleted) {
                   5569:         &Reply($client, "ok\n", $userinput);
                   5570:     } else {
                   5571:         &Failure( $client, "error: ".($!+0)."Unlinking cookie file Failed ".
                   5572:                   "while attempting delbalcookie\n", $userinput);
                   5573:     }
                   5574:     return 1;
                   5575: }
                   5576: &register_handler("delbalcookie", \&del_balcookie_handler, 0, 1, 0);
                   5577: 
                   5578: #
1.246     foxr     5579: #   Processes the setannounce command.  This command
                   5580: #   creates a file named announce.txt in the top directory of
                   5581: #   the documentn root and sets its contents.  The announce.txt file is
                   5582: #   printed in its entirety at the LonCAPA login page.  Note:
                   5583: #   once the announcement.txt fileis created it cannot be deleted.
                   5584: #   However, setting the contents of the file to empty removes the
                   5585: #   announcement from the login page of loncapa so who cares.
                   5586: #
                   5587: # Parameters:
                   5588: #    $cmd          - The command that got us dispatched.
                   5589: #    $announcement - The text of the announcement.
                   5590: #    $client       - Socket open on the client process.
                   5591: # Retunrns:
                   5592: #   1             - Indicating request processing should continue
                   5593: # Side Effects:
                   5594: #   The file {DocRoot}/announcement.txt is created.
                   5595: #   A reply is sent to $client.
                   5596: #
                   5597: sub set_announce_handler {
                   5598:     my ($cmd, $announcement, $client) = @_;
                   5599:   
                   5600:     my $userinput    = "$cmd:$announcement";
                   5601: 
                   5602:     chomp($announcement);
                   5603:     $announcement=&unescape($announcement);
                   5604:     if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
                   5605: 				'/announcement.txt')) {
                   5606: 	print $store $announcement;
                   5607: 	close $store;
                   5608: 	&Reply($client, "ok\n", $userinput);
                   5609:     } else {
                   5610: 	&Failure($client, "error: ".($!+0)."\n", $userinput);
                   5611:     }
                   5612: 
                   5613:     return 1;
                   5614: }
                   5615: &register_handler("setannounce", \&set_announce_handler, 0, 1, 0);
1.263     albertel 5616: 
1.246     foxr     5617: #
                   5618: #  Return the version of the daemon.  This can be used to determine
                   5619: #  the compatibility of cross version installations or, alternatively to
                   5620: #  simply know who's out of date and who isn't.  Note that the version
                   5621: #  is returned concatenated with the tail.
                   5622: # Parameters:
                   5623: #   $cmd        - the request that dispatched to us.
                   5624: #   $tail       - Tail of the request (client's version?).
                   5625: #   $client     - Socket open on the client.
                   5626: #Returns:
                   5627: #   1 - continue processing requests.
                   5628: # Side Effects:
                   5629: #   Replies with version to $client.
                   5630: sub get_version_handler {
                   5631:     my ($cmd, $tail, $client) = @_;
                   5632: 
                   5633:     my $userinput  = $cmd.$tail;
                   5634:     
                   5635:     &Reply($client, &version($userinput)."\n", $userinput);
                   5636: 
                   5637: 
                   5638:     return 1;
                   5639: }
                   5640: &register_handler("version", \&get_version_handler, 0, 1, 0);
1.263     albertel 5641: 
1.246     foxr     5642: #  Set the current host and domain.  This is used to support
                   5643: #  multihomed systems.  Each IP of the system, or even separate daemons
                   5644: #  on the same IP can be treated as handling a separate lonCAPA virtual
                   5645: #  machine.  This command selects the virtual lonCAPA.  The client always
                   5646: #  knows the right one since it is lonc and it is selecting the domain/system
                   5647: #  from the hosts.tab file.
                   5648: # Parameters:
                   5649: #    $cmd      - Command that dispatched us.
                   5650: #    $tail     - Tail of the command (domain/host requested).
                   5651: #    $socket   - Socket open on the client.
                   5652: #
                   5653: # Returns:
                   5654: #     1   - Indicates the program should continue to process requests.
                   5655: # Side-effects:
                   5656: #     The default domain/system context is modified for this daemon.
                   5657: #     a reply is sent to the client.
                   5658: #
                   5659: sub set_virtual_host_handler {
                   5660:     my ($cmd, $tail, $socket) = @_;
                   5661:   
                   5662:     my $userinput  ="$cmd:$tail";
                   5663: 
                   5664:     &Reply($client, &sethost($userinput)."\n", $userinput);
                   5665: 
                   5666: 
                   5667:     return 1;
                   5668: }
1.247     albertel 5669: &register_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
1.246     foxr     5670: 
                   5671: #  Process a request to exit:
                   5672: #   - "bye" is sent to the client.
                   5673: #   - The client socket is shutdown and closed.
                   5674: #   - We indicate to the caller that we should exit.
                   5675: # Formal Parameters:
                   5676: #   $cmd                - The command that got us here.
                   5677: #   $tail               - Tail of the command (empty).
                   5678: #   $client             - Socket open on the tail.
                   5679: # Returns:
                   5680: #   0      - Indicating the program should exit!!
                   5681: #
                   5682: sub exit_handler {
                   5683:     my ($cmd, $tail, $client) = @_;
                   5684: 
                   5685:     my $userinput = "$cmd:$tail";
                   5686: 
                   5687:     &logthis("Client $clientip ($clientname) hanging up: $userinput");
                   5688:     &Reply($client, "bye\n", $userinput);
                   5689:     $client->shutdown(2);        # shutdown the socket forcibly.
                   5690:     $client->close();
                   5691: 
                   5692:     return 0;
                   5693: }
1.248     foxr     5694: &register_handler("exit", \&exit_handler, 0,1,1);
                   5695: &register_handler("init", \&exit_handler, 0,1,1);
                   5696: &register_handler("quit", \&exit_handler, 0,1,1);
                   5697: 
                   5698: #  Determine if auto-enrollment is enabled.
                   5699: #  Note that the original had what I believe to be a defect.
                   5700: #  The original returned 0 if the requestor was not a registerd client.
                   5701: #  It should return "refused".
                   5702: # Formal Parameters:
                   5703: #   $cmd       - The command that invoked us.
                   5704: #   $tail      - The tail of the command (Extra command parameters.
                   5705: #   $client    - The socket open on the client that issued the request.
                   5706: # Returns:
                   5707: #    1         - Indicating processing should continue.
                   5708: #
                   5709: sub enrollment_enabled_handler {
                   5710:     my ($cmd, $tail, $client) = @_;
                   5711:     my $userinput = $cmd.":".$tail; # For logging purposes.
                   5712: 
                   5713:     
1.337     albertel 5714:     my ($cdom) = split(/:/, $tail, 2);   # Domain we're asking about.
                   5715: 
1.248     foxr     5716:     my $outcome  = &localenroll::run($cdom);
1.387     albertel 5717:     &Reply($client, \$outcome, $userinput);
1.248     foxr     5718: 
                   5719:     return 1;
                   5720: }
                   5721: &register_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
                   5722: 
1.417     raeburn  5723: #
1.423     raeburn  5724: #   Validate an institutional code used for a LON-CAPA course.          
1.417     raeburn  5725: #
                   5726: # Formal Parameters:
                   5727: #   $cmd          - The command request that got us dispatched.
                   5728: #   $tail         - The tail of the command.  In this case,
                   5729: #                   this is a colon separated set of words that will be split
                   5730: #                   into:
1.424     raeburn  5731: #                        $dom      - The domain for which the check of 
                   5732: #                                    institutional course code will occur.
                   5733: #
                   5734: #                        $instcode - The institutional code for the course
                   5735: #                                    being requested, or validated for rights
                   5736: #                                    to request.
                   5737: #
                   5738: #                        $owner    - The course requestor (who will be the
                   5739: #                                    course owner, in the form username:domain
                   5740: #
1.417     raeburn  5741: #   $client       - Socket open on the client.
                   5742: # Returns:
                   5743: #    1           - Indicating processing should continue.
                   5744: #
                   5745: sub validate_instcode_handler {
                   5746:     my ($cmd, $tail, $client) = @_;
                   5747:     my $userinput = "$cmd:$tail";
1.423     raeburn  5748:     my ($dom,$instcode,$owner) = split(/:/, $tail);
1.422     raeburn  5749:     $instcode = &unescape($instcode);
                   5750:     $owner = &unescape($owner);
1.498     raeburn  5751:     my ($outcome,$description,$credits) = 
1.426     raeburn  5752:         &localenroll::validate_instcode($dom,$instcode,$owner);
1.498     raeburn  5753:     my $result = &escape($outcome).'&'.&escape($description).'&'.
                   5754:                  &escape($credits);
1.426     raeburn  5755:     &Reply($client, \$result, $userinput);
1.417     raeburn  5756: 
                   5757:     return 1;
                   5758: }
                   5759: &register_handler("autovalidateinstcode", \&validate_instcode_handler, 0, 1, 0);
                   5760: 
1.248     foxr     5761: #   Get the official sections for which auto-enrollment is possible.
                   5762: #   Since the admin people won't know about 'unofficial sections' 
                   5763: #   we cannot auto-enroll on them.
                   5764: # Formal Parameters:
                   5765: #    $cmd     - The command request that got us dispatched here.
                   5766: #    $tail    - The remainder of the request.  In our case this
                   5767: #               will be split into:
                   5768: #               $coursecode   - The course name from the admin point of view.
                   5769: #               $cdom         - The course's domain(?).
                   5770: #    $client  - Socket open on the client.
                   5771: # Returns:
                   5772: #    1    - Indiciting processing should continue.
                   5773: #
                   5774: sub get_sections_handler {
                   5775:     my ($cmd, $tail, $client) = @_;
                   5776:     my $userinput = "$cmd:$tail";
                   5777: 
                   5778:     my ($coursecode, $cdom) = split(/:/, $tail);
                   5779:     my @secs = &localenroll::get_sections($coursecode,$cdom);
                   5780:     my $seclist = &escape(join(':',@secs));
                   5781: 
1.387     albertel 5782:     &Reply($client, \$seclist, $userinput);
1.248     foxr     5783:     
                   5784: 
                   5785:     return 1;
                   5786: }
                   5787: &register_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
                   5788: 
                   5789: #   Validate the owner of a new course section.  
                   5790: #
                   5791: # Formal Parameters:
                   5792: #   $cmd      - Command that got us dispatched.
                   5793: #   $tail     - the remainder of the command.  For us this consists of a
                   5794: #               colon separated string containing:
                   5795: #                  $inst    - Course Id from the institutions point of view.
                   5796: #                  $owner   - Proposed owner of the course.
                   5797: #                  $cdom    - Domain of the course (from the institutions
                   5798: #                             point of view?)..
                   5799: #   $client   - Socket open on the client.
                   5800: #
                   5801: # Returns:
                   5802: #   1        - Processing should continue.
                   5803: #
                   5804: sub validate_course_owner_handler {
                   5805:     my ($cmd, $tail, $client)  = @_;
                   5806:     my $userinput = "$cmd:$tail";
1.470     raeburn  5807:     my ($inst_course_id, $owner, $cdom, $coowners) = split(/:/, $tail);
                   5808:     
1.336     raeburn  5809:     $owner = &unescape($owner);
1.470     raeburn  5810:     $coowners = &unescape($coowners);
                   5811:     my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom,$coowners);
1.387     albertel 5812:     &Reply($client, \$outcome, $userinput);
1.248     foxr     5813: 
                   5814: 
                   5815: 
                   5816:     return 1;
                   5817: }
                   5818: &register_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
1.263     albertel 5819: 
1.248     foxr     5820: #
                   5821: #   Validate a course section in the official schedule of classes
                   5822: #   from the institutions point of view (part of autoenrollment).
                   5823: #
                   5824: # Formal Parameters:
                   5825: #   $cmd          - The command request that got us dispatched.
                   5826: #   $tail         - The tail of the command.  In this case,
                   5827: #                   this is a colon separated set of words that will be split
                   5828: #                   into:
                   5829: #                        $inst_course_id - The course/section id from the
                   5830: #                                          institutions point of view.
                   5831: #                        $cdom           - The domain from the institutions
                   5832: #                                          point of view.
                   5833: #   $client       - Socket open on the client.
                   5834: # Returns:
                   5835: #    1           - Indicating processing should continue.
                   5836: #
                   5837: sub validate_course_section_handler {
                   5838:     my ($cmd, $tail, $client) = @_;
                   5839:     my $userinput = "$cmd:$tail";
                   5840:     my ($inst_course_id, $cdom) = split(/:/, $tail);
                   5841: 
                   5842:     my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
1.387     albertel 5843:     &Reply($client, \$outcome, $userinput);
1.248     foxr     5844: 
                   5845: 
                   5846:     return 1;
                   5847: }
                   5848: &register_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
                   5849: 
                   5850: #
1.340     raeburn  5851: #   Validate course owner's access to enrollment data for specific class section. 
                   5852: #   
                   5853: #
                   5854: # Formal Parameters:
                   5855: #    $cmd     - The command request that got us dispatched.
                   5856: #    $tail    - The tail of the command.   In this case this is a colon separated
1.542     raeburn  5857: #               set of values that will be split into:
1.340     raeburn  5858: #               $inst_class  - Institutional code for the specific class section   
1.542     raeburn  5859: #               $ownerlist   - An escaped comma-separated list of username:domain 
                   5860: #                              of the course owner, and co-owner(s).
1.340     raeburn  5861: #               $cdom        - The domain of the course from the institution's
                   5862: #                              point of view.
                   5863: #    $client  - The socket open on the client.
                   5864: # Returns:
                   5865: #    1 - continue processing.
                   5866: #
                   5867: 
                   5868: sub validate_class_access_handler {
                   5869:     my ($cmd, $tail, $client) = @_;
                   5870:     my $userinput = "$cmd:$tail";
1.383     raeburn  5871:     my ($inst_class,$ownerlist,$cdom) = split(/:/, $tail);
1.392     raeburn  5872:     my $owners = &unescape($ownerlist);
1.341     albertel 5873:     my $outcome;
                   5874:     eval {
                   5875: 	local($SIG{__DIE__})='DEFAULT';
1.392     raeburn  5876: 	$outcome=&localenroll::check_section($inst_class,$owners,$cdom);
1.341     albertel 5877:     };
1.387     albertel 5878:     &Reply($client,\$outcome, $userinput);
1.340     raeburn  5879: 
                   5880:     return 1;
                   5881: }
                   5882: &register_handler("autovalidateclass_sec", \&validate_class_access_handler, 0, 1, 0);
                   5883: 
                   5884: #
1.542     raeburn  5885: #   Validate course owner or co-owners(s) access to enrollment data for all sections
                   5886: #   and crosslistings for a particular course.
                   5887: #
                   5888: #
                   5889: # Formal Parameters:
                   5890: #    $cmd     - The command request that got us dispatched.
                   5891: #    $tail    - The tail of the command.   In this case this is a colon separated
                   5892: #               set of values that will be split into:
                   5893: #               $ownerlist   - An escaped comma-separated list of username:domain
                   5894: #                              of the course owner, and co-owner(s).
                   5895: #               $cdom        - The domain of the course from the institution's
                   5896: #                              point of view.
                   5897: #               $classes     - Frozen hash of institutional course sections and
                   5898: #                              crosslistings.
                   5899: #    $client  - The socket open on the client.
                   5900: # Returns:
                   5901: #    1 - continue processing.
                   5902: #
                   5903: 
                   5904: sub validate_classes_handler {
                   5905:     my ($cmd, $tail, $client) = @_;
                   5906:     my $userinput = "$cmd:$tail";
                   5907:     my ($ownerlist,$cdom,$classes) = split(/:/, $tail);
                   5908:     my $classesref = &Apache::lonnet::thaw_unescape($classes);
                   5909:     my $owners = &unescape($ownerlist);
                   5910:     my $result;
                   5911:     eval {
                   5912:         local($SIG{__DIE__})='DEFAULT';
                   5913:         my %validations;
                   5914:         my $response = &localenroll::check_instclasses($owners,$cdom,$classesref,
                   5915:                                                        \%validations);
                   5916:         if ($response eq 'ok') {
                   5917:             foreach my $key (keys(%validations)) {
                   5918:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
                   5919:             }
                   5920:             $result =~ s/\&$//;
                   5921:         } else {
                   5922:             $result = 'error';
                   5923:         }
                   5924:     };
                   5925:     if (!$@) {
                   5926:         &Reply($client, \$result, $userinput);
                   5927:     } else {
                   5928:         &Failure($client,"unknown_cmd\n",$userinput);
                   5929:     }
                   5930:     return 1;
                   5931: }
                   5932: &register_handler("autovalidateinstclasses", \&validate_classes_handler, 0, 1, 0);
                   5933: 
                   5934: #
1.340     raeburn  5935: #   Create a password for a new LON-CAPA user added by auto-enrollment.
                   5936: #   Only used for case where authentication method for new user is localauth
1.248     foxr     5937: #
                   5938: # Formal Parameters:
                   5939: #    $cmd     - The command request that got us dispatched.
                   5940: #    $tail    - The tail of the command.   In this case this is a colon separated
                   5941: #               set of words that will be split into:
1.340     raeburn  5942: #               $authparam - An authentication parameter (localauth parameter).
1.248     foxr     5943: #               $cdom      - The domain of the course from the institution's
                   5944: #                            point of view.
                   5945: #    $client  - The socket open on the client.
                   5946: # Returns:
                   5947: #    1 - continue processing.
                   5948: #
                   5949: sub create_auto_enroll_password_handler {
                   5950:     my ($cmd, $tail, $client) = @_;
                   5951:     my $userinput = "$cmd:$tail";
                   5952: 
                   5953:     my ($authparam, $cdom) = split(/:/, $userinput);
                   5954: 
                   5955:     my ($create_passwd,$authchk);
                   5956:     ($authparam,
                   5957:      $create_passwd,
                   5958:      $authchk) = &localenroll::create_password($authparam,$cdom);
                   5959: 
                   5960:     &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
                   5961: 	   $userinput);
                   5962: 
                   5963: 
                   5964:     return 1;
                   5965: }
                   5966: &register_handler("autocreatepassword", \&create_auto_enroll_password_handler, 
                   5967: 		  0, 1, 0);
                   5968: 
1.522     raeburn  5969: sub auto_export_grades_handler {
                   5970:     my ($cmd, $tail, $client) = @_;
                   5971:     my $userinput = "$cmd:$tail";
                   5972:     my ($cdom,$cnum,$info,$data) = split(/:/,$tail);
                   5973:     my $inforef = &Apache::lonnet::thaw_unescape($info);
                   5974:     my $dataref = &Apache::lonnet::thaw_unescape($data);
                   5975:     my ($outcome,$result);;
                   5976:     eval {
                   5977:         local($SIG{__DIE__})='DEFAULT';
                   5978:         my %rtnhash;
                   5979:         $outcome=&localenroll::export_grades($cdom,$cnum,$inforef,$dataref,\%rtnhash);
                   5980:         if ($outcome eq 'ok') {
                   5981:             foreach my $key (keys(%rtnhash)) {
                   5982:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
                   5983:             }
                   5984:             $result =~ s/\&$//;
                   5985:         }
                   5986:     };
                   5987:     if (!$@) {
                   5988:         if ($outcome eq 'ok') {
                   5989:             if ($cipher) {
                   5990:                 my $cmdlength=length($result);
                   5991:                 $result.="         ";
                   5992:                 my $encresult='';
                   5993:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   5994:                     $encresult.= unpack("H16",
                   5995:                                         $cipher->encrypt(substr($result,
                   5996:                                                                 $encidx,
                   5997:                                                                 8)));
                   5998:                 }
                   5999:                 &Reply( $client, "enc:$cmdlength:$encresult\n", $userinput);
                   6000:             } else {
                   6001:                 &Failure( $client, "error:no_key\n", $userinput);
                   6002:             }
                   6003:         } else {
                   6004:             &Reply($client, "$outcome\n", $userinput);
                   6005:         }
                   6006:     } else {
                   6007:         &Failure($client,"export_error\n",$userinput);
                   6008:     }
                   6009:     return 1;
                   6010: }
                   6011: &register_handler("autoexportgrades", \&auto_export_grades_handler,
1.536     raeburn  6012:                   1, 1, 0);
1.522     raeburn  6013: 
1.248     foxr     6014: #   Retrieve and remove temporary files created by/during autoenrollment.
                   6015: #
                   6016: # Formal Parameters:
                   6017: #    $cmd      - The command that got us dispatched.
                   6018: #    $tail     - The tail of the command.  In our case this is a colon 
                   6019: #                separated list that will be split into:
1.526     raeburn  6020: #                $filename - The name of the file to retrieve.
1.248     foxr     6021: #                            The filename is given as a path relative to
                   6022: #                            the LonCAPA temp file directory.
                   6023: #    $client   - Socket open on the client.
                   6024: #
                   6025: # Returns:
                   6026: #   1     - Continue processing.
                   6027: sub retrieve_auto_file_handler {
                   6028:     my ($cmd, $tail, $client)    = @_;
                   6029:     my $userinput                = "cmd:$tail";
                   6030: 
                   6031:     my ($filename)   = split(/:/, $tail);
                   6032: 
                   6033:     my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
1.521     raeburn  6034: 
                   6035:     if ($filename =~m{/\.\./}) {
                   6036:         &Failure($client, "refused\n", $userinput);
1.526     raeburn  6037:     } elsif ($filename !~ /^$LONCAPA::match_domain\_$LONCAPA::match_courseid\_.+_classlist\.xml$/) {
                   6038:         &Failure($client, "refused\n", $userinput);
1.521     raeburn  6039:     } elsif ( (-e $source) && ($filename ne '') ) {
1.248     foxr     6040: 	my $reply = '';
                   6041: 	if (open(my $fh,$source)) {
                   6042: 	    while (<$fh>) {
                   6043: 		chomp($_);
                   6044: 		$_ =~ s/^\s+//g;
                   6045: 		$_ =~ s/\s+$//g;
                   6046: 		$reply .= $_;
                   6047: 	    }
                   6048: 	    close($fh);
                   6049: 	    &Reply($client, &escape($reply)."\n", $userinput);
                   6050: 
                   6051: #   Does this have to be uncommented??!?  (RF).
                   6052: #
                   6053: #                                unlink($source);
                   6054: 	} else {
                   6055: 	    &Failure($client, "error\n", $userinput);
                   6056: 	}
                   6057:     } else {
                   6058: 	&Failure($client, "error\n", $userinput);
                   6059:     }
                   6060:     
                   6061: 
                   6062:     return 1;
                   6063: }
                   6064: &register_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
                   6065: 
1.423     raeburn  6066: sub crsreq_checks_handler {
                   6067:     my ($cmd, $tail, $client) = @_;
                   6068:     my $userinput = "$cmd:$tail";
                   6069:     my $dom = $tail;
                   6070:     my $result;
1.519     raeburn  6071:     my @reqtypes = ('official','unofficial','community','textbook','placement');
1.423     raeburn  6072:     eval {
                   6073:         local($SIG{__DIE__})='DEFAULT';
                   6074:         my %validations;
1.424     raeburn  6075:         my $response = &localenroll::crsreq_checks($dom,\@reqtypes,
                   6076:                                                    \%validations);
1.423     raeburn  6077:         if ($response eq 'ok') { 
                   6078:             foreach my $key (keys(%validations)) {
                   6079:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
                   6080:             }
                   6081:             $result =~ s/\&$//;
                   6082:         } else {
                   6083:             $result = 'error';
                   6084:         }
                   6085:     };
                   6086:     if (!$@) {
                   6087:         &Reply($client, \$result, $userinput);
                   6088:     } else {
                   6089:         &Failure($client,"unknown_cmd\n",$userinput);
                   6090:     }
                   6091:     return 1;
                   6092: }
                   6093: &register_handler("autocrsreqchecks", \&crsreq_checks_handler, 0, 1, 0);
                   6094: 
                   6095: sub validate_crsreq_handler {
                   6096:     my ($cmd, $tail, $client) = @_;
                   6097:     my $userinput = "$cmd:$tail";
1.508     raeburn  6098:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$customdata) = split(/:/, $tail);
1.423     raeburn  6099:     $instcode = &unescape($instcode);
                   6100:     $owner = &unescape($owner);
                   6101:     $crstype = &unescape($crstype);
                   6102:     $inststatuslist = &unescape($inststatuslist);
                   6103:     $instcode = &unescape($instcode);
                   6104:     $instseclist = &unescape($instseclist);
1.508     raeburn  6105:     my $custominfo = &Apache::lonnet::thaw_unescape($customdata);
1.423     raeburn  6106:     my $outcome;
                   6107:     eval {
                   6108:         local($SIG{__DIE__})='DEFAULT';
                   6109:         $outcome = &localenroll::validate_crsreq($dom,$owner,$crstype,
                   6110:                                                  $inststatuslist,$instcode,
1.508     raeburn  6111:                                                  $instseclist,$custominfo);
1.423     raeburn  6112:     };
                   6113:     if (!$@) {
                   6114:         &Reply($client, \$outcome, $userinput);
                   6115:     } else {
                   6116:         &Failure($client,"unknown_cmd\n",$userinput);
                   6117:     }
                   6118:     return 1;
                   6119: }
                   6120: &register_handler("autocrsreqvalidation", \&validate_crsreq_handler, 0, 1, 0);
                   6121: 
1.506     raeburn  6122: sub crsreq_update_handler {
                   6123:     my ($cmd, $tail, $client) = @_;
                   6124:     my $userinput = "$cmd:$tail";
1.509     raeburn  6125:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,$code,
                   6126:         $accessstart,$accessend,$infohashref) =
1.506     raeburn  6127:         split(/:/, $tail);
                   6128:     $crstype = &unescape($crstype);
                   6129:     $action = &unescape($action);
                   6130:     $ownername = &unescape($ownername);
                   6131:     $ownerdomain = &unescape($ownerdomain);
                   6132:     $fullname = &unescape($fullname);
                   6133:     $title = &unescape($title);
                   6134:     $code = &unescape($code);
1.509     raeburn  6135:     $accessstart = &unescape($accessstart);
                   6136:     $accessend = &unescape($accessend);
1.506     raeburn  6137:     my $incoming = &Apache::lonnet::thaw_unescape($infohashref);
                   6138:     my ($result,$outcome);
                   6139:     eval {
                   6140:         local($SIG{__DIE__})='DEFAULT';
                   6141:         my %rtnhash;
                   6142:         $outcome = &localenroll::crsreq_updates($cdom,$cnum,$crstype,$action,
                   6143:                                                 $ownername,$ownerdomain,$fullname,
1.509     raeburn  6144:                                                 $title,$code,$accessstart,$accessend,
                   6145:                                                 $incoming,\%rtnhash);
1.506     raeburn  6146:         if ($outcome eq 'ok') {
1.515     raeburn  6147:             my @posskeys = qw(createdweb createdmsg createdcustomized createdactions queuedweb queuedmsg formitems reviewweb validationjs onload javascript);
1.506     raeburn  6148:             foreach my $key (keys(%rtnhash)) {
                   6149:                 if (grep(/^\Q$key\E/,@posskeys)) {
                   6150:                     $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
                   6151:                 }
                   6152:             }
                   6153:             $result =~ s/\&$//;
                   6154:         }
                   6155:     };
                   6156:     if (!$@) {
                   6157:         if ($outcome eq 'ok') {
                   6158:             &Reply($client, \$result, $userinput);
                   6159:         } else {
                   6160:             &Reply($client, "format_error\n", $userinput);
                   6161:         }
                   6162:     } else {
                   6163:         &Failure($client,"unknown_cmd\n",$userinput);
                   6164:     }
                   6165:     return 1;
                   6166: }
                   6167: &register_handler("autocrsrequpdate", \&crsreq_update_handler, 0, 1, 0);
                   6168: 
1.248     foxr     6169: #
                   6170: #   Read and retrieve institutional code format (for support form).
                   6171: # Formal Parameters:
                   6172: #    $cmd        - Command that dispatched us.
                   6173: #    $tail       - Tail of the command.  In this case it conatins 
                   6174: #                  the course domain and the coursename.
                   6175: #    $client     - Socket open on the client.
                   6176: # Returns:
                   6177: #    1     - Continue processing.
                   6178: #
                   6179: sub get_institutional_code_format_handler {
                   6180:     my ($cmd, $tail, $client)   = @_;
                   6181:     my $userinput               = "$cmd:$tail";
                   6182: 
                   6183:     my $reply;
                   6184:     my($cdom,$course) = split(/:/,$tail);
                   6185:     my @pairs = split/\&/,$course;
                   6186:     my %instcodes = ();
                   6187:     my %codes = ();
                   6188:     my @codetitles = ();
                   6189:     my %cat_titles = ();
                   6190:     my %cat_order = ();
                   6191:     foreach (@pairs) {
                   6192: 	my ($key,$value) = split/=/,$_;
                   6193: 	$instcodes{&unescape($key)} = &unescape($value);
                   6194:     }
                   6195:     my $formatreply = &localenroll::instcode_format($cdom,
                   6196: 						    \%instcodes,
                   6197: 						    \%codes,
                   6198: 						    \@codetitles,
                   6199: 						    \%cat_titles,
                   6200: 						    \%cat_order);
                   6201:     if ($formatreply eq 'ok') {
1.365     albertel 6202: 	my $codes_str = &Apache::lonnet::hash2str(%codes);
                   6203: 	my $codetitles_str = &Apache::lonnet::array2str(@codetitles);
                   6204: 	my $cat_titles_str = &Apache::lonnet::hash2str(%cat_titles);
                   6205: 	my $cat_order_str = &Apache::lonnet::hash2str(%cat_order);
1.248     foxr     6206: 	&Reply($client,
                   6207: 	       $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
                   6208: 	       .$cat_order_str."\n",
                   6209: 	       $userinput);
                   6210:     } else {
                   6211: 	# this else branch added by RF since if not ok, lonc will
                   6212: 	# hang waiting on reply until timeout.
                   6213: 	#
                   6214: 	&Reply($client, "format_error\n", $userinput);
                   6215:     }
                   6216:     
                   6217:     return 1;
                   6218: }
1.265     albertel 6219: &register_handler("autoinstcodeformat",
                   6220: 		  \&get_institutional_code_format_handler,0,1,0);
1.246     foxr     6221: 
1.345     raeburn  6222: sub get_institutional_defaults_handler {
                   6223:     my ($cmd, $tail, $client)   = @_;
                   6224:     my $userinput               = "$cmd:$tail";
                   6225: 
                   6226:     my $dom = $tail;
                   6227:     my %defaults_hash;
                   6228:     my @code_order;
                   6229:     my $outcome;
                   6230:     eval {
                   6231:         local($SIG{__DIE__})='DEFAULT';
                   6232:         $outcome = &localenroll::instcode_defaults($dom,\%defaults_hash,
                   6233:                                                    \@code_order);
                   6234:     };
                   6235:     if (!$@) {
                   6236:         if ($outcome eq 'ok') {
                   6237:             my $result='';
                   6238:             while (my ($key,$value) = each(%defaults_hash)) {
                   6239:                 $result.=&escape($key).'='.&escape($value).'&';
                   6240:             }
                   6241:             $result .= 'code_order='.&escape(join('&',@code_order));
1.387     albertel 6242:             &Reply($client,\$result,$userinput);
1.345     raeburn  6243:         } else {
                   6244:             &Reply($client,"error\n", $userinput);
                   6245:         }
                   6246:     } else {
                   6247:         &Failure($client,"unknown_cmd\n",$userinput);
                   6248:     }
                   6249: }
                   6250: &register_handler("autoinstcodedefaults",
                   6251:                   \&get_institutional_defaults_handler,0,1,0);
                   6252: 
1.416     raeburn  6253: sub get_possible_instcodes_handler {
                   6254:     my ($cmd, $tail, $client)   = @_;
                   6255:     my $userinput               = "$cmd:$tail";
                   6256: 
                   6257:     my $reply;
                   6258:     my $cdom = $tail;
1.417     raeburn  6259:     my (@codetitles,%cat_titles,%cat_order,@code_order);
1.416     raeburn  6260:     my $formatreply = &localenroll::possible_instcodes($cdom,
                   6261:                                                        \@codetitles,
                   6262:                                                        \%cat_titles,
1.417     raeburn  6263:                                                        \%cat_order,
                   6264:                                                        \@code_order);
1.416     raeburn  6265:     if ($formatreply eq 'ok') {
                   6266:         my $result = join('&',map {&escape($_);} (@codetitles)).':';
1.417     raeburn  6267:         $result .= join('&',map {&escape($_);} (@code_order)).':';
1.416     raeburn  6268:         foreach my $key (keys(%cat_titles)) {
                   6269:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_titles{$key}).'&';
                   6270:         }
                   6271:         $result =~ s/\&$//;
                   6272:         $result .= ':';
                   6273:         foreach my $key (keys(%cat_order)) {
                   6274:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_order{$key}).'&';
                   6275:         }
                   6276:         $result =~ s/\&$//;
                   6277:         &Reply($client,\$result,$userinput);
                   6278:     } else {
                   6279:         &Reply($client, "format_error\n", $userinput);
                   6280:     }
                   6281:     return 1;
                   6282: }
                   6283: &register_handler("autopossibleinstcodes",
                   6284:                   \&get_possible_instcodes_handler,0,1,0);
                   6285: 
1.381     raeburn  6286: sub get_institutional_user_rules {
                   6287:     my ($cmd, $tail, $client)   = @_;
                   6288:     my $userinput               = "$cmd:$tail";
                   6289:     my $dom = &unescape($tail);
                   6290:     my (%rules_hash,@rules_order);
                   6291:     my $outcome;
                   6292:     eval {
                   6293:         local($SIG{__DIE__})='DEFAULT';
                   6294:         $outcome = &localenroll::username_rules($dom,\%rules_hash,\@rules_order);
                   6295:     };
                   6296:     if (!$@) {
                   6297:         if ($outcome eq 'ok') {
                   6298:             my $result;
                   6299:             foreach my $key (keys(%rules_hash)) {
                   6300:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6301:             }
                   6302:             $result =~ s/\&$//;
                   6303:             $result .= ':';
                   6304:             if (@rules_order > 0) {
                   6305:                 foreach my $item (@rules_order) {
                   6306:                     $result .= &escape($item).'&';
                   6307:                 }
                   6308:             }
                   6309:             $result =~ s/\&$//;
1.387     albertel 6310:             &Reply($client,\$result,$userinput);
1.381     raeburn  6311:         } else {
                   6312:             &Reply($client,"error\n", $userinput);
                   6313:         }
                   6314:     } else {
                   6315:         &Failure($client,"unknown_cmd\n",$userinput);
                   6316:     }
                   6317: }
                   6318: &register_handler("instuserrules",\&get_institutional_user_rules,0,1,0);
                   6319: 
1.389     raeburn  6320: sub get_institutional_id_rules {
                   6321:     my ($cmd, $tail, $client)   = @_;
                   6322:     my $userinput               = "$cmd:$tail";
                   6323:     my $dom = &unescape($tail);
                   6324:     my (%rules_hash,@rules_order);
                   6325:     my $outcome;
                   6326:     eval {
                   6327:         local($SIG{__DIE__})='DEFAULT';
                   6328:         $outcome = &localenroll::id_rules($dom,\%rules_hash,\@rules_order);
                   6329:     };
                   6330:     if (!$@) {
                   6331:         if ($outcome eq 'ok') {
                   6332:             my $result;
                   6333:             foreach my $key (keys(%rules_hash)) {
                   6334:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6335:             }
                   6336:             $result =~ s/\&$//;
                   6337:             $result .= ':';
                   6338:             if (@rules_order > 0) {
                   6339:                 foreach my $item (@rules_order) {
                   6340:                     $result .= &escape($item).'&';
                   6341:                 }
                   6342:             }
                   6343:             $result =~ s/\&$//;
                   6344:             &Reply($client,\$result,$userinput);
                   6345:         } else {
                   6346:             &Reply($client,"error\n", $userinput);
                   6347:         }
                   6348:     } else {
                   6349:         &Failure($client,"unknown_cmd\n",$userinput);
                   6350:     }
                   6351: }
                   6352: &register_handler("instidrules",\&get_institutional_id_rules,0,1,0);
                   6353: 
1.397     raeburn  6354: sub get_institutional_selfcreate_rules {
1.396     raeburn  6355:     my ($cmd, $tail, $client)   = @_;
                   6356:     my $userinput               = "$cmd:$tail";
                   6357:     my $dom = &unescape($tail);
                   6358:     my (%rules_hash,@rules_order);
                   6359:     my $outcome;
                   6360:     eval {
                   6361:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  6362:         $outcome = &localenroll::selfcreate_rules($dom,\%rules_hash,\@rules_order);
1.396     raeburn  6363:     };
                   6364:     if (!$@) {
                   6365:         if ($outcome eq 'ok') {
                   6366:             my $result;
                   6367:             foreach my $key (keys(%rules_hash)) {
                   6368:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6369:             }
                   6370:             $result =~ s/\&$//;
                   6371:             $result .= ':';
                   6372:             if (@rules_order > 0) {
                   6373:                 foreach my $item (@rules_order) {
                   6374:                     $result .= &escape($item).'&';
                   6375:                 }
                   6376:             }
                   6377:             $result =~ s/\&$//;
                   6378:             &Reply($client,\$result,$userinput);
                   6379:         } else {
                   6380:             &Reply($client,"error\n", $userinput);
                   6381:         }
                   6382:     } else {
                   6383:         &Failure($client,"unknown_cmd\n",$userinput);
                   6384:     }
                   6385: }
1.397     raeburn  6386: &register_handler("instemailrules",\&get_institutional_selfcreate_rules,0,1,0);
1.396     raeburn  6387: 
1.381     raeburn  6388: 
                   6389: sub institutional_username_check {
                   6390:     my ($cmd, $tail, $client)   = @_;
                   6391:     my $userinput               = "$cmd:$tail";
                   6392:     my %rulecheck;
                   6393:     my $outcome;
                   6394:     my ($udom,$uname,@rules) = split(/:/,$tail);
                   6395:     $udom = &unescape($udom);
                   6396:     $uname = &unescape($uname);
                   6397:     @rules = map {&unescape($_);} (@rules);
                   6398:     eval {
                   6399:         local($SIG{__DIE__})='DEFAULT';
                   6400:         $outcome = &localenroll::username_check($udom,$uname,\@rules,\%rulecheck);
                   6401:     };
                   6402:     if (!$@) {
                   6403:         if ($outcome eq 'ok') {
                   6404:             my $result='';
                   6405:             foreach my $key (keys(%rulecheck)) {
                   6406:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6407:             }
1.387     albertel 6408:             &Reply($client,\$result,$userinput);
1.381     raeburn  6409:         } else {
                   6410:             &Reply($client,"error\n", $userinput);
                   6411:         }
                   6412:     } else {
                   6413:         &Failure($client,"unknown_cmd\n",$userinput);
                   6414:     }
                   6415: }
                   6416: &register_handler("instrulecheck",\&institutional_username_check,0,1,0);
                   6417: 
1.389     raeburn  6418: sub institutional_id_check {
                   6419:     my ($cmd, $tail, $client)   = @_;
                   6420:     my $userinput               = "$cmd:$tail";
                   6421:     my %rulecheck;
                   6422:     my $outcome;
                   6423:     my ($udom,$id,@rules) = split(/:/,$tail);
                   6424:     $udom = &unescape($udom);
                   6425:     $id = &unescape($id);
                   6426:     @rules = map {&unescape($_);} (@rules);
                   6427:     eval {
                   6428:         local($SIG{__DIE__})='DEFAULT';
                   6429:         $outcome = &localenroll::id_check($udom,$id,\@rules,\%rulecheck);
                   6430:     };
                   6431:     if (!$@) {
                   6432:         if ($outcome eq 'ok') {
                   6433:             my $result='';
                   6434:             foreach my $key (keys(%rulecheck)) {
                   6435:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6436:             }
                   6437:             &Reply($client,\$result,$userinput);
                   6438:         } else {
                   6439:             &Reply($client,"error\n", $userinput);
                   6440:         }
                   6441:     } else {
                   6442:         &Failure($client,"unknown_cmd\n",$userinput);
                   6443:     }
                   6444: }
                   6445: &register_handler("instidrulecheck",\&institutional_id_check,0,1,0);
1.345     raeburn  6446: 
1.397     raeburn  6447: sub institutional_selfcreate_check {
1.396     raeburn  6448:     my ($cmd, $tail, $client)   = @_;
                   6449:     my $userinput               = "$cmd:$tail";
                   6450:     my %rulecheck;
                   6451:     my $outcome;
                   6452:     my ($udom,$email,@rules) = split(/:/,$tail);
                   6453:     $udom = &unescape($udom);
                   6454:     $email = &unescape($email);
                   6455:     @rules = map {&unescape($_);} (@rules);
                   6456:     eval {
                   6457:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  6458:         $outcome = &localenroll::selfcreate_check($udom,$email,\@rules,\%rulecheck);
1.396     raeburn  6459:     };
                   6460:     if (!$@) {
                   6461:         if ($outcome eq 'ok') {
                   6462:             my $result='';
                   6463:             foreach my $key (keys(%rulecheck)) {
                   6464:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6465:             }
                   6466:             &Reply($client,\$result,$userinput);
                   6467:         } else {
                   6468:             &Reply($client,"error\n", $userinput);
                   6469:         }
                   6470:     } else {
                   6471:         &Failure($client,"unknown_cmd\n",$userinput);
                   6472:     }
                   6473: }
1.397     raeburn  6474: &register_handler("instselfcreatecheck",\&institutional_selfcreate_check,0,1,0);
1.396     raeburn  6475: 
1.317     raeburn  6476: # Get domain specific conditions for import of student photographs to a course
                   6477: #
                   6478: # Retrieves information from photo_permission subroutine in localenroll.
                   6479: # Returns outcome (ok) if no processing errors, and whether course owner is 
                   6480: # required to accept conditions of use (yes/no).
                   6481: #
                   6482: #    
                   6483: sub photo_permission_handler {
                   6484:     my ($cmd, $tail, $client)   = @_;
                   6485:     my $userinput               = "$cmd:$tail";
                   6486:     my $cdom = $tail;
                   6487:     my ($perm_reqd,$conditions);
1.320     albertel 6488:     my $outcome;
                   6489:     eval {
                   6490: 	local($SIG{__DIE__})='DEFAULT';
                   6491: 	$outcome = &localenroll::photo_permission($cdom,\$perm_reqd,
                   6492: 						  \$conditions);
                   6493:     };
                   6494:     if (!$@) {
                   6495: 	&Reply($client, &escape($outcome.':'.$perm_reqd.':'. $conditions)."\n",
                   6496: 	       $userinput);
                   6497:     } else {
                   6498: 	&Failure($client,"unknown_cmd\n",$userinput);
                   6499:     }
                   6500:     return 1;
1.317     raeburn  6501: }
                   6502: &register_handler("autophotopermission",\&photo_permission_handler,0,1,0);
                   6503: 
                   6504: #
                   6505: # Checks if student photo is available for a user in the domain, in the user's
                   6506: # directory (in /userfiles/internal/studentphoto.jpg).
                   6507: # Uses localstudentphoto:fetch() to ensure there is an up to date copy of
                   6508: # the student's photo.   
                   6509: 
                   6510: sub photo_check_handler {
                   6511:     my ($cmd, $tail, $client)   = @_;
                   6512:     my $userinput               = "$cmd:$tail";
                   6513:     my ($udom,$uname,$pid) = split(/:/,$tail);
                   6514:     $udom = &unescape($udom);
                   6515:     $uname = &unescape($uname);
                   6516:     $pid = &unescape($pid);
                   6517:     my $path=&propath($udom,$uname).'/userfiles/internal/';
                   6518:     if (!-e $path) {
                   6519:         &mkpath($path);
                   6520:     }
                   6521:     my $response;
                   6522:     my $result = &localstudentphoto::fetch($udom,$uname,$pid,\$response);
                   6523:     $result .= ':'.$response;
                   6524:     &Reply($client, &escape($result)."\n",$userinput);
1.320     albertel 6525:     return 1;
1.317     raeburn  6526: }
                   6527: &register_handler("autophotocheck",\&photo_check_handler,0,1,0);
                   6528: 
                   6529: #
                   6530: # Retrieve information from localenroll about whether to provide a button     
                   6531: # for users who have enbled import of student photos to initiate an 
                   6532: # update of photo files for registered students. Also include 
                   6533: # comment to display alongside button.  
                   6534: 
                   6535: sub photo_choice_handler {
                   6536:     my ($cmd, $tail, $client) = @_;
                   6537:     my $userinput             = "$cmd:$tail";
                   6538:     my $cdom                  = &unescape($tail);
1.320     albertel 6539:     my ($update,$comment);
                   6540:     eval {
                   6541: 	local($SIG{__DIE__})='DEFAULT';
                   6542: 	($update,$comment)    = &localenroll::manager_photo_update($cdom);
                   6543:     };
                   6544:     if (!$@) {
                   6545: 	&Reply($client,&escape($update).':'.&escape($comment)."\n",$userinput);
                   6546:     } else {
                   6547: 	&Failure($client,"unknown_cmd\n",$userinput);
                   6548:     }
                   6549:     return 1;
1.317     raeburn  6550: }
                   6551: &register_handler("autophotochoice",\&photo_choice_handler,0,1,0);
                   6552: 
1.265     albertel 6553: #
                   6554: # Gets a student's photo to exist (in the correct image type) in the user's 
                   6555: # directory.
                   6556: # Formal Parameters:
                   6557: #    $cmd     - The command request that got us dispatched.
                   6558: #    $tail    - A colon separated set of words that will be split into:
                   6559: #               $domain - student's domain
                   6560: #               $uname  - student username
                   6561: #               $type   - image type desired
                   6562: #    $client  - The socket open on the client.
                   6563: # Returns:
                   6564: #    1 - continue processing.
1.317     raeburn  6565: 
1.265     albertel 6566: sub student_photo_handler {
                   6567:     my ($cmd, $tail, $client) = @_;
1.317     raeburn  6568:     my ($domain,$uname,$ext,$type) = split(/:/, $tail);
1.265     albertel 6569: 
1.317     raeburn  6570:     my $path=&propath($domain,$uname). '/userfiles/internal/';
                   6571:     my $filename = 'studentphoto.'.$ext;
                   6572:     if ($type eq 'thumbnail') {
                   6573:         $filename = 'studentphoto_tn.'.$ext;
                   6574:     }
                   6575:     if (-e $path.$filename) {
1.265     albertel 6576: 	&Reply($client,"ok\n","$cmd:$tail");
                   6577: 	return 1;
                   6578:     }
                   6579:     &mkpath($path);
1.317     raeburn  6580:     my $file;
                   6581:     if ($type eq 'thumbnail') {
1.320     albertel 6582: 	eval {
                   6583: 	    local($SIG{__DIE__})='DEFAULT';
                   6584: 	    $file=&localstudentphoto::fetch_thumbnail($domain,$uname);
                   6585: 	};
1.317     raeburn  6586:     } else {
                   6587:         $file=&localstudentphoto::fetch($domain,$uname);
                   6588:     }
1.265     albertel 6589:     if (!$file) {
                   6590: 	&Failure($client,"unavailable\n","$cmd:$tail");
                   6591: 	return 1;
                   6592:     }
1.317     raeburn  6593:     if (!-e $path.$filename) { &convert_photo($file,$path.$filename); }
                   6594:     if (-e $path.$filename) {
1.265     albertel 6595: 	&Reply($client,"ok\n","$cmd:$tail");
                   6596: 	return 1;
                   6597:     }
                   6598:     &Failure($client,"unable_to_convert\n","$cmd:$tail");
                   6599:     return 1;
                   6600: }
                   6601: &register_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
1.246     foxr     6602: 
1.361     raeburn  6603: sub inst_usertypes_handler {
                   6604:     my ($cmd, $domain, $client) = @_;
                   6605:     my $res;
                   6606:     my $userinput = $cmd.":".$domain; # For logging purposes.
1.370     albertel 6607:     my (%typeshash,@order,$result);
                   6608:     eval {
                   6609: 	local($SIG{__DIE__})='DEFAULT';
                   6610: 	$result=&localenroll::inst_usertypes($domain,\%typeshash,\@order);
                   6611:     };
                   6612:     if ($result eq 'ok') {
1.361     raeburn  6613:         if (keys(%typeshash) > 0) {
                   6614:             foreach my $key (keys(%typeshash)) {
                   6615:                 $res.=&escape($key).'='.&escape($typeshash{$key}).'&';
                   6616:             }
                   6617:         }
                   6618:         $res=~s/\&$//;
                   6619:         $res .= ':';
                   6620:         if (@order > 0) {
                   6621:             foreach my $item (@order) {
                   6622:                 $res .= &escape($item).'&';
                   6623:             }
                   6624:         }
                   6625:         $res=~s/\&$//;
                   6626:     }
1.387     albertel 6627:     &Reply($client, \$res, $userinput);
1.361     raeburn  6628:     return 1;
                   6629: }
                   6630: &register_handler("inst_usertypes", \&inst_usertypes_handler, 0, 1, 0);
                   6631: 
1.264     albertel 6632: # mkpath makes all directories for a file, expects an absolute path with a
                   6633: # file or a trailing / if just a dir is passed
                   6634: # returns 1 on success 0 on failure
                   6635: sub mkpath {
                   6636:     my ($file)=@_;
                   6637:     my @parts=split(/\//,$file,-1);
                   6638:     my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
                   6639:     for (my $i=3;$i<= ($#parts-1);$i++) {
1.265     albertel 6640: 	$now.='/'.$parts[$i]; 
1.264     albertel 6641: 	if (!-e $now) {
                   6642: 	    if  (!mkdir($now,0770)) { return 0; }
                   6643: 	}
                   6644:     }
                   6645:     return 1;
                   6646: }
                   6647: 
1.207     foxr     6648: #---------------------------------------------------------------
                   6649: #
                   6650: #   Getting, decoding and dispatching requests:
                   6651: #
                   6652: #
                   6653: #   Get a Request:
                   6654: #   Gets a Request message from the client.  The transaction
                   6655: #   is defined as a 'line' of text.  We remove the new line
                   6656: #   from the text line.  
1.226     foxr     6657: #
1.211     albertel 6658: sub get_request {
1.207     foxr     6659:     my $input = <$client>;
                   6660:     chomp($input);
1.226     foxr     6661: 
1.234     foxr     6662:     &Debug("get_request: Request = $input\n");
1.207     foxr     6663: 
                   6664:     &status('Processing '.$clientname.':'.$input);
                   6665: 
                   6666:     return $input;
                   6667: }
1.212     foxr     6668: #---------------------------------------------------------------
                   6669: #
                   6670: #  Process a request.  This sub should shrink as each action
                   6671: #  gets farmed out into a separat sub that is registered 
                   6672: #  with the dispatch hash.  
                   6673: #
                   6674: # Parameters:
                   6675: #    user_input   - The request received from the client (lonc).
1.525     raeburn  6676: #
1.212     foxr     6677: # Returns:
                   6678: #    true to keep processing, false if caller should exit.
                   6679: #
                   6680: sub process_request {
1.525     raeburn  6681:     my ($userinput) = @_; # Easier for now to break style than to
                   6682:                           # fix all the userinput -> user_input.
1.212     foxr     6683:     my $wasenc    = 0;		# True if request was encrypted.
                   6684: # ------------------------------------------------------------ See if encrypted
1.322     albertel 6685:     # for command
                   6686:     # sethost:<server>
                   6687:     # <command>:<args>
                   6688:     #   we just send it to the processor
                   6689:     # for
                   6690:     # sethost:<server>:<command>:<args>
                   6691:     #  we do the implict set host and then do the command
                   6692:     if ($userinput =~ /^sethost:/) {
                   6693: 	(my $cmd,my $newid,$userinput) = split(':',$userinput,3);
                   6694: 	if (defined($userinput)) {
                   6695: 	    &sethost("$cmd:$newid");
                   6696: 	} else {
                   6697: 	    $userinput = "$cmd:$newid";
                   6698: 	}
                   6699:     }
                   6700: 
1.212     foxr     6701:     if ($userinput =~ /^enc/) {
                   6702: 	$userinput = decipher($userinput);
                   6703: 	$wasenc=1;
                   6704: 	if(!$userinput) {	# Cipher not defined.
1.251     foxr     6705: 	    &Failure($client, "error: Encrypted data without negotated key\n");
1.212     foxr     6706: 	    return 0;
                   6707: 	}
                   6708:     }
                   6709:     Debug("process_request: $userinput\n");
                   6710:     
1.213     foxr     6711:     #  
                   6712:     #   The 'correct way' to add a command to lond is now to
                   6713:     #   write a sub to execute it and Add it to the command dispatch
                   6714:     #   hash via a call to register_handler..  The comments to that
                   6715:     #   sub should give you enough to go on to show how to do this
                   6716:     #   along with the examples that are building up as this code
                   6717:     #   is getting refactored.   Until all branches of the
                   6718:     #   if/elseif monster below have been factored out into
                   6719:     #   separate procesor subs, if the dispatch hash is missing
                   6720:     #   the command keyword, we will fall through to the remainder
                   6721:     #   of the if/else chain below in order to keep this thing in 
                   6722:     #   working order throughout the transmogrification.
                   6723: 
                   6724:     my ($command, $tail) = split(/:/, $userinput, 2);
                   6725:     chomp($command);
                   6726:     chomp($tail);
                   6727:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
1.214     foxr     6728:     $command =~ s/(\r)//;	# And this too for parameterless commands.
                   6729:     if(!$tail) {
                   6730: 	$tail ="";		# defined but blank.
                   6731:     }
1.213     foxr     6732: 
                   6733:     &Debug("Command received: $command, encoded = $wasenc");
                   6734: 
                   6735:     if(defined $Dispatcher{$command}) {
                   6736: 
                   6737: 	my $dispatch_info = $Dispatcher{$command};
                   6738: 	my $handler       = $$dispatch_info[0];
                   6739: 	my $need_encode   = $$dispatch_info[1];
                   6740: 	my $client_types  = $$dispatch_info[2];
                   6741: 	Debug("Matched dispatch hash: mustencode: $need_encode "
                   6742: 	      ."ClientType $client_types");
                   6743:       
                   6744: 	#  Validate the request:
                   6745:       
                   6746: 	my $ok = 1;
                   6747: 	my $requesterprivs = 0;
                   6748: 	if(&isClient()) {
                   6749: 	    $requesterprivs |= $CLIENT_OK;
                   6750: 	}
                   6751: 	if(&isManager()) {
                   6752: 	    $requesterprivs |= $MANAGER_OK;
                   6753: 	}
                   6754: 	if($need_encode && (!$wasenc)) {
                   6755: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
                   6756: 	    $ok = 0;
                   6757: 	}
                   6758: 	if(($client_types & $requesterprivs) == 0) {
                   6759: 	    Debug("Client not privileged to do this operation");
                   6760: 	    $ok = 0;
                   6761: 	}
1.525     raeburn  6762:         if ($ok) {
1.535     raeburn  6763:             my $realcommand = $command;
                   6764:             if ($command eq 'querysend') {
                   6765:                 my ($query,$rest)=split(/\:/,$tail,2);
                   6766:                 $query=~s/\n*$//g;
                   6767:                 my @possqueries = 
                   6768:                     qw(userlog courselog fetchenrollment institutionalphotos usersearch instdirsearch getinstuser getmultinstusers);
                   6769:                 if (grep(/^\Q$query\E$/,@possqueries)) {
                   6770:                     $command .= '_'.$query;
                   6771:                 } elsif ($query eq 'prepare activity log') {
                   6772:                     $command .= '_activitylog';
                   6773:                 }
                   6774:             }
1.525     raeburn  6775:             if (ref($trust{$command}) eq 'HASH') {
                   6776:                 my $donechecks;
                   6777:                 if ($trust{$command}{'anywhere'}) {
                   6778:                    $donechecks = 1;
                   6779:                 } elsif ($trust{$command}{'manageronly'}) {
                   6780:                     unless (&isManager()) {
                   6781:                         $ok = 0;
                   6782:                     }
                   6783:                     $donechecks = 1;
                   6784:                 } elsif ($trust{$command}{'institutiononly'}) {
                   6785:                     unless ($clientsameinst) {
                   6786:                         $ok = 0;
                   6787:                     }
                   6788:                     $donechecks = 1;
                   6789:                 } elsif ($clientsameinst) {
                   6790:                     $donechecks = 1;
                   6791:                 }
                   6792:                 unless ($donechecks) {
                   6793:                     foreach my $rule (keys(%{$trust{$command}})) {
                   6794:                         next if ($rule eq 'remote');
                   6795:                         if ($trust{$command}{$rule}) {
                   6796:                             if ($clientprohibited{$rule}) {
                   6797:                                 $ok = 0;
                   6798:                             } else {
                   6799:                                 $ok = 1;
                   6800:                                 $donechecks = 1;
                   6801:                                 last;
                   6802:                             }
                   6803:                         }
                   6804:                     }
                   6805:                 }
                   6806:                 unless ($donechecks) {
                   6807:                     if ($trust{$command}{'remote'}) {
                   6808:                         if ($clientremoteok) {
                   6809:                             $ok = 1;
                   6810:                         } else {
                   6811:                             $ok = 0;
                   6812:                         } 
                   6813:                     }
                   6814:                 }
                   6815:             }
1.535     raeburn  6816:             $command = $realcommand;
1.525     raeburn  6817:         }
1.213     foxr     6818: 
                   6819: 	if($ok) {
                   6820: 	    Debug("Dispatching to handler $command $tail");
                   6821: 	    my $keep_going = &$handler($command, $tail, $client);
                   6822: 	    return $keep_going;
                   6823: 	} else {
                   6824: 	    Debug("Refusing to dispatch because client did not match requirements");
                   6825: 	    Failure($client, "refused\n", $userinput);
                   6826: 	    return 1;
                   6827: 	}
1.525     raeburn  6828:     }
1.213     foxr     6829: 
1.262     foxr     6830:     print $client "unknown_cmd\n";
1.212     foxr     6831: # -------------------------------------------------------------------- complete
                   6832:     Debug("process_request - returning 1");
                   6833:     return 1;
                   6834: }
1.207     foxr     6835: #
                   6836: #   Decipher encoded traffic
                   6837: #  Parameters:
                   6838: #     input      - Encoded data.
                   6839: #  Returns:
                   6840: #     Decoded data or undef if encryption key was not yet negotiated.
                   6841: #  Implicit input:
                   6842: #     cipher  - This global holds the negotiated encryption key.
                   6843: #
1.211     albertel 6844: sub decipher {
1.207     foxr     6845:     my ($input)  = @_;
                   6846:     my $output = '';
1.212     foxr     6847:     
                   6848:     
1.207     foxr     6849:     if($cipher) {
                   6850: 	my($enc, $enclength, $encinput) = split(/:/, $input);
                   6851: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
                   6852: 	    $output .= 
                   6853: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
                   6854: 	}
                   6855: 	return substr($output, 0, $enclength);
                   6856:     } else {
                   6857: 	return undef;
                   6858:     }
                   6859: }
                   6860: 
                   6861: #
                   6862: #   Register a command processor.  This function is invoked to register a sub
                   6863: #   to process a request.  Once registered, the ProcessRequest sub can automatically
                   6864: #   dispatch requests to an appropriate sub, and do the top level validity checking
                   6865: #   as well:
                   6866: #    - Is the keyword recognized.
                   6867: #    - Is the proper client type attempting the request.
                   6868: #    - Is the request encrypted if it has to be.
                   6869: #   Parameters:
                   6870: #    $request_name         - Name of the request being registered.
                   6871: #                           This is the command request that will match
                   6872: #                           against the hash keywords to lookup the information
                   6873: #                           associated with the dispatch information.
                   6874: #    $procedure           - Reference to a sub to call to process the request.
                   6875: #                           All subs get called as follows:
                   6876: #                             Procedure($cmd, $tail, $replyfd, $key)
                   6877: #                             $cmd    - the actual keyword that invoked us.
                   6878: #                             $tail   - the tail of the request that invoked us.
                   6879: #                             $replyfd- File descriptor connected to the client
                   6880: #    $must_encode          - True if the request must be encoded to be good.
                   6881: #    $client_ok            - True if it's ok for a client to request this.
                   6882: #    $manager_ok           - True if it's ok for a manager to request this.
                   6883: # Side effects:
                   6884: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
                   6885: #      - On failure, the program will die as it's a bad internal bug to try to 
                   6886: #        register a duplicate command handler.
                   6887: #
1.211     albertel 6888: sub register_handler {
1.212     foxr     6889:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
1.207     foxr     6890: 
                   6891:     #  Don't allow duplication#
                   6892:    
                   6893:     if (defined $Dispatcher{$request_name}) {
                   6894: 	die "Attempting to define a duplicate request handler for $request_name\n";
                   6895:     }
                   6896:     #   Build the client type mask:
                   6897:     
                   6898:     my $client_type_mask = 0;
                   6899:     if($client_ok) {
                   6900: 	$client_type_mask  |= $CLIENT_OK;
                   6901:     }
                   6902:     if($manager_ok) {
                   6903: 	$client_type_mask  |= $MANAGER_OK;
                   6904:     }
                   6905:    
                   6906:     #  Enter the hash:
                   6907:       
                   6908:     my @entry = ($procedure, $must_encode, $client_type_mask);
                   6909:    
                   6910:     $Dispatcher{$request_name} = \@entry;
                   6911:    
                   6912: }
                   6913: 
                   6914: 
                   6915: #------------------------------------------------------------------
                   6916: 
                   6917: 
                   6918: 
                   6919: 
1.141     foxr     6920: #
1.96      foxr     6921: #  Convert an error return code from lcpasswd to a string value.
                   6922: #
                   6923: sub lcpasswdstrerror {
                   6924:     my $ErrorCode = shift;
1.97      foxr     6925:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96      foxr     6926: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
                   6927:     } else {
1.98      foxr     6928: 	return $passwderrors[$ErrorCode];
1.96      foxr     6929:     }
                   6930: }
                   6931: 
1.23      harris41 6932: # grabs exception and records it to log before exiting
                   6933: sub catchexception {
1.27      albertel 6934:     my ($error)=@_;
1.25      www      6935:     $SIG{'QUIT'}='DEFAULT';
                   6936:     $SIG{__DIE__}='DEFAULT';
1.165     albertel 6937:     &status("Catching exception");
1.190     albertel 6938:     &logthis("<font color='red'>CRITICAL: "
1.373     albertel 6939:      ."ABNORMAL EXIT. Child $$ for server ".$perlvar{'lonHostID'}." died through "
1.27      albertel 6940:      ."a crash with this error msg->[$error]</font>");
1.57      www      6941:     &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27      albertel 6942:     if ($client) { print $client "error: $error\n"; }
1.59      www      6943:     $server->close();
1.27      albertel 6944:     die($error);
1.23      harris41 6945: }
1.63      www      6946: sub timeout {
1.165     albertel 6947:     &status("Handling Timeout");
1.190     albertel 6948:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
1.63      www      6949:     &catchexception('Timeout');
                   6950: }
1.22      harris41 6951: # -------------------------------- Set signal handlers to record abnormal exits
                   6952: 
1.226     foxr     6953: 
1.22      harris41 6954: $SIG{'QUIT'}=\&catchexception;
                   6955: $SIG{__DIE__}=\&catchexception;
                   6956: 
1.81      matthew  6957: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95      harris41 6958: &status("Read loncapa.conf and loncapa_apache.conf");
                   6959: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141     foxr     6960: %perlvar=%{$perlvarref};
1.80      harris41 6961: undef $perlvarref;
1.19      www      6962: 
1.35      harris41 6963: # ----------------------------- Make sure this process is running from user=www
                   6964: my $wwwid=getpwnam('www');
                   6965: if ($wwwid!=$<) {
1.134     albertel 6966:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   6967:    my $subj="LON: $currenthostid User ID mismatch";
1.550     raeburn  6968:    system("echo 'User ID mismatch.  lond must be run as user www.' |".
                   6969:           " mail -s '$subj' $emailto > /dev/null");
1.35      harris41 6970:    exit 1;
                   6971: }
                   6972: 
1.19      www      6973: # --------------------------------------------- Check if other instance running
                   6974: 
                   6975: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
                   6976: 
                   6977: if (-e $pidfile) {
                   6978:    my $lfh=IO::File->new("$pidfile");
                   6979:    my $pide=<$lfh>;
                   6980:    chomp($pide);
1.29      harris41 6981:    if (kill 0 => $pide) { die "already running"; }
1.19      www      6982: }
1.1       albertel 6983: 
                   6984: # ------------------------------------------------------------- Read hosts file
                   6985: 
                   6986: 
                   6987: 
                   6988: # establish SERVER socket, bind and listen.
                   6989: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
                   6990:                                 Type      => SOCK_STREAM,
                   6991:                                 Proto     => 'tcp',
1.469     foxr     6992:                                 ReuseAddr     => 1,
1.1       albertel 6993:                                 Listen    => 10 )
1.29      harris41 6994:   or die "making socket: $@\n";
1.1       albertel 6995: 
                   6996: # --------------------------------------------------------- Do global variables
                   6997: 
                   6998: # global variables
                   6999: 
1.134     albertel 7000: my %children               = ();       # keys are current child process IDs
1.1       albertel 7001: 
                   7002: sub REAPER {                        # takes care of dead children
                   7003:     $SIG{CHLD} = \&REAPER;
1.165     albertel 7004:     &status("Handling child death");
1.178     foxr     7005:     my $pid;
                   7006:     do {
                   7007: 	$pid = waitpid(-1,&WNOHANG());
                   7008: 	if (defined($children{$pid})) {
                   7009: 	    &logthis("Child $pid died");
                   7010: 	    delete($children{$pid});
1.183     albertel 7011: 	} elsif ($pid > 0) {
1.178     foxr     7012: 	    &logthis("Unknown Child $pid died");
                   7013: 	}
                   7014:     } while ( $pid > 0 );
                   7015:     foreach my $child (keys(%children)) {
                   7016: 	$pid = waitpid($child,&WNOHANG());
                   7017: 	if ($pid > 0) {
                   7018: 	    &logthis("Child $child - $pid looks like we missed it's death");
                   7019: 	    delete($children{$pid});
                   7020: 	}
1.176     albertel 7021:     }
1.165     albertel 7022:     &status("Finished Handling child death");
1.1       albertel 7023: }
                   7024: 
                   7025: sub HUNTSMAN {                      # signal handler for SIGINT
1.165     albertel 7026:     &status("Killing children (INT)");
1.1       albertel 7027:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
                   7028:     kill 'INT' => keys %children;
1.59      www      7029:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1       albertel 7030:     my $execdir=$perlvar{'lonDaemons'};
                   7031:     unlink("$execdir/logs/lond.pid");
1.190     albertel 7032:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.165     albertel 7033:     &status("Done killing children");
1.1       albertel 7034:     exit;                           # clean up with dignity
                   7035: }
                   7036: 
                   7037: sub HUPSMAN {                      # signal handler for SIGHUP
                   7038:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
1.165     albertel 7039:     &status("Killing children for restart (HUP)");
1.1       albertel 7040:     kill 'INT' => keys %children;
1.59      www      7041:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.190     albertel 7042:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.134     albertel 7043:     my $execdir=$perlvar{'lonDaemons'};
1.30      harris41 7044:     unlink("$execdir/logs/lond.pid");
1.165     albertel 7045:     &status("Restarting self (HUP)");
1.1       albertel 7046:     exec("$execdir/lond");         # here we go again
                   7047: }
                   7048: 
1.144     foxr     7049: #
1.148     foxr     7050: #  Reload the Apache daemon's state.
1.150     foxr     7051: #  This is done by invoking /home/httpd/perl/apachereload
                   7052: #  a setuid perl script that can be root for us to do this job.
1.148     foxr     7053: #
                   7054: sub ReloadApache {
1.473     raeburn  7055: # --------------------------- Handle case of another apachereload process (locking)
1.474     raeburn  7056:     if (&LONCAPA::try_to_lock('/tmp/lock_apachereload')) {
                   7057:         my $execdir = $perlvar{'lonDaemons'};
                   7058:         my $script  = $execdir."/apachereload";
                   7059:         system($script);
                   7060:         unlink('/tmp/lock_apachereload'); #  Remove the lock file.
                   7061:     }
1.148     foxr     7062: }
                   7063: 
                   7064: #
1.144     foxr     7065: #   Called in response to a USR2 signal.
                   7066: #   - Reread hosts.tab
                   7067: #   - All children connected to hosts that were removed from hosts.tab
                   7068: #     are killed via SIGINT
                   7069: #   - All children connected to previously existing hosts are sent SIGUSR1
                   7070: #   - Our internal hosts hash is updated to reflect the new contents of
                   7071: #     hosts.tab causing connections from hosts added to hosts.tab to
                   7072: #     now be honored.
                   7073: #
                   7074: sub UpdateHosts {
1.165     albertel 7075:     &status("Reload hosts.tab");
1.147     foxr     7076:     logthis('<font color="blue"> Updating connections </font>');
1.148     foxr     7077:     #
                   7078:     #  The %children hash has the set of IP's we currently have children
                   7079:     #  on.  These need to be matched against records in the hosts.tab
                   7080:     #  Any ip's no longer in the table get killed off they correspond to
                   7081:     #  either dropped or changed hosts.  Note that the re-read of the table
                   7082:     #  will take care of new and changed hosts as connections come into being.
                   7083: 
1.371     albertel 7084:     &Apache::lonnet::reset_hosts_info();
1.532     raeburn  7085:     my %active;
1.148     foxr     7086: 
1.368     albertel 7087:     foreach my $child (keys(%children)) {
1.148     foxr     7088: 	my $childip = $children{$child};
1.374     albertel 7089: 	if ($childip ne '127.0.0.1'
                   7090: 	    && !defined(&Apache::lonnet::get_hosts_from_ip($childip))) {
1.149     foxr     7091: 	    logthis('<font color="blue"> UpdateHosts killing child '
                   7092: 		    ." $child for ip $childip </font>");
1.148     foxr     7093: 	    kill('INT', $child);
1.149     foxr     7094: 	} else {
1.532     raeburn  7095:             $active{$child} = $childip;
1.149     foxr     7096: 	    logthis('<font color="green"> keeping child for ip '
                   7097: 		    ." $childip (pid=$child) </font>");
1.148     foxr     7098: 	}
                   7099:     }
1.532     raeburn  7100: 
                   7101:     my %oldconf = %secureconf;
                   7102:     my %connchange;
1.555     raeburn  7103:     if (lonssl::Read_Connect_Config(\%secureconf,\%perlvar,\%crlchecked) eq 'ok') {
1.545     raeburn  7104:         logthis('<font color="blue"> Reloaded SSL connection rules and cleared CRL checking history </font>');
1.532     raeburn  7105:     } else {
1.545     raeburn  7106:         logthis('<font color="yellow"> Failed to reload SSL connection rules and clear CRL checking history </font>');
1.532     raeburn  7107:     }
                   7108:     if ((ref($oldconf{'connfrom'}) eq 'HASH') && (ref($secureconf{'connfrom'}) eq 'HASH')) {
                   7109:         foreach my $type ('dom','intdom','other') {
                   7110:             if ((($oldconf{'connfrom'}{$type} eq 'no') && ($secureconf{'connfrom'}{$type} eq 'req')) ||
                   7111:                 (($oldconf{'connfrom'}{$type} eq 'req') && ($secureconf{'connfrom'}{$type} eq 'no'))) {
                   7112:                 $connchange{$type} = 1;
                   7113:             }
                   7114:         }
                   7115:     }
                   7116:     if (keys(%connchange)) {
                   7117:         foreach my $child (keys(%active)) {
                   7118:             my $childip = $active{$child};
                   7119:             if ($childip ne '127.0.0.1') {
                   7120:                 my $childhostname  = gethostbyaddr(Socket::inet_aton($childip),AF_INET);
                   7121:                 if ($childhostname ne '') {
                   7122:                     my $childlonhost = &Apache::lonnet::get_server_homeID($childhostname);
                   7123:                     my ($samedom,$sameinst) = &set_client_info($childlonhost);
                   7124:                     if ($samedom) {
                   7125:                         if ($connchange{'dom'}) {
                   7126:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7127:                                    ." $child for ip $childip </font>");
                   7128:                             kill('INT', $child);
                   7129:                         }
                   7130:                     } elsif ($sameinst) {
                   7131:                         if ($connchange{'intdom'}) {
                   7132:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7133:                                    ." $child for ip $childip </font>");
                   7134:                            kill('INT', $child);
                   7135:                         }
                   7136:                     } else {
                   7137:                         if ($connchange{'other'}) {
                   7138:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7139:                                    ." $child for ip $childip </font>");
                   7140:                             kill('INT', $child);
                   7141:                         }
                   7142:                     }
                   7143:                 }
                   7144:             }
                   7145:         }
                   7146:     }
1.148     foxr     7147:     ReloadApache;
1.165     albertel 7148:     &status("Finished reloading hosts.tab");
1.144     foxr     7149: }
                   7150: 
1.57      www      7151: sub checkchildren {
1.165     albertel 7152:     &status("Checking on the children (sending signals)");
1.57      www      7153:     &initnewstatus();
                   7154:     &logstatus();
                   7155:     &logthis('Going to check on the children');
1.134     albertel 7156:     my $docdir=$perlvar{'lonDocRoot'};
1.61      harris41 7157:     foreach (sort keys %children) {
1.221     albertel 7158: 	#sleep 1;
1.57      www      7159:         unless (kill 'USR1' => $_) {
                   7160: 	    &logthis ('Child '.$_.' is dead');
                   7161:             &logstatus($$.' is dead');
1.221     albertel 7162: 	    delete($children{$_});
1.57      www      7163:         } 
1.61      harris41 7164:     }
1.63      www      7165:     sleep 5;
1.212     foxr     7166:     $SIG{ALRM} = sub { Debug("timeout"); 
                   7167: 		       die "timeout";  };
1.113     albertel 7168:     $SIG{__DIE__} = 'DEFAULT';
1.165     albertel 7169:     &status("Checking on the children (waiting for reports)");
1.63      www      7170:     foreach (sort keys %children) {
                   7171:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113     albertel 7172:           eval {
                   7173:             alarm(300);
1.63      www      7174: 	    &logthis('Child '.$_.' did not respond');
1.67      albertel 7175: 	    kill 9 => $_;
1.131     albertel 7176: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   7177: 	    #$subj="LON: $currenthostid killed lond process $_";
                   7178: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
                   7179: 	    #$execdir=$perlvar{'lonDaemons'};
                   7180: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.221     albertel 7181: 	    delete($children{$_});
1.113     albertel 7182: 	    alarm(0);
                   7183: 	  }
1.63      www      7184:         }
                   7185:     }
1.113     albertel 7186:     $SIG{ALRM} = 'DEFAULT';
1.155     albertel 7187:     $SIG{__DIE__} = \&catchexception;
1.165     albertel 7188:     &status("Finished checking children");
1.221     albertel 7189:     &logthis('Finished Checking children');
1.57      www      7190: }
                   7191: 
1.1       albertel 7192: # --------------------------------------------------------------------- Logging
                   7193: 
                   7194: sub logthis {
                   7195:     my $message=shift;
                   7196:     my $execdir=$perlvar{'lonDaemons'};
                   7197:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
                   7198:     my $now=time;
                   7199:     my $local=localtime($now);
1.58      www      7200:     $lastlog=$local.': '.$message;
1.1       albertel 7201:     print $fh "$local ($$): $message\n";
                   7202: }
                   7203: 
1.77      foxr     7204: # ------------------------- Conditional log if $DEBUG true.
                   7205: sub Debug {
                   7206:     my $message = shift;
                   7207:     if($DEBUG) {
                   7208: 	&logthis($message);
                   7209:     }
                   7210: }
1.161     foxr     7211: 
                   7212: #
                   7213: #   Sub to do replies to client.. this gives a hook for some
                   7214: #   debug tracing too:
                   7215: #  Parameters:
                   7216: #     fd      - File open on client.
                   7217: #     reply   - Text to send to client.
                   7218: #     request - Original request from client.
                   7219: #
1.490     droeschl 7220: #NOTE $reply must be terminated by exactly *one* \n. If $reply is a reference
                   7221: #this is done automatically ($$reply must not contain any \n in this case). 
                   7222: #If $reply is a string the caller has to ensure this.
1.161     foxr     7223: sub Reply {
1.192     foxr     7224:     my ($fd, $reply, $request) = @_;
1.387     albertel 7225:     if (ref($reply)) {
                   7226: 	print $fd $$reply;
                   7227: 	print $fd "\n";
                   7228: 	if ($DEBUG) { Debug("Request was $request  Reply was $$reply"); }
                   7229:     } else {
                   7230: 	print $fd $reply;
                   7231: 	if ($DEBUG) { Debug("Request was $request  Reply was $reply"); }
                   7232:     }
1.212     foxr     7233:     $Transactions++;
                   7234: }
                   7235: 
                   7236: 
                   7237: #
                   7238: #    Sub to report a failure.
                   7239: #    This function:
                   7240: #     -   Increments the failure statistic counters.
                   7241: #     -   Invokes Reply to send the error message to the client.
                   7242: # Parameters:
                   7243: #    fd       - File descriptor open on the client
                   7244: #    reply    - Reply text to emit.
                   7245: #    request  - The original request message (used by Reply
                   7246: #               to debug if that's enabled.
                   7247: # Implicit outputs:
                   7248: #    $Failures- The number of failures is incremented.
                   7249: #    Reply (invoked here) sends a message to the 
                   7250: #    client:
                   7251: #
                   7252: sub Failure {
                   7253:     my $fd      = shift;
                   7254:     my $reply   = shift;
                   7255:     my $request = shift;
                   7256:    
                   7257:     $Failures++;
                   7258:     Reply($fd, $reply, $request);      # That's simple eh?
1.161     foxr     7259: }
1.57      www      7260: # ------------------------------------------------------------------ Log status
                   7261: 
                   7262: sub logstatus {
1.178     foxr     7263:     &status("Doing logging");
                   7264:     my $docdir=$perlvar{'lonDocRoot'};
                   7265:     {
                   7266: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
1.200     matthew  7267:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
1.178     foxr     7268:         $fh->close();
                   7269:     }
1.221     albertel 7270:     &status("Finished $$.txt");
                   7271:     {
                   7272: 	open(LOG,">>$docdir/lon-status/londstatus.txt");
                   7273: 	flock(LOG,LOCK_EX);
                   7274: 	print LOG $$."\t".$clientname."\t".$currenthostid."\t"
                   7275: 	    .$status."\t".$lastlog."\t $keymode\n";
1.275     albertel 7276: 	flock(LOG,LOCK_UN);
1.221     albertel 7277: 	close(LOG);
                   7278:     }
1.178     foxr     7279:     &status("Finished logging");
1.57      www      7280: }
                   7281: 
                   7282: sub initnewstatus {
                   7283:     my $docdir=$perlvar{'lonDocRoot'};
                   7284:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
1.460     foxr     7285:     my $now=time();
1.57      www      7286:     my $local=localtime($now);
                   7287:     print $fh "LOND status $local - parent $$\n\n";
1.64      www      7288:     opendir(DIR,"$docdir/lon-status/londchld");
1.134     albertel 7289:     while (my $filename=readdir(DIR)) {
1.64      www      7290:         unlink("$docdir/lon-status/londchld/$filename");
                   7291:     }
                   7292:     closedir(DIR);
1.57      www      7293: }
                   7294: 
                   7295: # -------------------------------------------------------------- Status setting
                   7296: 
                   7297: sub status {
                   7298:     my $what=shift;
                   7299:     my $now=time;
                   7300:     my $local=localtime($now);
1.178     foxr     7301:     $status=$local.': '.$what;
                   7302:     $0='lond: '.$what.' '.$local;
1.57      www      7303: }
1.11      www      7304: 
1.13      www      7305: # -------------------------------------------------------------- Talk to lonsql
                   7306: 
1.234     foxr     7307: sub sql_reply {
1.12      harris41 7308:     my ($cmd)=@_;
1.234     foxr     7309:     my $answer=&sub_sql_reply($cmd);
                   7310:     if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
1.12      harris41 7311:     return $answer;
                   7312: }
                   7313: 
1.234     foxr     7314: sub sub_sql_reply {
1.12      harris41 7315:     my ($cmd)=@_;
                   7316:     my $unixsock="mysqlsock";
                   7317:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
                   7318:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                   7319:                                       Type    => SOCK_STREAM,
                   7320:                                       Timeout => 10)
                   7321:        or return "con_lost";
1.319     www      7322:     print $sclient "$cmd:$currentdomainid\n";
1.12      harris41 7323:     my $answer=<$sclient>;
                   7324:     chomp($answer);
                   7325:     if (!$answer) { $answer="con_lost"; }
                   7326:     return $answer;
                   7327: }
                   7328: 
1.1       albertel 7329: # --------------------------------------- Is this the home server of an author?
1.11      www      7330: 
1.1       albertel 7331: sub ishome {
                   7332:     my $author=shift;
                   7333:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   7334:     my ($udom,$uname)=split(/\//,$author);
                   7335:     my $proname=propath($udom,$uname);
                   7336:     if (-e $proname) {
                   7337: 	return 'owner';
                   7338:     } else {
                   7339:         return 'not_owner';
                   7340:     }
                   7341: }
                   7342: 
                   7343: # ======================================================= Continue main program
                   7344: # ---------------------------------------------------- Fork once and dissociate
                   7345: 
1.134     albertel 7346: my $fpid=fork;
1.1       albertel 7347: exit if $fpid;
1.29      harris41 7348: die "Couldn't fork: $!" unless defined ($fpid);
1.1       albertel 7349: 
1.29      harris41 7350: POSIX::setsid() or die "Can't start new session: $!";
1.1       albertel 7351: 
                   7352: # ------------------------------------------------------- Write our PID on disk
                   7353: 
1.134     albertel 7354: my $execdir=$perlvar{'lonDaemons'};
1.1       albertel 7355: open (PIDSAVE,">$execdir/logs/lond.pid");
                   7356: print PIDSAVE "$$\n";
                   7357: close(PIDSAVE);
1.190     albertel 7358: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.57      www      7359: &status('Starting');
1.1       albertel 7360: 
1.106     foxr     7361: 
1.1       albertel 7362: 
                   7363: # ----------------------------------------------------- Install signal handlers
                   7364: 
1.57      www      7365: 
1.1       albertel 7366: $SIG{CHLD} = \&REAPER;
                   7367: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   7368: $SIG{HUP}  = \&HUPSMAN;
1.57      www      7369: $SIG{USR1} = \&checkchildren;
1.144     foxr     7370: $SIG{USR2} = \&UpdateHosts;
1.106     foxr     7371: 
1.148     foxr     7372: #  Read the host hashes:
1.368     albertel 7373: &Apache::lonnet::load_hosts_tab();
1.447     raeburn  7374: my %iphost = &Apache::lonnet::get_iphost(1);
1.106     foxr     7375: 
1.480     raeburn  7376: $dist=`$perlvar{'lonDaemons'}/distprobe`;
1.286     albertel 7377: 
1.471     raeburn  7378: my $arch = `uname -i`;
1.475     raeburn  7379: chomp($arch);
1.471     raeburn  7380: if ($arch eq 'unknown') {
                   7381:     $arch = `uname -m`;
1.475     raeburn  7382:     chomp($arch);
1.471     raeburn  7383: }
                   7384: 
1.555     raeburn  7385: unless (lonssl::Read_Connect_Config(\%secureconf,\%perlvar,\%crlchecked) eq 'ok') {
1.532     raeburn  7386:     &logthis('<font color="blue">No connectionrules table. Will fallback to loncapa.conf</font>');
                   7387: }
                   7388: 
1.106     foxr     7389: # --------------------------------------------------------------
                   7390: #   Accept connections.  When a connection comes in, it is validated
                   7391: #   and if good, a child process is created to process transactions
                   7392: #   along the connection.
                   7393: 
1.1       albertel 7394: while (1) {
1.165     albertel 7395:     &status('Starting accept');
1.106     foxr     7396:     $client = $server->accept() or next;
1.165     albertel 7397:     &status('Accepted '.$client.' off to spawn');
1.386     albertel 7398:     make_new_child($client);
1.165     albertel 7399:     &status('Finished spawning');
1.1       albertel 7400: }
                   7401: 
1.212     foxr     7402: sub make_new_child {
                   7403:     my $pid;
                   7404: #    my $cipher;     # Now global
                   7405:     my $sigset;
1.178     foxr     7406: 
1.212     foxr     7407:     $client = shift;
                   7408:     &status('Starting new child '.$client);
                   7409:     &logthis('<font color="green"> Attempting to start child ('.$client.
                   7410: 	     ")</font>");    
                   7411:     # block signal for fork
                   7412:     $sigset = POSIX::SigSet->new(SIGINT);
                   7413:     sigprocmask(SIG_BLOCK, $sigset)
                   7414:         or die "Can't block SIGINT for fork: $!\n";
1.178     foxr     7415: 
1.212     foxr     7416:     die "fork: $!" unless defined ($pid = fork);
1.178     foxr     7417: 
1.212     foxr     7418:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
                   7419: 	                               # connection liveness.
1.178     foxr     7420: 
1.212     foxr     7421:     #
                   7422:     #  Figure out who we're talking to so we can record the peer in 
                   7423:     #  the pid hash.
                   7424:     #
                   7425:     my $caller = getpeername($client);
                   7426:     my ($port,$iaddr);
                   7427:     if (defined($caller) && length($caller) > 0) {
                   7428: 	($port,$iaddr)=unpack_sockaddr_in($caller);
                   7429:     } else {
                   7430: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
                   7431:     }
                   7432:     if (defined($iaddr)) {
                   7433: 	$clientip  = inet_ntoa($iaddr);
                   7434: 	Debug("Connected with $clientip");
                   7435:     } else {
                   7436: 	&logthis("Unable to determine clientip");
                   7437: 	$clientip='Unavailable';
                   7438:     }
                   7439:     
                   7440:     if ($pid) {
                   7441:         # Parent records the child's birth and returns.
                   7442:         sigprocmask(SIG_UNBLOCK, $sigset)
                   7443:             or die "Can't unblock SIGINT for fork: $!\n";
                   7444:         $children{$pid} = $clientip;
                   7445:         &status('Started child '.$pid);
1.462     foxr     7446: 	close($client);
1.212     foxr     7447:         return;
                   7448:     } else {
                   7449:         # Child can *not* return from this subroutine.
                   7450:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
                   7451:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
                   7452:                                 #don't get intercepted
                   7453:         $SIG{USR1}= \&logstatus;
                   7454:         $SIG{ALRM}= \&timeout;
1.468     foxr     7455: 	#
                   7456: 	# Block sigpipe as it gets thrownon socket disconnect and we want to 
                   7457: 	# deal with that as a read faiure instead.
                   7458: 	#
                   7459: 	my $blockset = POSIX::SigSet->new(SIGPIPE);
                   7460: 	sigprocmask(SIG_BLOCK, $blockset);
                   7461: 
1.212     foxr     7462:         $lastlog='Forked ';
                   7463:         $status='Forked';
1.178     foxr     7464: 
1.212     foxr     7465:         # unblock signals
                   7466:         sigprocmask(SIG_UNBLOCK, $sigset)
                   7467:             or die "Can't unblock SIGINT for fork: $!\n";
1.178     foxr     7468: 
1.212     foxr     7469: #        my $tmpsnum=0;            # Now global
                   7470: #---------------------------------------------------- kerberos 5 initialization
                   7471:         &Authen::Krb5::init_context();
1.511     raeburn  7472: 
                   7473:         my $no_ets;
1.514     raeburn  7474:         if ($dist =~ /^(?:centos|rhes|scientific)(\d+)$/) {
1.511     raeburn  7475:             if ($1 >= 7) {
                   7476:                 $no_ets = 1;
                   7477:             }
                   7478:         } elsif ($dist =~ /^suse(\d+\.\d+)$/) {
                   7479:             if (($1 eq '9.3') || ($1 >= 12.2)) {
                   7480:                 $no_ets = 1; 
                   7481:             }
1.514     raeburn  7482:         } elsif ($dist =~ /^sles(\d+)$/) {
                   7483:             if ($1 > 11) {
                   7484:                 $no_ets = 1;
                   7485:             }
1.511     raeburn  7486:         } elsif ($dist =~ /^fedora(\d+)$/) {
                   7487:             if ($1 < 7) {
                   7488:                 $no_ets = 1;
                   7489:             }
                   7490:         }
                   7491:         unless ($no_ets) {
1.286     albertel 7492: 	    &Authen::Krb5::init_ets();
                   7493: 	}
1.209     albertel 7494: 
1.212     foxr     7495: 	&status('Accepted connection');
                   7496: # =============================================================================
                   7497:             # do something with the connection
                   7498: # -----------------------------------------------------------------------------
                   7499: 	# see if we know client and 'check' for spoof IP by ineffective challenge
1.178     foxr     7500: 
1.278     albertel 7501: 	my $outsideip=$clientip;
                   7502: 	if ($clientip eq '127.0.0.1') {
1.368     albertel 7503: 	    $outsideip=&Apache::lonnet::get_host_ip($perlvar{'lonHostID'});
1.278     albertel 7504: 	}
1.412     foxr     7505: 	&ReadManagerTable();
1.368     albertel 7506: 	my $clientrec=defined(&Apache::lonnet::get_hosts_from_ip($outsideip));
1.278     albertel 7507: 	my $ismanager=($managers{$outsideip}    ne undef);
1.432     raeburn  7508: 	$clientname  = "[unknown]";
1.212     foxr     7509: 	if($clientrec) {	# Establish client type.
                   7510: 	    $ConnectionType = "client";
1.368     albertel 7511: 	    $clientname = (&Apache::lonnet::get_hosts_from_ip($outsideip))[-1];
1.212     foxr     7512: 	    if($ismanager) {
                   7513: 		$ConnectionType = "both";
                   7514: 	    }
                   7515: 	} else {
                   7516: 	    $ConnectionType = "manager";
1.278     albertel 7517: 	    $clientname = $managers{$outsideip};
1.212     foxr     7518: 	}
1.556     raeburn  7519: 	my $clientok;
1.178     foxr     7520: 
1.212     foxr     7521: 	if ($clientrec || $ismanager) {
                   7522: 	    &status("Waiting for init from $clientip $clientname");
                   7523: 	    &logthis('<font color="yellow">INFO: Connection, '.
                   7524: 		     $clientip.
                   7525: 		  " ($clientname) connection type = $ConnectionType </font>" );
                   7526: 	    &status("Connecting $clientip  ($clientname))"); 
                   7527: 	    my $remotereq=<$client>;
                   7528: 	    chomp($remotereq);
                   7529: 	    Debug("Got init: $remotereq");
1.337     albertel 7530: 
1.212     foxr     7531: 	    if ($remotereq =~ /^init/) {
                   7532: 		&sethost("sethost:$perlvar{'lonHostID'}");
                   7533: 		#
                   7534: 		#  If the remote is attempting a local init... give that a try:
                   7535: 		#
1.432     raeburn  7536: 		(my $i, my $inittype, $clientversion) = split(/:/, $remotereq);
1.492     droeschl 7537:         # For LON-CAPA 2.9, the  client session will have sent its LON-CAPA
                   7538:         # version when initiating the connection. For LON-CAPA 2.8 and older,
                   7539:         # the version is retrieved from the global %loncaparevs in lonnet.pm.            
1.494     droeschl 7540:         # $clientversion contains path to keyfile if $inittype eq 'local'
                   7541:         # it's overridden below in this case
1.492     droeschl 7542:         $clientversion ||= $Apache::lonnet::loncaparevs{$clientname};
1.209     albertel 7543: 
1.212     foxr     7544: 		# If the connection type is ssl, but I didn't get my
                   7545: 		# certificate files yet, then I'll drop  back to 
                   7546: 		# insecure (if allowed).
1.532     raeburn  7547: 
                   7548:                 if ($inittype eq "ssl") {
                   7549:                     my $context;
                   7550:                     if ($clientsamedom) {
                   7551:                         $context = 'dom';
                   7552:                         if ($secureconf{'connfrom'}{'dom'} eq 'no') {
                   7553:                             $inittype = "";
                   7554:                         }
                   7555:                     } elsif ($clientsameinst) {
                   7556:                         $context = 'intdom';
                   7557:                         if ($secureconf{'connfrom'}{'intdom'} eq 'no') {
                   7558:                             $inittype = "";
                   7559:                         }
                   7560:                     } else {
                   7561:                         $context = 'other';
                   7562:                         if ($secureconf{'connfrom'}{'other'} eq 'no') {
                   7563:                             $inittype = "";
                   7564:                         }
                   7565:                     }
                   7566:                     if ($inittype eq '') {
                   7567:                         &logthis("<font color=\"blue\"> Domain config set "
                   7568:                                 ."to no ssl for $clientname (context: $context)"
                   7569:                                 ." -- trying insecure auth</font>");
                   7570:                     }
                   7571:                 }
                   7572: 
1.212     foxr     7573: 		if($inittype eq "ssl") {
                   7574: 		    my ($ca, $cert) = lonssl::CertificateFile;
                   7575: 		    my $kfile       = lonssl::KeyFile;
                   7576: 		    if((!$ca)   || 
                   7577: 		       (!$cert) || 
                   7578: 		       (!$kfile)) {
                   7579: 			$inittype = ""; # This forces insecure attempt.
                   7580: 			&logthis("<font color=\"blue\"> Certificates not "
                   7581: 				 ."installed -- trying insecure auth</font>");
1.224     foxr     7582: 		    } else {	# SSL certificates are in place so
1.212     foxr     7583: 		    }		# Leave the inittype alone.
                   7584: 		}
                   7585: 
                   7586: 		if($inittype eq "local") {
1.432     raeburn  7587:                     $clientversion = $perlvar{'lonVersion'};
1.212     foxr     7588: 		    my $key = LocalConnection($client, $remotereq);
                   7589: 		    if($key) {
                   7590: 			Debug("Got local key $key");
                   7591: 			$clientok     = 1;
                   7592: 			my $cipherkey = pack("H32", $key);
                   7593: 			$cipher       = new IDEA($cipherkey);
                   7594: 			print $client "ok:local\n";
1.442     www      7595: 			&logthis('<font color="green">'
1.212     foxr     7596: 				 . "Successful local authentication </font>");
                   7597: 			$keymode = "local"
1.178     foxr     7598: 		    } else {
1.212     foxr     7599: 			Debug("Failed to get local key");
                   7600: 			$clientok = 0;
                   7601: 			shutdown($client, 3);
                   7602: 			close $client;
1.178     foxr     7603: 		    }
1.212     foxr     7604: 		} elsif ($inittype eq "ssl") {
1.532     raeburn  7605: 		    my $key = SSLConnection($client,$clientname);
1.212     foxr     7606: 		    if ($key) {
                   7607: 			$clientok = 1;
                   7608: 			my $cipherkey = pack("H32", $key);
                   7609: 			$cipher       = new IDEA($cipherkey);
                   7610: 			&logthis('<font color="green">'
                   7611: 				 ."Successfull ssl authentication with $clientname </font>");
                   7612: 			$keymode = "ssl";
                   7613: 	     
1.178     foxr     7614: 		    } else {
1.212     foxr     7615: 			$clientok = 0;
                   7616: 			close $client;
1.178     foxr     7617: 		    }
1.212     foxr     7618: 	   
                   7619: 		} else {
                   7620: 		    my $ok = InsecureConnection($client);
                   7621: 		    if($ok) {
                   7622: 			$clientok = 1;
                   7623: 			&logthis('<font color="green">'
                   7624: 				 ."Successful insecure authentication with $clientname </font>");
                   7625: 			print $client "ok\n";
                   7626: 			$keymode = "insecure";
1.178     foxr     7627: 		    } else {
1.212     foxr     7628: 			&logthis('<font color="yellow">'
                   7629: 				  ."Attempted insecure connection disallowed </font>");
                   7630: 			close $client;
                   7631: 			$clientok = 0;
1.178     foxr     7632: 		    }
                   7633: 		}
1.212     foxr     7634: 	    } else {
                   7635: 		&logthis(
                   7636: 			 "<font color='blue'>WARNING: "
                   7637: 			 ."$clientip failed to initialize: >$remotereq< </font>");
                   7638: 		&status('No init '.$clientip);
                   7639: 	    }
                   7640: 	} else {
                   7641: 	    &logthis(
                   7642: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
                   7643: 	    &status('Hung up on '.$clientip);
                   7644: 	}
                   7645:  
                   7646: 	if ($clientok) {
                   7647: # ---------------- New known client connecting, could mean machine online again
1.368     albertel 7648: 	    if (&Apache::lonnet::get_host_ip($currenthostid) ne $clientip 
1.367     albertel 7649: 		&& $clientip ne '127.0.0.1') {
1.375     albertel 7650: 		&Apache::lonnet::reconlonc($clientname);
1.212     foxr     7651: 	    }
                   7652: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
                   7653: 	    &status('Will listen to '.$clientname);
                   7654: # ------------------------------------------------------------ Process requests
                   7655: 	    my $keep_going = 1;
                   7656: 	    my $user_input;
1.556     raeburn  7657: 
1.212     foxr     7658: 	    while(($user_input = get_request) && $keep_going) {
                   7659: 		alarm(120);
                   7660: 		Debug("Main: Got $user_input\n");
                   7661: 		$keep_going = &process_request($user_input);
1.178     foxr     7662: 		alarm(0);
1.212     foxr     7663: 		&status('Listening to '.$clientname." ($keymode)");	   
1.161     foxr     7664: 	    }
1.212     foxr     7665: 
1.59      www      7666: # --------------------------------------------- client unknown or fishy, refuse
1.212     foxr     7667: 	}  else {
1.161     foxr     7668: 	    print $client "refused\n";
                   7669: 	    $client->close();
1.190     albertel 7670: 	    &logthis("<font color='blue'>WARNING: "
1.161     foxr     7671: 		     ."Rejected client $clientip, closing connection</font>");
                   7672: 	}
1.525     raeburn  7673:     }
1.161     foxr     7674:     
1.1       albertel 7675: # =============================================================================
1.161     foxr     7676:     
1.190     albertel 7677:     &logthis("<font color='red'>CRITICAL: "
1.161     foxr     7678: 	     ."Disconnect from $clientip ($clientname)</font>");    
                   7679:     
                   7680:     
                   7681:     # this exit is VERY important, otherwise the child will become
                   7682:     # a producer of more and more children, forking yourself into
                   7683:     # process death.
                   7684:     exit;
1.106     foxr     7685:     
1.78      foxr     7686: }
1.532     raeburn  7687: 
                   7688: #
                   7689: #  Used to determine if a particular client is from the same domain
1.556     raeburn  7690: #  as the current server, or from the same internet domain, and
                   7691: #  also if the client can host sessions for the domain's users.
                   7692: #  A hash is populated with keys set to commands sent by the client
                   7693: #  which may not be executed for this domain.
1.532     raeburn  7694: #
                   7695: #  Optional input -- the client to check for domain and internet domain.
                   7696: #  If not specified, defaults to the package variable: $clientname
                   7697: #
                   7698: #  If called in array context will not set package variables, but will
                   7699: #  instead return an array of two values - (a) true if client is in the
1.556     raeburn  7700: #  same domain as the server, and (b) true if client is in the same 
                   7701: #  internet domain.
1.532     raeburn  7702: #
                   7703: #  If called in scalar context, sets package variables for current client:
                   7704: #
1.556     raeburn  7705: #  $clienthomedom    - LonCAPA domain of homeID for client.
                   7706: #  $clientsamedom    - LonCAPA domain same for this host and client.
                   7707: #  $clientintdom     - LonCAPA "internet domain" for client.
                   7708: #  $clientsameinst   - LonCAPA "internet domain" same for this host & client.
                   7709: #  $clientremoteok   - If current domain permits hosting on this client: 1
                   7710: #  %clientprohibited - Commands prohibited for domain's users for this client.
                   7711: #
                   7712: #  if the host and client have the same "internet domain", then the value
                   7713: #  of $clientremoteok is not used, and no commands are prohibited.
1.532     raeburn  7714: #
                   7715: #  returns 1 to indicate package variables have been set for current client.
                   7716: #
                   7717: 
                   7718: sub set_client_info {
                   7719:     my ($lonhost) = @_;
                   7720:     $lonhost ||= $clientname;
                   7721:     my $clienthost = &Apache::lonnet::hostname($lonhost);
                   7722:     my $clientserverhomeID = &Apache::lonnet::get_server_homeID($clienthost);
                   7723:     my $homedom = &Apache::lonnet::host_domain($clientserverhomeID);
                   7724:     my $samedom = 0;
1.557   ! raeburn  7725:     if ($perlvar{'lonDefDomain'} eq $homedom) {
1.532     raeburn  7726:         $samedom = 1;
                   7727:     }
                   7728:     my $intdom = &Apache::lonnet::internet_dom($clientserverhomeID);
                   7729:     my $sameinst = 0;
                   7730:     if ($intdom ne '') {
                   7731:         my $internet_names = &Apache::lonnet::get_internet_names($currenthostid);
                   7732:         if (ref($internet_names) eq 'ARRAY') {
                   7733:             if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   7734:                 $sameinst = 1;
                   7735:             }
                   7736:         }
                   7737:     }
                   7738:     if (wantarray) {
                   7739:         return ($samedom,$sameinst);
                   7740:     } else {
                   7741:         $clienthomedom = $homedom;
                   7742:         $clientsamedom = $samedom;
                   7743:         $clientintdom = $intdom;
                   7744:         $clientsameinst = $sameinst;
1.556     raeburn  7745:         if ($clientsameinst) {
                   7746:             undef($clientremoteok);
                   7747:             undef(%clientprohibited);
                   7748:         } else {
                   7749:             $clientremoteok = &get_remote_hostable($currentdomainid);
                   7750:             %clientprohibited = &get_prohibited($currentdomainid);
                   7751:         }
1.532     raeburn  7752:         return 1;
                   7753:     }
                   7754: }
                   7755: 
1.261     foxr     7756: #
                   7757: #   Determine if a user is an author for the indicated domain.
                   7758: #
                   7759: # Parameters:
                   7760: #    domain          - domain to check in .
                   7761: #    user            - Name of user to check.
                   7762: #
                   7763: # Return:
                   7764: #     1             - User is an author for domain.
                   7765: #     0             - User is not an author for domain.
                   7766: sub is_author {
                   7767:     my ($domain, $user) = @_;
                   7768: 
                   7769:     &Debug("is_author: $user @ $domain");
                   7770: 
                   7771:     my $hashref = &tie_user_hash($domain, $user, "roles",
                   7772: 				 &GDBM_READER());
                   7773: 
                   7774:     #  Author role should show up as a key /domain/_au
1.78      foxr     7775: 
1.321     albertel 7776:     my $value;
1.487     foxr     7777:     if ($hashref) {
1.78      foxr     7778: 
1.487     foxr     7779: 	my $key    = "/$domain/_au";
                   7780: 	if (defined($hashref)) {
                   7781: 	    $value = $hashref->{$key};
                   7782: 	    if(!untie_user_hash($hashref)) {
                   7783: 		return 'error: ' .  ($!+0)." untie (GDBM) Failed";
                   7784: 	    }
                   7785: 	}
                   7786: 	
                   7787: 	if(defined($value)) {
                   7788: 	    &Debug("$user @ $domain is an author");
                   7789: 	}
                   7790:     } else {
                   7791: 	return 'error: '.($!+0)." tie (GDBM) Failed";
1.261     foxr     7792:     }
                   7793: 
                   7794:     return defined($value);
                   7795: }
1.78      foxr     7796: #
                   7797: #   Checks to see if the input roleput request was to set
1.482     www      7798: # an author role.  If so, creates construction space 
1.78      foxr     7799: # Parameters:
                   7800: #    request   - The request sent to the rolesput subchunk.
                   7801: #                We're looking for  /domain/_au
                   7802: #    domain    - The domain in which the user is having roles doctored.
                   7803: #    user      - Name of the user for which the role is being put.
                   7804: #    authtype  - The authentication type associated with the user.
                   7805: #
1.289     albertel 7806: sub manage_permissions {
1.192     foxr     7807:     my ($request, $domain, $user, $authtype) = @_;
1.78      foxr     7808:     # See if the request is of the form /$domain/_au
1.289     albertel 7809:     if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
1.484     raeburn  7810:         my $path=$perlvar{'lonDocRoot'}."/priv/$domain";
1.482     www      7811:         unless (-e $path) {        
                   7812:            mkdir($path);
                   7813:         }
                   7814:         unless (-e $path.'/'.$user) {
                   7815:            mkdir($path.'/'.$user);
                   7816:         }
1.78      foxr     7817:     }
                   7818: }
1.222     foxr     7819: 
                   7820: 
                   7821: #
                   7822: #  Return the full path of a user password file, whether it exists or not.
                   7823: # Parameters:
                   7824: #   domain     - Domain in which the password file lives.
                   7825: #   user       - name of the user.
                   7826: # Returns:
                   7827: #    Full passwd path:
                   7828: #
                   7829: sub password_path {
                   7830:     my ($domain, $user) = @_;
1.264     albertel 7831:     return &propath($domain, $user).'/passwd';
1.222     foxr     7832: }
                   7833: 
                   7834: #   Password Filename
                   7835: #   Returns the path to a passwd file given domain and user... only if
                   7836: #  it exists.
                   7837: # Parameters:
                   7838: #   domain    - Domain in which to search.
                   7839: #   user      - username.
                   7840: # Returns:
                   7841: #   - If the password file exists returns its path.
                   7842: #   - If the password file does not exist, returns undefined.
                   7843: #
                   7844: sub password_filename {
                   7845:     my ($domain, $user) = @_;
                   7846: 
                   7847:     Debug ("PasswordFilename called: dom = $domain user = $user");
                   7848: 
                   7849:     my $path  = &password_path($domain, $user);
                   7850:     Debug("PasswordFilename got path: $path");
                   7851:     if(-e $path) {
                   7852: 	return $path;
                   7853:     } else {
                   7854: 	return undef;
                   7855:     }
                   7856: }
                   7857: 
                   7858: #
                   7859: #   Rewrite the contents of the user's passwd file.
                   7860: #  Parameters:
                   7861: #    domain    - domain of the user.
                   7862: #    name      - User's name.
                   7863: #    contents  - New contents of the file.
1.533     raeburn  7864: #    saveold   - (optional). If true save old file in a passwd.bak file.
1.222     foxr     7865: # Returns:
                   7866: #   0    - Failed.
                   7867: #   1    - Success.
                   7868: #
                   7869: sub rewrite_password_file {
1.533     raeburn  7870:     my ($domain, $user, $contents, $saveold) = @_;
1.222     foxr     7871: 
                   7872:     my $file = &password_filename($domain, $user);
                   7873:     if (defined $file) {
1.533     raeburn  7874:         if ($saveold) {
                   7875:             my $bakfile = $file.'.bak';
                   7876:             if (CopyFile($file,$bakfile)) {
                   7877:                 chmod(0400,$bakfile);
                   7878:                 &logthis("Old password saved in passwd.bak for internally authenticated user: $user:$domain");
                   7879:             } else {
                   7880:                 &logthis("Failed to save old password in passwd.bak for internally authenticated user: $user:$domain");
                   7881:             }
                   7882:         }
1.222     foxr     7883: 	my $pf = IO::File->new(">$file");
                   7884: 	if($pf) {
                   7885: 	    print $pf "$contents\n";
                   7886: 	    return 1;
                   7887: 	} else {
                   7888: 	    return 0;
                   7889: 	}
                   7890:     } else {
                   7891: 	return 0;
                   7892:     }
                   7893: 
                   7894: }
                   7895: 
1.78      foxr     7896: #
1.222     foxr     7897: #   get_auth_type - Determines the authorization type of a user in a domain.
1.78      foxr     7898: 
                   7899: #     Returns the authorization type or nouser if there is no such user.
                   7900: #
1.436     raeburn  7901: sub get_auth_type {
1.192     foxr     7902:     my ($domain, $user)  = @_;
1.78      foxr     7903: 
1.222     foxr     7904:     Debug("get_auth_type( $domain, $user ) \n");
1.78      foxr     7905:     my $proname    = &propath($domain, $user); 
                   7906:     my $passwdfile = "$proname/passwd";
                   7907:     if( -e $passwdfile ) {
                   7908: 	my $pf = IO::File->new($passwdfile);
                   7909: 	my $realpassword = <$pf>;
                   7910: 	chomp($realpassword);
1.79      foxr     7911: 	Debug("Password info = $realpassword\n");
1.78      foxr     7912: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79      foxr     7913: 	Debug("Authtype = $authtype, content = $contentpwd\n");
1.259     raeburn  7914: 	return "$authtype:$contentpwd";     
1.224     foxr     7915:     } else {
1.79      foxr     7916: 	Debug("Returning nouser");
1.78      foxr     7917: 	return "nouser";
                   7918:     }
1.1       albertel 7919: }
                   7920: 
1.220     foxr     7921: #
                   7922: #  Validate a user given their domain, name and password.  This utility
                   7923: #  function is used by both  AuthenticateHandler and ChangePasswordHandler
                   7924: #  to validate the login credentials of a user.
                   7925: # Parameters:
                   7926: #    $domain    - The domain being logged into (this is required due to
                   7927: #                 the capability for multihomed systems.
                   7928: #    $user      - The name of the user being validated.
                   7929: #    $password  - The user's propoposed password.
                   7930: #
                   7931: # Returns:
                   7932: #     1        - The domain,user,pasword triplet corresponds to a valid
                   7933: #                user.
                   7934: #     0        - The domain,user,password triplet is not a valid user.
                   7935: #
                   7936: sub validate_user {
1.396     raeburn  7937:     my ($domain, $user, $password, $checkdefauth) = @_;
1.220     foxr     7938: 
                   7939:     # Why negative ~pi you may well ask?  Well this function is about
                   7940:     # authentication, and therefore very important to get right.
                   7941:     # I've initialized the flag that determines whether or not I've 
                   7942:     # validated correctly to a value it's not supposed to get.
                   7943:     # At the end of this function. I'll ensure that it's not still that
                   7944:     # value so we don't just wind up returning some accidental value
                   7945:     # as a result of executing an unforseen code path that
1.249     foxr     7946:     # did not set $validated.  At the end of valid execution paths,
                   7947:     # validated shoule be 1 for success or 0 for failuer.
1.220     foxr     7948: 
                   7949:     my $validated = -3.14159;
                   7950: 
                   7951:     #  How we authenticate is determined by the type of authentication
                   7952:     #  the user has been assigned.  If the authentication type is
                   7953:     #  "nouser", the user does not exist so we will return 0.
                   7954: 
1.222     foxr     7955:     my $contents = &get_auth_type($domain, $user);
1.220     foxr     7956:     my ($howpwd, $contentpwd) = split(/:/, $contents);
                   7957: 
                   7958:     my $null = pack("C",0);	# Used by kerberos auth types.
                   7959: 
1.395     raeburn  7960:     if ($howpwd eq 'nouser') {
1.396     raeburn  7961:         if ($checkdefauth) {
                   7962:             my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   7963:             if ($domdefaults{'auth_def'} eq 'localauth') {
                   7964:                 $howpwd = $domdefaults{'auth_def'};
                   7965:                 $contentpwd = $domdefaults{'auth_arg_def'};
                   7966:             } elsif ((($domdefaults{'auth_def'} eq 'krb4') || 
                   7967:                       ($domdefaults{'auth_def'} eq 'krb5')) &&
                   7968:                      ($domdefaults{'auth_arg_def'} ne '')) {
                   7969:                 $howpwd = $domdefaults{'auth_def'};
                   7970:                 $contentpwd = $domdefaults{'auth_arg_def'}; 
                   7971:             }
1.395     raeburn  7972:         }
1.533     raeburn  7973:     }
1.220     foxr     7974:     if ($howpwd ne 'nouser') {
                   7975: 	if($howpwd eq "internal") { # Encrypted is in local password file.
1.518     raeburn  7976:             if (length($contentpwd) == 13) {
                   7977:                 $validated = (crypt($password,$contentpwd) eq $contentpwd);
                   7978:                 if ($validated) {
1.533     raeburn  7979:                     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   7980:                     if ($domdefaults{'intauth_switch'}) {
                   7981:                         my $ncpass = &hash_passwd($domain,$password);
                   7982:                         my $saveold;
                   7983:                         if ($domdefaults{'intauth_switch'} == 2) {
                   7984:                             $saveold = 1;
                   7985:                         }
                   7986:                         if (&rewrite_password_file($domain,$user,"$howpwd:$ncpass",$saveold)) {
                   7987:                             &update_passwd_history($user,$domain,$howpwd,'conversion');
                   7988:                             &logthis("Validated password hashed with bcrypt for $user:$domain");
                   7989:                         }
1.518     raeburn  7990:                     }
                   7991:                 }
                   7992:             } else {
1.533     raeburn  7993:                 $validated = &check_internal_passwd($password,$contentpwd,$domain,$user);
1.518     raeburn  7994:             }
1.220     foxr     7995: 	}
                   7996: 	elsif ($howpwd eq "unix") { # User is a normal unix user.
                   7997: 	    $contentpwd = (getpwnam($user))[1];
                   7998: 	    if($contentpwd) {
                   7999: 		if($contentpwd eq 'x') { # Shadow password file...
                   8000: 		    my $pwauth_path = "/usr/local/sbin/pwauth";
                   8001: 		    open PWAUTH,  "|$pwauth_path" or
                   8002: 			die "Cannot invoke authentication";
                   8003: 		    print PWAUTH "$user\n$password\n";
                   8004: 		    close PWAUTH;
                   8005: 		    $validated = ! $?;
                   8006: 
                   8007: 		} else { 	         # Passwords in /etc/passwd. 
                   8008: 		    $validated = (crypt($password,
                   8009: 					$contentpwd) eq $contentpwd);
                   8010: 		}
                   8011: 	    } else {
                   8012: 		$validated = 0;
                   8013: 	    }
1.439     raeburn  8014: 	} elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
                   8015:             my $checkwithkrb5 = 0;
                   8016:             if ($dist =~/^fedora(\d+)$/) {
                   8017:                 if ($1 > 11) {
                   8018:                     $checkwithkrb5 = 1;
                   8019:                 }
                   8020:             } elsif ($dist =~ /^suse([\d.]+)$/) {
                   8021:                 if ($1 > 11.1) {
                   8022:                     $checkwithkrb5 = 1; 
                   8023:                 }
                   8024:             }
                   8025:             if ($checkwithkrb5) {
                   8026:                 $validated = &krb5_authen($password,$null,$user,$contentpwd);
                   8027:             } else {
                   8028:                 $validated = &krb4_authen($password,$null,$user,$contentpwd);
                   8029:             }
1.224     foxr     8030: 	} elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
1.439     raeburn  8031:             $validated = &krb5_authen($password,$null,$user,$contentpwd);
1.224     foxr     8032: 	} elsif ($howpwd eq "localauth") { 
1.220     foxr     8033: 	    #  Authenticate via installation specific authentcation method:
                   8034: 	    $validated = &localauth::localauth($user, 
                   8035: 					       $password, 
1.353     albertel 8036: 					       $contentpwd,
                   8037: 					       $domain);
1.358     albertel 8038: 	    if ($validated < 0) {
1.357     albertel 8039: 		&logthis("localauth for $contentpwd $user:$domain returned a $validated");
                   8040: 		$validated = 0;
                   8041: 	    }
1.224     foxr     8042: 	} else {			# Unrecognized auth is also bad.
1.220     foxr     8043: 	    $validated = 0;
                   8044: 	}
                   8045:     } else {
                   8046: 	$validated = 0;
                   8047:     }
                   8048:     #
                   8049:     #  $validated has the correct stat of the authentication:
                   8050:     #
                   8051: 
                   8052:     unless ($validated != -3.14159) {
1.249     foxr     8053: 	#  I >really really< want to know if this happens.
                   8054: 	#  since it indicates that user authentication is badly
                   8055: 	#  broken in some code path.
                   8056:         #
                   8057: 	die "ValidateUser - failed to set the value of validated $domain, $user $password";
1.220     foxr     8058:     }
                   8059:     return $validated;
                   8060: }
                   8061: 
1.518     raeburn  8062: sub check_internal_passwd {
1.533     raeburn  8063:     my ($plainpass,$stored,$domain,$user) = @_;
1.518     raeburn  8064:     my (undef,$method,@rest) = split(/!/,$stored);
1.533     raeburn  8065:     if ($method eq 'bcrypt') {
1.518     raeburn  8066:         my $result = &hash_passwd($domain,$plainpass,@rest);
                   8067:         if ($result ne $stored) {
                   8068:             return 0;
                   8069:         }
1.533     raeburn  8070:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   8071:         if ($domdefaults{'intauth_check'}) {
                   8072:             # Upgrade to a larger number of rounds if necessary
                   8073:             my $defaultcost = $domdefaults{'intauth_cost'};
                   8074:             if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
                   8075:                 $defaultcost = 10;
                   8076:             }
                   8077:             if (int($rest[0])<int($defaultcost)) {
                   8078:                 if ($domdefaults{'intauth_check'} == 1) { 
                   8079:                     my $ncpass = &hash_passwd($domain,$plainpass);
                   8080:                     if (&rewrite_password_file($domain,$user,"internal:$ncpass")) {
                   8081:                         &update_passwd_history($user,$domain,'internal','update cost');
                   8082:                         &logthis("Validated password hashed with bcrypt for $user:$domain");
                   8083:                     }
                   8084:                     return 1;
                   8085:                 } elsif ($domdefaults{'intauth_check'} == 2) {
                   8086:                     return 0;
                   8087:                 }
                   8088:             }
                   8089:         } else {
                   8090:             return 1;
1.518     raeburn  8091:         }
                   8092:     }
                   8093:     return 0;
                   8094: }
                   8095: 
                   8096: sub get_last_authchg {
                   8097:     my ($domain,$user) = @_;
                   8098:     my $lastmod;
                   8099:     my $logname = &propath($domain,$user).'/passwd.log';
                   8100:     if (-e "$logname") {
                   8101:         $lastmod = (stat("$logname"))[9];
                   8102:     }
                   8103:     return $lastmod;
                   8104: }
                   8105: 
1.439     raeburn  8106: sub krb4_authen {
                   8107:     my ($password,$null,$user,$contentpwd) = @_;
                   8108:     my $validated = 0;
                   8109:     if (!($password =~ /$null/) ) {  # Null password not allowed.
                   8110:         eval {
                   8111:             require Authen::Krb4;
                   8112:         };
                   8113:         if (!$@) {
                   8114:             my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
                   8115:                                                        "",
                   8116:                                                        $contentpwd,,
                   8117:                                                        'krbtgt',
                   8118:                                                        $contentpwd,
                   8119:                                                        1,
                   8120:                                                        $password);
                   8121:             if(!$k4error) {
                   8122:                 $validated = 1;
                   8123:             } else {
                   8124:                 $validated = 0;
                   8125:                 &logthis('krb4: '.$user.', '.$contentpwd.', '.
                   8126:                           &Authen::Krb4::get_err_txt($Authen::Krb4::error));
                   8127:             }
                   8128:         } else {
                   8129:             $validated = krb5_authen($password,$null,$user,$contentpwd);
                   8130:         }
                   8131:     }
                   8132:     return $validated;
                   8133: }
                   8134: 
                   8135: sub krb5_authen {
                   8136:     my ($password,$null,$user,$contentpwd) = @_;
                   8137:     my $validated = 0;
                   8138:     if(!($password =~ /$null/)) { # Null password not allowed.
                   8139:         my $krbclient = &Authen::Krb5::parse_name($user.'@'
                   8140:                                                   .$contentpwd);
                   8141:         my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
                   8142:         my $krbserver  = &Authen::Krb5::parse_name($krbservice);
                   8143:         my $credentials= &Authen::Krb5::cc_default();
                   8144:         $credentials->initialize(&Authen::Krb5::parse_name($user.'@'
                   8145:                                                             .$contentpwd));
                   8146:         my $krbreturn;
                   8147:         if (exists(&Authen::Krb5::get_init_creds_password)) {
                   8148:             $krbreturn =
                   8149:                 &Authen::Krb5::get_init_creds_password($krbclient,$password,
                   8150:                                                           $krbservice);
                   8151:             $validated = (ref($krbreturn) eq 'Authen::Krb5::Creds');
                   8152:         } else {
                   8153:             $krbreturn  =
                   8154:                 &Authen::Krb5::get_in_tkt_with_password($krbclient,$krbserver,
                   8155:                                                          $password,$credentials);
                   8156:             $validated = ($krbreturn == 1);
                   8157:         }
                   8158:         if (!$validated) {
                   8159:             &logthis('krb5: '.$user.', '.$contentpwd.', '.
                   8160:                      &Authen::Krb5::error());
                   8161:         }
                   8162:     }
                   8163:     return $validated;
                   8164: }
1.220     foxr     8165: 
1.84      albertel 8166: sub addline {
                   8167:     my ($fname,$hostid,$ip,$newline)=@_;
                   8168:     my $contents;
                   8169:     my $found=0;
1.355     albertel 8170:     my $expr='^'.quotemeta($hostid).':'.quotemeta($ip).':';
1.134     albertel 8171:     my $sh;
1.84      albertel 8172:     if ($sh=IO::File->new("$fname.subscription")) {
                   8173: 	while (my $subline=<$sh>) {
                   8174: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
                   8175: 	}
                   8176: 	$sh->close();
                   8177:     }
                   8178:     $sh=IO::File->new(">$fname.subscription");
                   8179:     if ($contents) { print $sh $contents; }
                   8180:     if ($newline) { print $sh $newline; }
                   8181:     $sh->close();
                   8182:     return $found;
1.86      www      8183: }
                   8184: 
1.234     foxr     8185: sub get_chat {
1.324     raeburn  8186:     my ($cdom,$cname,$udom,$uname,$group)=@_;
1.310     albertel 8187: 
1.87      www      8188:     my @entries=();
1.324     raeburn  8189:     my $namespace = 'nohist_chatroom';
                   8190:     my $namespace_inroom = 'nohist_inchatroom';
1.335     albertel 8191:     if ($group ne '') {
1.324     raeburn  8192:         $namespace .= '_'.$group;
                   8193:         $namespace_inroom .= '_'.$group;
                   8194:     }
                   8195:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 8196: 				 &GDBM_READER());
                   8197:     if ($hashref) {
                   8198: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.311     albertel 8199: 	&untie_user_hash($hashref);
1.123     www      8200:     }
1.124     www      8201:     my @participants=();
1.134     albertel 8202:     my $cutoff=time-60;
1.324     raeburn  8203:     $hashref = &tie_user_hash($cdom, $cname, $namespace_inroom,
1.310     albertel 8204: 			      &GDBM_WRCREAT());
                   8205:     if ($hashref) {
                   8206:         $hashref->{$uname.':'.$udom}=time;
                   8207:         foreach my $user (sort(keys(%$hashref))) {
                   8208: 	    if ($hashref->{$user}>$cutoff) {
                   8209: 		push(@participants, 'active_participant:'.$user);
1.123     www      8210:             }
                   8211:         }
1.311     albertel 8212:         &untie_user_hash($hashref);
1.86      www      8213:     }
1.124     www      8214:     return (@participants,@entries);
1.86      www      8215: }
                   8216: 
1.234     foxr     8217: sub chat_add {
1.324     raeburn  8218:     my ($cdom,$cname,$newchat,$group)=@_;
1.88      albertel 8219:     my @entries=();
1.142     www      8220:     my $time=time;
1.324     raeburn  8221:     my $namespace = 'nohist_chatroom';
                   8222:     my $logfile = 'chatroom.log';
1.335     albertel 8223:     if ($group ne '') {
1.324     raeburn  8224:         $namespace .= '_'.$group;
                   8225:         $logfile = 'chatroom_'.$group.'.log';
                   8226:     }
                   8227:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 8228: 				 &GDBM_WRCREAT());
                   8229:     if ($hashref) {
                   8230: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.88      albertel 8231: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
                   8232: 	my ($thentime,$idnum)=split(/\_/,$lastid);
                   8233: 	my $newid=$time.'_000000';
                   8234: 	if ($thentime==$time) {
                   8235: 	    $idnum=~s/^0+//;
                   8236: 	    $idnum++;
                   8237: 	    $idnum=substr('000000'.$idnum,-6,6);
                   8238: 	    $newid=$time.'_'.$idnum;
                   8239: 	}
1.310     albertel 8240: 	$hashref->{$newid}=$newchat;
1.88      albertel 8241: 	my $expired=$time-3600;
1.310     albertel 8242: 	foreach my $comment (keys(%$hashref)) {
                   8243: 	    my ($thistime) = ($comment=~/(\d+)\_/);
1.88      albertel 8244: 	    if ($thistime<$expired) {
1.310     albertel 8245: 		delete $hashref->{$comment};
1.88      albertel 8246: 	    }
                   8247: 	}
1.310     albertel 8248: 	{
                   8249: 	    my $proname=&propath($cdom,$cname);
1.324     raeburn  8250: 	    if (open(CHATLOG,">>$proname/$logfile")) { 
1.310     albertel 8251: 		print CHATLOG ("$time:".&unescape($newchat)."\n");
                   8252: 	    }
                   8253: 	    close(CHATLOG);
1.142     www      8254: 	}
1.311     albertel 8255: 	&untie_user_hash($hashref);
1.86      www      8256:     }
1.84      albertel 8257: }
                   8258: 
                   8259: sub unsub {
                   8260:     my ($fname,$clientip)=@_;
                   8261:     my $result;
1.188     foxr     8262:     my $unsubs = 0;		# Number of successful unsubscribes:
                   8263: 
                   8264: 
                   8265:     # An old way subscriptions were handled was to have a 
                   8266:     # subscription marker file:
                   8267: 
                   8268:     Debug("Attempting unlink of $fname.$clientname");
1.161     foxr     8269:     if (unlink("$fname.$clientname")) {
1.188     foxr     8270: 	$unsubs++;		# Successful unsub via marker file.
                   8271:     } 
                   8272: 
                   8273:     # The more modern way to do it is to have a subscription list
                   8274:     # file:
                   8275: 
1.84      albertel 8276:     if (-e "$fname.subscription") {
1.161     foxr     8277: 	my $found=&addline($fname,$clientname,$clientip,'');
1.188     foxr     8278: 	if ($found) { 
                   8279: 	    $unsubs++;
                   8280: 	}
                   8281:     } 
                   8282: 
                   8283:     #  If either or both of these mechanisms succeeded in unsubscribing a 
                   8284:     #  resource we can return ok:
                   8285: 
                   8286:     if($unsubs) {
                   8287: 	$result = "ok\n";
1.84      albertel 8288:     } else {
1.188     foxr     8289: 	$result = "not_subscribed\n";
1.84      albertel 8290:     }
1.188     foxr     8291: 
1.84      albertel 8292:     return $result;
                   8293: }
                   8294: 
1.101     www      8295: sub currentversion {
                   8296:     my $fname=shift;
                   8297:     my $version=-1;
                   8298:     my $ulsdir='';
                   8299:     if ($fname=~/^(.+)\/[^\/]+$/) {
                   8300:        $ulsdir=$1;
                   8301:     }
1.114     albertel 8302:     my ($fnamere1,$fnamere2);
                   8303:     # remove version if already specified
1.101     www      8304:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114     albertel 8305:     # get the bits that go before and after the version number
                   8306:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
                   8307: 	$fnamere1=$1;
                   8308: 	$fnamere2='.'.$2;
                   8309:     }
1.101     www      8310:     if (-e $fname) { $version=1; }
                   8311:     if (-e $ulsdir) {
1.134     albertel 8312: 	if(-d $ulsdir) {
                   8313: 	    if (opendir(LSDIR,$ulsdir)) {
                   8314: 		my $ulsfn;
                   8315: 		while ($ulsfn=readdir(LSDIR)) {
1.101     www      8316: # see if this is a regular file (ignore links produced earlier)
1.134     albertel 8317: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
                   8318: 		    unless (-l $thisfile) {
1.160     www      8319: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134     albertel 8320: 			    if ($1>$version) { $version=$1; }
                   8321: 			}
                   8322: 		    }
                   8323: 		}
                   8324: 		closedir(LSDIR);
                   8325: 		$version++;
                   8326: 	    }
                   8327: 	}
                   8328:     }
                   8329:     return $version;
1.101     www      8330: }
                   8331: 
                   8332: sub thisversion {
                   8333:     my $fname=shift;
                   8334:     my $version=-1;
                   8335:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
                   8336: 	$version=$1;
                   8337:     }
                   8338:     return $version;
                   8339: }
                   8340: 
1.84      albertel 8341: sub subscribe {
                   8342:     my ($userinput,$clientip)=@_;
                   8343:     my $result;
1.293     albertel 8344:     my ($cmd,$fname)=split(/:/,$userinput,2);
1.84      albertel 8345:     my $ownership=&ishome($fname);
                   8346:     if ($ownership eq 'owner') {
1.101     www      8347: # explitly asking for the current version?
                   8348:         unless (-e $fname) {
                   8349:             my $currentversion=&currentversion($fname);
                   8350: 	    if (&thisversion($fname)==$currentversion) {
                   8351:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
                   8352: 		    my $root=$1;
                   8353:                     my $extension=$2;
                   8354:                     symlink($root.'.'.$extension,
                   8355:                             $root.'.'.$currentversion.'.'.$extension);
1.102     www      8356:                     unless ($extension=~/\.meta$/) {
                   8357:                        symlink($root.'.'.$extension.'.meta',
                   8358:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
                   8359: 		    }
1.101     www      8360:                 }
                   8361:             }
                   8362:         }
1.84      albertel 8363: 	if (-e $fname) {
                   8364: 	    if (-d $fname) {
                   8365: 		$result="directory\n";
                   8366: 	    } else {
1.161     foxr     8367: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134     albertel 8368: 		my $now=time;
1.161     foxr     8369: 		my $found=&addline($fname,$clientname,$clientip,
                   8370: 				   "$clientname:$clientip:$now\n");
1.84      albertel 8371: 		if ($found) { $result="$fname\n"; }
                   8372: 		# if they were subscribed to only meta data, delete that
                   8373:                 # subscription, when you subscribe to a file you also get
                   8374:                 # the metadata
                   8375: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
                   8376: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
1.476     raeburn  8377:                 my $protocol = $Apache::lonnet::protocol{$perlvar{'lonHostID'}};
                   8378:                 $protocol = 'http' if ($protocol ne 'https');
                   8379: 		$fname=$protocol.'://'.&Apache::lonnet::hostname($perlvar{'lonHostID'})."/".$fname;
1.84      albertel 8380: 		$result="$fname\n";
                   8381: 	    }
                   8382: 	} else {
                   8383: 	    $result="not_found\n";
                   8384: 	}
                   8385:     } else {
                   8386: 	$result="rejected\n";
                   8387:     }
                   8388:     return $result;
                   8389: }
1.287     foxr     8390: #  Change the passwd of a unix user.  The caller must have
                   8391: #  first verified that the user is a loncapa user.
                   8392: #
                   8393: # Parameters:
                   8394: #    user      - Unix user name to change.
                   8395: #    pass      - New password for the user.
                   8396: # Returns:
                   8397: #    ok    - if success
                   8398: #    other - Some meaningfule error message string.
                   8399: # NOTE:
                   8400: #    invokes a setuid script to change the passwd.
                   8401: sub change_unix_password {
                   8402:     my ($user, $pass) = @_;
                   8403: 
                   8404:     &Debug("change_unix_password");
                   8405:     my $execdir=$perlvar{'lonDaemons'};
                   8406:     &Debug("Opening lcpasswd pipeline");
                   8407:     my $pf = IO::File->new("|$execdir/lcpasswd > "
                   8408: 			   ."$perlvar{'lonDaemons'}"
                   8409: 			   ."/logs/lcpasswd.log");
                   8410:     print $pf "$user\n$pass\n$pass\n";
                   8411:     close $pf;
                   8412:     my $err = $?;
                   8413:     return ($err < @passwderrors) ? $passwderrors[$err] : 
                   8414: 	"pwchange_falure - unknown error";
                   8415: 
                   8416:     
                   8417: }
                   8418: 
1.91      albertel 8419: 
                   8420: sub make_passwd_file {
1.518     raeburn  8421:     my ($uname,$udom,$umode,$npass,$passfilename,$action)=@_;
1.390     raeburn  8422:     my $result="ok";
1.91      albertel 8423:     if ($umode eq 'krb4' or $umode eq 'krb5') {
                   8424: 	{
                   8425: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8426: 	    if ($pf) {
                   8427: 		print $pf "$umode:$npass\n";
1.518     raeburn  8428:                 &update_passwd_history($uname,$udom,$umode,$action);
1.261     foxr     8429: 	    } else {
                   8430: 		$result = "pass_file_failed_error";
                   8431: 	    }
1.91      albertel 8432: 	}
                   8433:     } elsif ($umode eq 'internal') {
1.518     raeburn  8434:         my $ncpass = &hash_passwd($udom,$npass);
1.91      albertel 8435: 	{
                   8436: 	    &Debug("Creating internal auth");
                   8437: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8438: 	    if($pf) {
1.518     raeburn  8439: 		print $pf "internal:$ncpass\n";
                   8440:                 &update_passwd_history($uname,$udom,$umode,$action); 
1.261     foxr     8441: 	    } else {
                   8442: 		$result = "pass_file_failed_error";
                   8443: 	    }
1.91      albertel 8444: 	}
                   8445:     } elsif ($umode eq 'localauth') {
                   8446: 	{
                   8447: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8448: 	    if($pf) {
                   8449: 		print $pf "localauth:$npass\n";
1.524     raeburn  8450:                 &update_passwd_history($uname,$udom,$umode,$action);
1.261     foxr     8451: 	    } else {
                   8452: 		$result = "pass_file_failed_error";
                   8453: 	    }
1.91      albertel 8454: 	}
                   8455:     } elsif ($umode eq 'unix') {
1.502     raeburn  8456: 	&logthis(">>>Attempt to create unix account blocked -- unix auth not available for new users.");
                   8457: 	$result="no_new_unix_accounts";
1.91      albertel 8458:     } elsif ($umode eq 'none') {
                   8459: 	{
1.223     foxr     8460: 	    my $pf = IO::File->new("> $passfilename");
1.261     foxr     8461: 	    if($pf) {
                   8462: 		print $pf "none:\n";
                   8463: 	    } else {
                   8464: 		$result = "pass_file_failed_error";
                   8465: 	    }
1.91      albertel 8466: 	}
1.543     raeburn  8467:     } elsif ($umode eq 'lti') {
                   8468:         my $pf = IO::File->new(">$passfilename");
                   8469:         if($pf) {
                   8470:             print $pf "lti:\n";
                   8471:             &update_passwd_history($uname,$udom,$umode,$action);
                   8472:         } else {
                   8473:             $result = "pass_file_failed_error";
                   8474:         }
1.91      albertel 8475:     } else {
1.390     raeburn  8476: 	$result="auth_mode_error";
1.91      albertel 8477:     }
                   8478:     return $result;
1.121     albertel 8479: }
                   8480: 
1.265     albertel 8481: sub convert_photo {
                   8482:     my ($start,$dest)=@_;
                   8483:     system("convert $start $dest");
                   8484: }
                   8485: 
1.121     albertel 8486: sub sethost {
                   8487:     my ($remotereq) = @_;
                   8488:     my (undef,$hostid)=split(/:/,$remotereq);
1.322     albertel 8489:     # ignore sethost if we are already correct
                   8490:     if ($hostid eq $currenthostid) {
                   8491: 	return 'ok';
                   8492:     }
                   8493: 
1.121     albertel 8494:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
1.368     albertel 8495:     if (&Apache::lonnet::get_host_ip($perlvar{'lonHostID'}) 
                   8496: 	eq &Apache::lonnet::get_host_ip($hostid)) {
1.200     matthew  8497: 	$currenthostid  =$hostid;
1.369     albertel 8498: 	$currentdomainid=&Apache::lonnet::host_domain($hostid);
1.556     raeburn  8499:         &set_client_info();
1.443     www      8500: #	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
1.121     albertel 8501:     } else {
                   8502: 	&logthis("Requested host id $hostid not an alias of ".
                   8503: 		 $perlvar{'lonHostID'}." refusing connection");
                   8504: 	return 'unable_to_set';
                   8505:     }
                   8506:     return 'ok';
                   8507: }
                   8508: 
                   8509: sub version {
                   8510:     my ($userinput)=@_;
                   8511:     $remoteVERSION=(split(/:/,$userinput))[1];
                   8512:     return "version:$VERSION";
1.127     albertel 8513: }
1.178     foxr     8514: 
1.447     raeburn  8515: sub get_usersession_config {
                   8516:     my ($dom,$name) = @_;
                   8517:     my ($usersessionconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8518:     if (defined($cached)) {
                   8519:         return $usersessionconf;
                   8520:     } else {
                   8521:         my %domconfig = &Apache::lonnet::get_dom('configuration',['usersessions'],$dom);
1.525     raeburn  8522:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'usersessions'},3600);
                   8523:         return $domconfig{'usersessions'};
1.447     raeburn  8524:     }
                   8525:     return;
                   8526: }
1.200     matthew  8527: 
1.534     raeburn  8528: sub get_usersearch_config {
                   8529:     my ($dom,$name) = @_;
                   8530:     my ($usersearchconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8531:     if (defined($cached)) {
                   8532:         return $usersearchconf;
                   8533:     } else {
                   8534:         my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$dom);
                   8535:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'directorysrch'},600);
                   8536:         return $domconfig{'directorysrch'};
                   8537:     }
                   8538:     return;
                   8539: }
                   8540: 
1.525     raeburn  8541: sub get_prohibited {
                   8542:     my ($dom) = @_;
                   8543:     my $name = 'trust';
                   8544:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8545:     unless (defined($cached)) {
                   8546:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$dom);
                   8547:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'trust'},3600);
                   8548:         $trustconfig = $domconfig{'trust'};
                   8549:     }
                   8550:     my %prohibited;
                   8551:     if (ref($trustconfig)) {
                   8552:         foreach my $prefix (keys(%{$trustconfig})) {
                   8553:             if (ref($trustconfig->{$prefix}) eq 'HASH') {
                   8554:                 my $reject;
                   8555:                 if (ref($trustconfig->{$prefix}->{'exc'}) eq 'ARRAY') {
                   8556:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'exc'}})) {
                   8557:                         $reject = 1;
                   8558:                     }
                   8559:                 }
                   8560:                 if (ref($trustconfig->{$prefix}->{'inc'}) eq 'ARRAY') {
                   8561:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'inc'}})) {
                   8562:                         $reject = 0;
                   8563:                     } else {
                   8564:                         $reject = 1;
                   8565:                     }
                   8566:                 }
                   8567:                 if ($reject) {
                   8568:                     $prohibited{$prefix} = 1;
                   8569:                 }
                   8570:             }
                   8571:         }
                   8572:     }
                   8573:     return %prohibited;
                   8574: }
1.450     raeburn  8575: 
1.556     raeburn  8576: sub get_remote_hostable {
                   8577:     my ($dom) = @_;
                   8578:     my $result;
                   8579:     if ($clientintdom) {
                   8580:         $result = 1;
                   8581:         my $remsessconf = &get_usersession_config($dom,'remotesession');
                   8582:         if (ref($remsessconf) eq 'HASH') {
                   8583:             if (ref($remsessconf->{'remote'}) eq 'HASH') {
                   8584:                 if (ref($remsessconf->{'remote'}->{'excludedomain'}) eq 'ARRAY') {
                   8585:                     if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'excludedomain'}})) {
                   8586:                         $result = 0;
                   8587:                     }
                   8588:                 }
                   8589:                 if (ref($remsessconf->{'remote'}->{'includedomain'}) eq 'ARRAY') {
                   8590:                     if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'includedomain'}})) {
                   8591:                         $result = 1;
                   8592:                     } else {
                   8593:                         $result = 0;
                   8594:                     }
                   8595:                 }
                   8596:             }
                   8597:         }
                   8598:     }
                   8599:     return $result;
                   8600: }
                   8601: 
1.471     raeburn  8602: sub distro_and_arch {
                   8603:     return $dist.':'.$arch;
                   8604: }
                   8605: 
1.61      harris41 8606: # ----------------------------------- POD (plain old documentation, CPAN style)
                   8607: 
                   8608: =head1 NAME
                   8609: 
                   8610: lond - "LON Daemon" Server (port "LOND" 5663)
                   8611: 
                   8612: =head1 SYNOPSIS
                   8613: 
1.74      harris41 8614: Usage: B<lond>
                   8615: 
                   8616: Should only be run as user=www.  This is a command-line script which
                   8617: is invoked by B<loncron>.  There is no expectation that a typical user
                   8618: will manually start B<lond> from the command-line.  (In other words,
                   8619: DO NOT START B<lond> YOURSELF.)
1.61      harris41 8620: 
                   8621: =head1 DESCRIPTION
                   8622: 
1.74      harris41 8623: There are two characteristics associated with the running of B<lond>,
                   8624: PROCESS MANAGEMENT (starting, stopping, handling child processes)
                   8625: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
                   8626: subscriptions, etc).  These are described in two large
                   8627: sections below.
                   8628: 
                   8629: B<PROCESS MANAGEMENT>
                   8630: 
1.61      harris41 8631: Preforker - server who forks first. Runs as a daemon. HUPs.
                   8632: Uses IDEA encryption
                   8633: 
1.74      harris41 8634: B<lond> forks off children processes that correspond to the other servers
                   8635: in the network.  Management of these processes can be done at the
                   8636: parent process level or the child process level.
                   8637: 
                   8638: B<logs/lond.log> is the location of log messages.
                   8639: 
                   8640: The process management is now explained in terms of linux shell commands,
                   8641: subroutines internal to this code, and signal assignments:
                   8642: 
                   8643: =over 4
                   8644: 
                   8645: =item *
                   8646: 
                   8647: PID is stored in B<logs/lond.pid>
                   8648: 
                   8649: This is the process id number of the parent B<lond> process.
                   8650: 
                   8651: =item *
                   8652: 
                   8653: SIGTERM and SIGINT
                   8654: 
                   8655: Parent signal assignment:
                   8656:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   8657: 
                   8658: Child signal assignment:
                   8659:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
                   8660: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
                   8661:  to restart a new child.)
                   8662: 
                   8663: Command-line invocations:
                   8664:  B<kill> B<-s> SIGTERM I<PID>
                   8665:  B<kill> B<-s> SIGINT I<PID>
                   8666: 
                   8667: Subroutine B<HUNTSMAN>:
                   8668:  This is only invoked for the B<lond> parent I<PID>.
                   8669: This kills all the children, and then the parent.
                   8670: The B<lonc.pid> file is cleared.
                   8671: 
                   8672: =item *
                   8673: 
                   8674: SIGHUP
                   8675: 
                   8676: Current bug:
                   8677:  This signal can only be processed the first time
                   8678: on the parent process.  Subsequent SIGHUP signals
                   8679: have no effect.
                   8680: 
                   8681: Parent signal assignment:
                   8682:  $SIG{HUP}  = \&HUPSMAN;
                   8683: 
                   8684: Child signal assignment:
                   8685:  none (nothing happens)
                   8686: 
                   8687: Command-line invocations:
                   8688:  B<kill> B<-s> SIGHUP I<PID>
                   8689: 
                   8690: Subroutine B<HUPSMAN>:
                   8691:  This is only invoked for the B<lond> parent I<PID>,
                   8692: This kills all the children, and then the parent.
                   8693: The B<lond.pid> file is cleared.
                   8694: 
                   8695: =item *
                   8696: 
                   8697: SIGUSR1
                   8698: 
                   8699: Parent signal assignment:
                   8700:  $SIG{USR1} = \&USRMAN;
                   8701: 
                   8702: Child signal assignment:
                   8703:  $SIG{USR1}= \&logstatus;
                   8704: 
                   8705: Command-line invocations:
                   8706:  B<kill> B<-s> SIGUSR1 I<PID>
                   8707: 
                   8708: Subroutine B<USRMAN>:
                   8709:  When invoked for the B<lond> parent I<PID>,
                   8710: SIGUSR1 is sent to all the children, and the status of
                   8711: each connection is logged.
1.144     foxr     8712: 
                   8713: =item *
                   8714: 
                   8715: SIGUSR2
                   8716: 
                   8717: Parent Signal assignment:
                   8718:     $SIG{USR2} = \&UpdateHosts
                   8719: 
                   8720: Child signal assignment:
                   8721:     NONE
                   8722: 
1.74      harris41 8723: 
                   8724: =item *
                   8725: 
                   8726: SIGCHLD
                   8727: 
                   8728: Parent signal assignment:
                   8729:  $SIG{CHLD} = \&REAPER;
                   8730: 
                   8731: Child signal assignment:
                   8732:  none
                   8733: 
                   8734: Command-line invocations:
                   8735:  B<kill> B<-s> SIGCHLD I<PID>
                   8736: 
                   8737: Subroutine B<REAPER>:
                   8738:  This is only invoked for the B<lond> parent I<PID>.
                   8739: Information pertaining to the child is removed.
                   8740: The socket port is cleaned up.
                   8741: 
                   8742: =back
                   8743: 
                   8744: B<SERVER-SIDE ACTIVITIES>
                   8745: 
                   8746: Server-side information can be accepted in an encrypted or non-encrypted
                   8747: method.
                   8748: 
                   8749: =over 4
                   8750: 
                   8751: =item ping
                   8752: 
                   8753: Query a client in the hosts.tab table; "Are you there?"
                   8754: 
                   8755: =item pong
                   8756: 
                   8757: Respond to a ping query.
                   8758: 
                   8759: =item ekey
                   8760: 
                   8761: Read in encrypted key, make cipher.  Respond with a buildkey.
                   8762: 
                   8763: =item load
                   8764: 
                   8765: Respond with CPU load based on a computation upon /proc/loadavg.
                   8766: 
                   8767: =item currentauth
                   8768: 
                   8769: Reply with current authentication information (only over an
                   8770: encrypted channel).
                   8771: 
                   8772: =item auth
                   8773: 
                   8774: Only over an encrypted channel, reply as to whether a user's
                   8775: authentication information can be validated.
                   8776: 
                   8777: =item passwd
                   8778: 
                   8779: Allow for a password to be set.
                   8780: 
                   8781: =item makeuser
                   8782: 
                   8783: Make a user.
                   8784: 
1.517     raeburn  8785: =item changeuserauth
1.74      harris41 8786: 
                   8787: Allow for authentication mechanism and password to be changed.
                   8788: 
                   8789: =item home
1.61      harris41 8790: 
1.74      harris41 8791: Respond to a question "are you the home for a given user?"
                   8792: 
                   8793: =item update
                   8794: 
                   8795: Update contents of a subscribed resource.
                   8796: 
                   8797: =item unsubscribe
                   8798: 
                   8799: The server is unsubscribing from a resource.
                   8800: 
                   8801: =item subscribe
                   8802: 
                   8803: The server is subscribing to a resource.
                   8804: 
                   8805: =item log
                   8806: 
                   8807: Place in B<logs/lond.log>
                   8808: 
                   8809: =item put
                   8810: 
                   8811: stores hash in namespace
                   8812: 
1.496     raeburn  8813: =item rolesput
1.74      harris41 8814: 
                   8815: put a role into a user's environment
                   8816: 
                   8817: =item get
                   8818: 
                   8819: returns hash with keys from array
                   8820: reference filled in from namespace
                   8821: 
                   8822: =item eget
                   8823: 
                   8824: returns hash with keys from array
                   8825: reference filled in from namesp (encrypts the return communication)
                   8826: 
                   8827: =item rolesget
                   8828: 
                   8829: get a role from a user's environment
                   8830: 
                   8831: =item del
                   8832: 
                   8833: deletes keys out of array from namespace
                   8834: 
                   8835: =item keys
                   8836: 
                   8837: returns namespace keys
                   8838: 
                   8839: =item dump
                   8840: 
                   8841: dumps the complete (or key matching regexp) namespace into a hash
                   8842: 
                   8843: =item store
                   8844: 
                   8845: stores hash permanently
                   8846: for this url; hashref needs to be given and should be a \%hashname; the
                   8847: remaining args aren't required and if they aren't passed or are '' they will
                   8848: be derived from the ENV
                   8849: 
                   8850: =item restore
                   8851: 
                   8852: returns a hash for a given url
                   8853: 
                   8854: =item querysend
                   8855: 
                   8856: Tells client about the lonsql process that has been launched in response
                   8857: to a sent query.
                   8858: 
                   8859: =item queryreply
                   8860: 
                   8861: Accept information from lonsql and make appropriate storage in temporary
                   8862: file space.
                   8863: 
                   8864: =item idput
                   8865: 
                   8866: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
                   8867: for each student, defined perhaps by the institutional Registrar.)
                   8868: 
                   8869: =item idget
                   8870: 
                   8871: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
                   8872: for each student, defined perhaps by the institutional Registrar.)
                   8873: 
1.517     raeburn  8874: =item iddel
                   8875: 
                   8876: Deletes one or more ids in a domain's id database.
                   8877: 
1.74      harris41 8878: =item tmpput
                   8879: 
                   8880: Accept and store information in temporary space.
                   8881: 
                   8882: =item tmpget
                   8883: 
                   8884: Send along temporarily stored information.
                   8885: 
                   8886: =item ls
                   8887: 
                   8888: List part of a user's directory.
                   8889: 
1.135     foxr     8890: =item pushtable
                   8891: 
                   8892: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
                   8893: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
                   8894: must be restored manually in case of a problem with the new table file.
                   8895: pushtable requires that the request be encrypted and validated via
                   8896: ValidateManager.  The form of the command is:
                   8897: enc:pushtable tablename <tablecontents> \n
                   8898: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
                   8899: cleartext newline.
                   8900: 
1.74      harris41 8901: =item Hanging up (exit or init)
                   8902: 
                   8903: What to do when a client tells the server that they (the client)
                   8904: are leaving the network.
                   8905: 
                   8906: =item unknown command
                   8907: 
                   8908: If B<lond> is sent an unknown command (not in the list above),
                   8909: it replys to the client "unknown_cmd".
1.135     foxr     8910: 
1.74      harris41 8911: 
                   8912: =item UNKNOWN CLIENT
                   8913: 
                   8914: If the anti-spoofing algorithm cannot verify the client,
                   8915: the client is rejected (with a "refused" message sent
                   8916: to the client, and the connection is closed.
                   8917: 
                   8918: =back
1.61      harris41 8919: 
                   8920: =head1 PREREQUISITES
                   8921: 
                   8922: IO::Socket
                   8923: IO::File
                   8924: Apache::File
                   8925: POSIX
                   8926: Crypt::IDEA
                   8927: GDBM_File
                   8928: Authen::Krb4
1.91      albertel 8929: Authen::Krb5
1.61      harris41 8930: 
                   8931: =head1 COREQUISITES
                   8932: 
1.490     droeschl 8933: none
                   8934: 
1.61      harris41 8935: =head1 OSNAMES
                   8936: 
                   8937: linux
                   8938: 
                   8939: =head1 SCRIPT CATEGORIES
                   8940: 
                   8941: Server/Process
                   8942: 
                   8943: =cut
1.409     foxr     8944: 
                   8945: 
                   8946: =pod
                   8947: 
                   8948: =head1 LOG MESSAGES
                   8949: 
                   8950: The messages below can be emitted in the lond log.  This log is located
                   8951: in ~httpd/perl/logs/lond.log  Many log messages have HTML encapsulation
                   8952: to provide coloring if examined from inside a web page. Some do not.
                   8953: Where color is used, the colors are; Red for sometihhng to get excited
                   8954: about and to follow up on. Yellow for something to keep an eye on to
                   8955: be sure it does not get worse, Green,and Blue for informational items.
                   8956: 
                   8957: In the discussions below, sometimes reference is made to ~httpd
                   8958: when describing file locations.  There isn't really an httpd 
                   8959: user, however there is an httpd directory that gets installed in the
                   8960: place that user home directories go.  On linux, this is usually
                   8961: (always?) /home/httpd.
                   8962: 
                   8963: 
                   8964: Some messages are colorless.  These are usually (not always)
                   8965: Green/Blue color level messages.
                   8966: 
                   8967: =over 2
                   8968: 
                   8969: =item (Red)  LocalConnection rejecting non local: <ip> ne 127.0.0.1
                   8970: 
                   8971: A local connection negotiation was attempted by
                   8972: a host whose IP address was not 127.0.0.1.
                   8973: The socket is closed and the child will exit.
                   8974: lond has three ways to establish an encyrption
                   8975: key with a client:
                   8976: 
                   8977: =over 2
                   8978: 
                   8979: =item local 
                   8980: 
                   8981: The key is written and read from a file.
                   8982: This is only valid for connections from localhost.
                   8983: 
                   8984: =item insecure 
                   8985: 
                   8986: The key is generated by the server and
                   8987: transmitted to the client.
                   8988: 
                   8989: =item  ssl (secure)
                   8990: 
                   8991: An ssl connection is negotiated with the client,
                   8992: the key is generated by the server and sent to the 
                   8993: client across this ssl connection before the
                   8994: ssl connectionis terminated and clear text
                   8995: transmission resumes.
                   8996: 
                   8997: =back
                   8998: 
                   8999: =item (Red) LocalConnection: caller is insane! init = <init> and type = <type>
                   9000: 
                   9001: The client is local but has not sent an initialization
                   9002: string that is the literal "init:local"  The connection
                   9003: is closed and the child exits.
                   9004: 
                   9005: =item Red CRITICAL Can't get key file <error>        
                   9006: 
                   9007: SSL key negotiation is being attempted but the call to
1.549     raeburn  9008: lonssl::KeyFile failed.  This usually means that the
1.409     foxr     9009: configuration file is not correctly defining or protecting
                   9010: the directories/files lonCertificateDirectory or
                   9011: lonnetPrivateKey
                   9012: <error> is a string that describes the reason that
                   9013: the key file could not be located.
                   9014: 
                   9015: =item (Red) CRITICAL  Can't get certificates <error>  
                   9016: 
                   9017: SSL key negotiation failed because we were not able to retrives our certificate
                   9018: or the CA's certificate in the call to lonssl::CertificateFile
                   9019: <error> is the textual reason this failed.  Usual reasons:
                   9020: 
                   9021: =over 2
1.490     droeschl 9022: 
1.409     foxr     9023: =item Apache config file for loncapa  incorrect:
1.490     droeschl 9024: 
1.409     foxr     9025: one of the variables 
                   9026: lonCertificateDirectory, lonnetCertificateAuthority, or lonnetCertificate
                   9027: undefined or incorrect
                   9028: 
                   9029: =item Permission error:
                   9030: 
                   9031: The directory pointed to by lonCertificateDirectory is not readable by lond
                   9032: 
                   9033: =item Permission error:
                   9034: 
                   9035: Files in the directory pointed to by lonCertificateDirectory are not readable by lond.
                   9036: 
                   9037: =item Installation error:                         
                   9038: 
                   9039: Either the certificate authority file or the certificate have not
                   9040: been installed in lonCertificateDirectory.
                   9041: 
                   9042: =item (Red) CRITICAL SSL Socket promotion failed:  <err> 
                   9043: 
                   9044: The promotion of the connection from plaintext to SSL failed
                   9045: <err> is the reason for the failure.  There are two
                   9046: system calls involved in the promotion (one of which failed), 
                   9047: a dup to produce
                   9048: a second fd on the raw socket over which the encrypted data
                   9049: will flow and IO::SOcket::SSL->new_from_fd which creates
                   9050: the SSL connection on the duped fd.
                   9051: 
                   9052: =item (Blue)   WARNING client did not respond to challenge 
                   9053: 
                   9054: This occurs on an insecure (non SSL) connection negotiation request.
                   9055: lond generates some number from the time, the PID and sends it to
                   9056: the client.  The client must respond by echoing this information back.
                   9057: If the client does not do so, that's a violation of the challenge
                   9058: protocols and the connection will be failed.
                   9059: 
                   9060: =item (Red) No manager table. Nobody can manage!!    
                   9061: 
                   9062: lond has the concept of privileged hosts that
                   9063: can perform remote management function such
                   9064: as update the hosts.tab.   The manager hosts
                   9065: are described in the 
                   9066: ~httpd/lonTabs/managers.tab file.
                   9067: this message is logged if this file is missing.
                   9068: 
                   9069: 
                   9070: =item (Green) Registering manager <dnsname> as <cluster_name> with <ipaddress>
                   9071: 
                   9072: Reports the successful parse and registration
                   9073: of a specific manager. 
                   9074: 
                   9075: =item Green existing host <clustername:dnsname>  
                   9076: 
                   9077: The manager host is already defined in the hosts.tab
                   9078: the information in that table, rather than the info in the
                   9079: manager table will be used to determine the manager's ip.
                   9080: 
                   9081: =item (Red) Unable to craete <filename>                 
                   9082: 
                   9083: lond has been asked to create new versions of an administrative
                   9084: file (by a manager).  When this is done, the new file is created
                   9085: in a temp file and then renamed into place so that there are always
                   9086: usable administrative files, even if the update fails.  This failure
                   9087: message means that the temp file could not be created.
                   9088: The update is abandoned, and the old file is available for use.
                   9089: 
                   9090: =item (Green) CopyFile from <oldname> to <newname> failed
                   9091: 
                   9092: In an update of administrative files, the copy of the existing file to a
                   9093: backup file failed.  The installation of the new file may still succeed,
                   9094: but there will not be a back up file to rever to (this should probably
                   9095: be yellow).
                   9096: 
                   9097: =item (Green) Pushfile: backed up <oldname> to <newname>
                   9098: 
                   9099: See above, the backup of the old administrative file succeeded.
                   9100: 
                   9101: =item (Red)  Pushfile: Unable to install <filename> <reason>
                   9102: 
                   9103: The new administrative file could not be installed.  In this case,
                   9104: the old administrative file is still in use.
                   9105: 
                   9106: =item (Green) Installed new < filename>.                      
                   9107: 
                   9108: The new administrative file was successfullly installed.                                               
                   9109: 
                   9110: =item (Red) Reinitializing lond pid=<pid>                    
                   9111: 
                   9112: The lonc child process <pid> will be sent a USR2 
                   9113: signal.
                   9114: 
                   9115: =item (Red) Reinitializing self                                    
                   9116: 
                   9117: We've been asked to re-read our administrative files,and
                   9118: are doing so.
                   9119: 
                   9120: =item (Yellow) error:Invalid process identifier <ident>  
                   9121: 
                   9122: A reinit command was received, but the target part of the 
                   9123: command was not valid.  It must be either
                   9124: 'lond' or 'lonc' but was <ident>
                   9125: 
                   9126: =item (Green) isValideditCommand checking: Command = <command> Key = <key> newline = <newline>
                   9127: 
                   9128: Checking to see if lond has been handed a valid edit
                   9129: command.  It is possible the edit command is not valid
                   9130: in that case there are no log messages to indicate that.
                   9131: 
                   9132: =item Result of password change for  <username> pwchange_success
                   9133: 
                   9134: The password for <username> was
                   9135: successfully changed.
                   9136: 
                   9137: =item Unable to open <user> passwd to change password
                   9138: 
                   9139: Could not rewrite the 
                   9140: internal password file for a user
                   9141: 
                   9142: =item Result of password change for <user> : <result>
1.490     droeschl 9143: 
1.409     foxr     9144: A unix password change for <user> was attempted 
                   9145: and the pipe returned <result>  
                   9146: 
                   9147: =item LWP GET: <message> for <fname> (<remoteurl>)
                   9148: 
                   9149: The lightweight process fetch for a resource failed
                   9150: with <message> the local filename that should
                   9151: have existed/been created was  <fname> the
                   9152: corresponding URI: <remoteurl>  This is emitted in several
                   9153: places.
                   9154: 
                   9155: =item Unable to move <transname> to <destname>     
                   9156: 
                   9157: From fetch_user_file_handler - the user file was replicated but could not
                   9158: be mv'd to its final location.
                   9159: 
                   9160: =item Looking for <domain> <username>              
                   9161: 
                   9162: From user_has_session_handler - This should be a Debug call instead
                   9163: it indicates lond is about to check whether the specified user has a 
                   9164: session active on the specified domain on the local host.
                   9165: 
                   9166: =item Client <ip> (<name>) hanging up: <input>     
                   9167: 
                   9168: lond has been asked to exit by its client.  The <ip> and <name> identify the
                   9169: client systemand <input> is the full exit command sent to the server.
                   9170: 
                   9171: =item Red CRITICAL: ABNORMAL EXIT. child <pid> for server <hostname> died through a crass with this error->[<message>].
1.490     droeschl 9172: 
1.409     foxr     9173: A lond child terminated.  NOte that this termination can also occur when the
                   9174: child receives the QUIT or DIE signals.  <pid> is the process id of the child,
                   9175: <hostname> the host lond is working for, and <message> the reason the child died
                   9176: to the best of our ability to get it (I would guess that any numeric value
                   9177: represents and errno value).  This is immediately followed by
                   9178: 
                   9179: =item  Famous last words: Catching exception - <log> 
                   9180: 
                   9181: Where log is some recent information about the state of the child.
                   9182: 
                   9183: =item Red CRITICAL: TIME OUT <pid>                     
                   9184: 
                   9185: Some timeout occured for server <pid>.  THis is normally a timeout on an LWP
                   9186: doing an HTTP::GET.
                   9187: 
                   9188: =item child <pid> died                              
                   9189: 
                   9190: The reaper caught a SIGCHILD for the lond child process <pid>
                   9191: This should be modified to also display the IP of the dying child
                   9192: $children{$pid}
                   9193: 
                   9194: =item Unknown child 0 died                           
                   9195: A child died but the wait for it returned a pid of zero which really should not
                   9196: ever happen. 
                   9197: 
                   9198: =item Child <which> - <pid> looks like we missed it's death 
                   9199: 
                   9200: When a sigchild is received, the reaper process checks all children to see if they are
                   9201: alive.  If children are dying quite quickly, the lack of signal queuing can mean
                   9202: that a signal hearalds the death of more than one child.  If so this message indicates
                   9203: which other one died. <which> is the ip of a dead child
                   9204: 
                   9205: =item Free socket: <shutdownretval>                
                   9206: 
                   9207: The HUNTSMAN sub was called due to a SIGINT in a child process.  The socket is being shutdown.
                   9208: for whatever reason, <shutdownretval> is printed but in fact shutdown() is not documented
                   9209: to return anything. This is followed by: 
                   9210: 
                   9211: =item Red CRITICAL: Shutting down                       
                   9212: 
                   9213: Just prior to exit.
                   9214: 
                   9215: =item Free socket: <shutdownretval>                 
                   9216: 
                   9217: The HUPSMAN sub was called due to a SIGHUP.  all children get killsed, and lond execs itself.
                   9218: This is followed by:
                   9219: 
                   9220: =item (Red) CRITICAL: Restarting                         
                   9221: 
                   9222: lond is about to exec itself to restart.
                   9223: 
                   9224: =item (Blue) Updating connections                        
                   9225: 
                   9226: (In response to a USR2).  All the children (except the one for localhost)
                   9227: are about to be killed, the hosts tab reread, and Apache reloaded via apachereload.
                   9228: 
                   9229: =item (Blue) UpdateHosts killing child <pid> for ip <ip>   
                   9230: 
                   9231: Due to USR2 as above.
                   9232: 
                   9233: =item (Green) keeping child for ip <ip> (pid = <pid>)    
                   9234: 
                   9235: In response to USR2 as above, the child indicated is not being restarted because
                   9236: it's assumed that we'll always need a child for the localhost.
                   9237: 
                   9238: 
                   9239: =item Going to check on the children                
                   9240: 
                   9241: Parent is about to check on the health of the child processes.
                   9242: Note that this is in response to a USR1 sent to the parent lond.
                   9243: there may be one or more of the next two messages:
                   9244: 
                   9245: =item <pid> is dead                                 
                   9246: 
                   9247: A child that we have in our child hash as alive has evidently died.
                   9248: 
                   9249: =item  Child <pid> did not respond                   
                   9250: 
                   9251: In the health check the child <pid> did not update/produce a pid_.txt
                   9252: file when sent it's USR1 signal.  That process is killed with a 9 signal, as it's
                   9253: assumed to be hung in some un-fixable way.
                   9254: 
                   9255: =item Finished checking children                   
1.490     droeschl 9256: 
1.409     foxr     9257: Master processs's USR1 processing is cojmplete.
                   9258: 
                   9259: =item (Red) CRITICAL: ------- Starting ------            
                   9260: 
                   9261: (There are more '-'s on either side).  Lond has forked itself off to 
                   9262: form a new session and is about to start actual initialization.
                   9263: 
                   9264: =item (Green) Attempting to start child (<client>)       
                   9265: 
                   9266: Started a new child process for <client>.  Client is IO::Socket object
                   9267: connected to the child.  This was as a result of a TCP/IP connection from a client.
                   9268: 
                   9269: =item Unable to determine who caller was, getpeername returned nothing
1.490     droeschl 9270: 
1.409     foxr     9271: In child process initialization.  either getpeername returned undef or
                   9272: a zero sized object was returned.  Processing continues, but in my opinion,
                   9273: this should be cause for the child to exit.
                   9274: 
                   9275: =item Unable to determine clientip                  
                   9276: 
                   9277: In child process initialization.  The peer address from getpeername was not defined.
                   9278: The client address is stored as "Unavailable" and processing continues.
                   9279: 
                   9280: =item (Yellow) INFO: Connection <ip> <name> connection type = <type>
1.490     droeschl 9281: 
1.409     foxr     9282: In child initialization.  A good connectionw as received from <ip>.
                   9283: 
                   9284: =over 2
                   9285: 
                   9286: =item <name> 
                   9287: 
                   9288: is the name of the client from hosts.tab.
                   9289: 
                   9290: =item <type> 
                   9291: 
                   9292: Is the connection type which is either 
                   9293: 
                   9294: =over 2
                   9295: 
                   9296: =item manager 
                   9297: 
                   9298: The connection is from a manager node, not in hosts.tab
                   9299: 
                   9300: =item client  
                   9301: 
                   9302: the connection is from a non-manager in the hosts.tab
                   9303: 
                   9304: =item both
                   9305: 
                   9306: The connection is from a manager in the hosts.tab.
                   9307: 
                   9308: =back
                   9309: 
                   9310: =back
                   9311: 
                   9312: =item (Blue) Certificates not installed -- trying insecure auth
                   9313: 
                   9314: One of the certificate file, key file or
                   9315: certificate authority file could not be found for a client attempting
                   9316: SSL connection intiation.  COnnection will be attemptied in in-secure mode.
                   9317: (this would be a system with an up to date lond that has not gotten a 
                   9318: certificate from us).
                   9319: 
                   9320: =item (Green)  Successful local authentication            
                   9321: 
                   9322: A local connection successfully negotiated the encryption key. 
                   9323: In this case the IDEA key is in a file (that is hopefully well protected).
                   9324: 
                   9325: =item (Green) Successful ssl authentication with <client>  
                   9326: 
                   9327: The client (<client> is the peer's name in hosts.tab), has successfully
                   9328: negotiated an SSL connection with this child process.
                   9329: 
                   9330: =item (Green) Successful insecure authentication with <client>
1.490     droeschl 9331: 
1.409     foxr     9332: 
                   9333: The client has successfully negotiated an  insecure connection withthe child process.
                   9334: 
                   9335: =item (Yellow) Attempted insecure connection disallowed    
                   9336: 
                   9337: The client attempted and failed to successfully negotiate a successful insecure
                   9338: connection.  This can happen either because the variable londAllowInsecure is false
                   9339: or undefined, or becuse the child did not successfully echo back the challenge
                   9340: string.
                   9341: 
                   9342: 
                   9343: =back
                   9344: 
1.441     raeburn  9345: =back
                   9346: 
1.409     foxr     9347: 
                   9348: =cut

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