Annotation of loncom/lond, revision 1.559

1.1       albertel    1: #!/usr/bin/perl
                      2: # The LearningOnline Network
                      3: # lond "LON Daemon" Server (port "LOND" 5663)
1.60      www         4: #
1.559   ! raeburn     5: # $Id: lond,v 1.558 2019/04/26 20:22:10 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.559   ! raeburn    68: my $VERSION='$Revision: 1.558 $'; #' 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'})) {
1.559   ! raeburn  2033:                         if ($dist =~ /^(centos|rhes|fedora|scientific|oracle)/) {
1.480     raeburn  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: 	my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
1.558     raeburn  2352:         my $notunique;
1.222     foxr     2353: 	if ($howpwd eq 'internal') {
                   2354: 	    &Debug("internal auth");
1.518     raeburn  2355:             my $ncpass = &hash_passwd($udom,$npass);
1.558     raeburn  2356:             my (undef,$method,@rest) = split(/!/,$contentpwd);
                   2357:             if ($method eq 'bcrypt') {
                   2358:                 my %passwdconf = &Apache::lonnet::get_passwdconf($udom);
                   2359:                 if (($passwdconf{'numsaved'}) && ($passwdconf{'numsaved'} =~ /^\d+$/)) {
                   2360:                     my @oldpasswds;
                   2361:                     my $userpath = &propath($udom,$uname);
                   2362:                     my $fullpath = $userpath.'/oldpasswds';
                   2363:                     if (-d $userpath) {
                   2364:                         my @oldfiles;
                   2365:                         if (-e $fullpath) {
                   2366:                             if (opendir(my $dir,$fullpath)) {
                   2367:                                 (@oldfiles) = grep(/^\d+$/,readdir($dir));
                   2368:                                 closedir($dir);
                   2369:                             }
                   2370:                             if (@oldfiles) {
                   2371:                                 @oldfiles = sort { $b <=> $a } (@oldfiles);
                   2372:                                 my $numremoved = 0;
                   2373:                                 for (my $i=0; $i<@oldfiles; $i++) {
                   2374:                                     if ($i>=$passwdconf{'numsaved'}) {
                   2375:                                         if (-f "$fullpath/$oldfiles[$i]") {
                   2376:                                             if (unlink("$fullpath/$oldfiles[$i]")) {
                   2377:                                                 $numremoved ++;
                   2378:                                             }
                   2379:                                         }
                   2380:                                     } elsif (open(my $fh,'<',"$fullpath/$oldfiles[$i]")) {
                   2381:                                         while (my $line = <$fh>) {
                   2382:                                             push(@oldpasswds,$line);
                   2383:                                         }
                   2384:                                         close($fh);
                   2385:                                     }
                   2386:                                 }
                   2387:                                 if ($numremoved) {
                   2388:                                     &logthis("unlinked $numremoved old password files for $uname:$udom");
                   2389:                                 }
                   2390:                             }
                   2391:                         }
                   2392:                         push(@oldpasswds,$contentpwd);
                   2393:                         foreach my $item (@oldpasswds) {
                   2394:                             my (undef,$method,@rest) = split(/!/,$item);
                   2395:                             if ($method eq 'bcrypt') {
                   2396:                                 my $result = &hash_passwd($udom,$npass,@rest);
                   2397:                                 if ($result eq $item) {
                   2398:                                     $notunique = 1;
                   2399:                                     last;
                   2400:                                 }
                   2401:                             }
                   2402:                         }
                   2403:                         unless ($notunique) {
                   2404:                             unless (-e $fullpath) {
                   2405:                                 if (&mkpath("$fullpath/")) {
                   2406:                                     chmod(0700,$fullpath);
                   2407:                                 }
                   2408:                             }
                   2409:                             if (-d $fullpath) {
                   2410:                                 my $now = time;
                   2411:                                 if (open(my $fh,'>',"$fullpath/$now")) {
                   2412:                                     print $fh $contentpwd;
                   2413:                                     close($fh);
                   2414:                                     chmod(0400,"$fullpath/$now");
                   2415:                                 }
                   2416:                             }
                   2417:                         }
                   2418:                     }
                   2419:                 }
                   2420:             }
                   2421:             if ($notunique) {
                   2422:                 my $msg="Result of password change for $uname:$udom - password matches one used before";
                   2423:                 if ($lonhost) {
                   2424:                     $msg .= " - request originated from: $lonhost";
                   2425:                 }
                   2426:                 &logthis($msg);
                   2427:                 &Reply($client, "prioruse\n", $userinput);
                   2428: 	    } elsif (&rewrite_password_file($udom, $uname, "internal:$ncpass")) {
1.428     raeburn  2429: 		my $msg="Result of password change for $uname: pwchange_success";
                   2430:                 if ($lonhost) {
                   2431:                     $msg .= " - request originated from: $lonhost";
                   2432:                 }
                   2433:                 &logthis($msg);
1.518     raeburn  2434:                 &update_passwd_history($uname,$udom,$howpwd,$context);
1.222     foxr     2435: 		&Reply($client, "ok\n", $userinput);
                   2436: 	    } else {
                   2437: 		&logthis("Unable to open $uname passwd "               
                   2438: 			 ."to change password");
                   2439: 		&Failure( $client, "non_authorized\n",$userinput);
                   2440: 	    }
1.346     raeburn  2441: 	} elsif ($howpwd eq 'unix' && $context ne 'reset_by_email') {
1.287     foxr     2442: 	    my $result = &change_unix_password($uname, $npass);
1.518     raeburn  2443:             if ($result eq 'ok') {
                   2444:                 &update_passwd_history($uname,$udom,$howpwd,$context);
                   2445:              }
1.222     foxr     2446: 	    &logthis("Result of password change for $uname: ".
1.287     foxr     2447: 		     $result);
1.387     albertel 2448: 	    &Reply($client, \$result, $userinput);
1.222     foxr     2449: 	} else {
                   2450: 	    # this just means that the current password mode is not
                   2451: 	    # one we know how to change (e.g the kerberos auth modes or
                   2452: 	    # locally written auth handler).
                   2453: 	    #
                   2454: 	    &Failure( $client, "auth_mode_error\n", $userinput);
                   2455: 	}  
1.224     foxr     2456:     } else {
1.428     raeburn  2457: 	if ($failure eq '') {
                   2458: 	    $failure = 'non_authorized';
                   2459: 	}
                   2460: 	&Failure( $client, "$failure\n", $userinput);
1.222     foxr     2461:     }
                   2462: 
                   2463:     return 1;
                   2464: }
1.263     albertel 2465: &register_handler("passwd", \&change_password_handler, 1, 1, 0);
1.222     foxr     2466: 
1.518     raeburn  2467: sub hash_passwd {
                   2468:     my ($domain,$plainpass,@rest) = @_;
                   2469:     my ($salt,$cost);
                   2470:     if (@rest) {
                   2471:         $cost = $rest[0];
                   2472:         # salt is first 22 characters, base-64 encoded by bcrypt
                   2473:         my $plainsalt = substr($rest[1],0,22);
                   2474:         $salt = Crypt::Eksblowfish::Bcrypt::de_base64($plainsalt);
                   2475:     } else {
1.533     raeburn  2476:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   2477:         my $defaultcost = $domdefaults{'intauth_cost'};
1.518     raeburn  2478:         if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
                   2479:             $cost = 10;
                   2480:         } else {
                   2481:             $cost = $defaultcost;
                   2482:         }
                   2483:         # Generate random 16-octet base64 salt
                   2484:         $salt = "";
                   2485:         $salt .= pack("C", int rand(256)) for 1..16;
                   2486:     }
                   2487:     my $hash = &Crypt::Eksblowfish::Bcrypt::bcrypt_hash({
                   2488:         key_nul => 1,
                   2489:         cost    => $cost,
                   2490:         salt    => $salt,
                   2491:     }, Digest::SHA::sha512(Encode::encode('UTF-8',$plainpass)));
                   2492: 
                   2493:     my $result = join("!", "", "bcrypt", sprintf("%02d",$cost),
                   2494:                 &Crypt::Eksblowfish::Bcrypt::en_base64($salt).
                   2495:                 &Crypt::Eksblowfish::Bcrypt::en_base64($hash));
                   2496:     return $result;
                   2497: }
                   2498: 
1.225     foxr     2499: #
                   2500: #   Create a new user.  User in this case means a lon-capa user.
                   2501: #   The user must either already exist in some authentication realm
                   2502: #   like kerberos or the /etc/passwd.  If not, a user completely local to
                   2503: #   this loncapa system is created.
                   2504: #
                   2505: # Parameters:
                   2506: #    $cmd      - The command that got us here.
                   2507: #    $tail     - Tail of the command (remaining parameters).
                   2508: #    $client   - File descriptor connected to client.
                   2509: # Returns
                   2510: #     0        - Requested to exit, caller should shut down.
                   2511: #     1        - Continue processing.
                   2512: # Implicit inputs:
                   2513: #    The authentication systems describe above have their own forms of implicit
                   2514: #    input into the authentication process that are described above.
                   2515: sub add_user_handler {
                   2516: 
                   2517:     my ($cmd, $tail, $client) = @_;
                   2518: 
                   2519: 
                   2520:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   2521:     my $userinput = $cmd.":".$tail; # Reconstruct the full request line.
                   2522: 
                   2523:     &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
                   2524: 
                   2525: 
                   2526:     if($udom eq $currentdomainid) { # Reject new users for other domains...
                   2527: 	
                   2528: 	my $oldumask=umask(0077);
                   2529: 	chomp($npass);
                   2530: 	$npass=&unescape($npass);
                   2531: 	my $passfilename  = &password_path($udom, $uname);
                   2532: 	&Debug("Password file created will be:".$passfilename);
                   2533: 	if (-e $passfilename) {
                   2534: 	    &Failure( $client, "already_exists\n", $userinput);
                   2535: 	} else {
                   2536: 	    my $fperror='';
1.264     albertel 2537: 	    if (!&mkpath($passfilename)) {
                   2538: 		$fperror="error: ".($!+0)." mkdir failed while attempting "
                   2539: 		    ."makeuser";
1.225     foxr     2540: 	    }
                   2541: 	    unless ($fperror) {
1.518     raeburn  2542: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
                   2543:                                              $passfilename,'makeuser');
1.390     raeburn  2544: 		&Reply($client,\$result, $userinput);     #BUGBUG - could be fail
1.225     foxr     2545: 	    } else {
1.387     albertel 2546: 		&Failure($client, \$fperror, $userinput);
1.225     foxr     2547: 	    }
                   2548: 	}
                   2549: 	umask($oldumask);
                   2550:     }  else {
                   2551: 	&Failure($client, "not_right_domain\n",
                   2552: 		$userinput);	# Even if we are multihomed.
                   2553:     
                   2554:     }
                   2555:     return 1;
                   2556: 
                   2557: }
                   2558: &register_handler("makeuser", \&add_user_handler, 1, 1, 0);
                   2559: 
                   2560: #
                   2561: #   Change the authentication method of a user.  Note that this may
                   2562: #   also implicitly change the user's password if, for example, the user is
                   2563: #   joining an existing authentication realm.  Known authentication realms at
                   2564: #   this time are:
                   2565: #    internal   - Purely internal password file (only loncapa knows this user)
                   2566: #    local      - Institutionally written authentication module.
                   2567: #    unix       - Unix user (/etc/passwd with or without /etc/shadow).
                   2568: #    kerb4      - kerberos version 4
                   2569: #    kerb5      - kerberos version 5
                   2570: #
                   2571: # Parameters:
                   2572: #    $cmd      - The command that got us here.
                   2573: #    $tail     - Tail of the command (remaining parameters).
                   2574: #    $client   - File descriptor connected to client.
                   2575: # Returns
                   2576: #     0        - Requested to exit, caller should shut down.
                   2577: #     1        - Continue processing.
                   2578: # Implicit inputs:
                   2579: #    The authentication systems describe above have their own forms of implicit
                   2580: #    input into the authentication process that are described above.
1.287     foxr     2581: # NOTE:
                   2582: #   This is also used to change the authentication credential values (e.g. passwd).
                   2583: #   
1.225     foxr     2584: #
                   2585: sub change_authentication_handler {
                   2586: 
                   2587:     my ($cmd, $tail, $client) = @_;
                   2588:    
                   2589:     my $userinput  = "$cmd:$tail";              # Reconstruct user input.
                   2590: 
                   2591:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   2592:     &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
                   2593:     if ($udom ne $currentdomainid) {
                   2594: 	&Failure( $client, "not_right_domain\n", $client);
                   2595:     } else {
                   2596: 	
                   2597: 	chomp($npass);
                   2598: 	
                   2599: 	$npass=&unescape($npass);
1.261     foxr     2600: 	my $oldauth = &get_auth_type($udom, $uname); # Get old auth info.
1.225     foxr     2601: 	my $passfilename = &password_path($udom, $uname);
                   2602: 	if ($passfilename) {	# Not allowed to create a new user!!
1.287     foxr     2603: 	    # If just changing the unix passwd. need to arrange to run
1.502     raeburn  2604: 	    # passwd since otherwise make_passwd_file will fail as 
                   2605: 	    # creation of unix authenticated users is no longer supported
                   2606:             # except from the command line, when running make_domain_coordinator.pl
1.287     foxr     2607: 
                   2608: 	    if(($oldauth =~/^unix/) && ($umode eq "unix")) {
                   2609: 		my $result = &change_unix_password($uname, $npass);
                   2610: 		&logthis("Result of password change for $uname: ".$result);
                   2611: 		if ($result eq "ok") {
1.518     raeburn  2612:                     &update_passwd_history($uname,$udom,$umode,'changeuserauth'); 
1.390     raeburn  2613: 		    &Reply($client, \$result);
1.288     albertel 2614: 		} else {
1.387     albertel 2615: 		    &Failure($client, \$result);
1.287     foxr     2616: 		}
1.288     albertel 2617: 	    } else {
1.518     raeburn  2618: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
                   2619:                                              $passfilename,'changeuserauth');
1.287     foxr     2620: 		#
                   2621: 		#  If the current auth mode is internal, and the old auth mode was
                   2622: 		#  unix, or krb*,  and the user is an author for this domain,
                   2623: 		#  re-run manage_permissions for that role in order to be able
                   2624: 		#  to take ownership of the construction space back to www:www
                   2625: 		#
1.502     raeburn  2626: 
                   2627: 
1.387     albertel 2628: 		&Reply($client, \$result, $userinput);
1.261     foxr     2629: 	    }
                   2630: 	       
                   2631: 
1.225     foxr     2632: 	} else {	       
1.251     foxr     2633: 	    &Failure($client, "non_authorized\n", $userinput); # Fail the user now.
1.225     foxr     2634: 	}
                   2635:     }
                   2636:     return 1;
                   2637: }
                   2638: &register_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
                   2639: 
1.518     raeburn  2640: sub update_passwd_history {
                   2641:     my ($uname,$udom,$umode,$context) = @_;
                   2642:     my $proname=&propath($udom,$uname);
                   2643:     my $now = time;
                   2644:     if (open(my $fh,">>$proname/passwd.log")) {
                   2645:         print $fh "$now:$umode:$context\n";
                   2646:         close($fh);
                   2647:     }
                   2648:     return;
                   2649: }
                   2650: 
1.225     foxr     2651: #
                   2652: #   Determines if this is the home server for a user.  The home server
                   2653: #   for a user will have his/her lon-capa passwd file.  Therefore all we need
                   2654: #   to do is determine if this file exists.
                   2655: #
                   2656: # Parameters:
                   2657: #    $cmd      - The command that got us here.
                   2658: #    $tail     - Tail of the command (remaining parameters).
                   2659: #    $client   - File descriptor connected to client.
                   2660: # Returns
                   2661: #     0        - Requested to exit, caller should shut down.
                   2662: #     1        - Continue processing.
                   2663: # Implicit inputs:
                   2664: #    The authentication systems describe above have their own forms of implicit
                   2665: #    input into the authentication process that are described above.
                   2666: #
                   2667: sub is_home_handler {
                   2668:     my ($cmd, $tail, $client) = @_;
                   2669:    
                   2670:     my $userinput  = "$cmd:$tail";
                   2671:    
                   2672:     my ($udom,$uname)=split(/:/,$tail);
                   2673:     chomp($uname);
                   2674:     my $passfile = &password_filename($udom, $uname);
                   2675:     if($passfile) {
                   2676: 	&Reply( $client, "found\n", $userinput);
                   2677:     } else {
                   2678: 	&Failure($client, "not_found\n", $userinput);
                   2679:     }
                   2680:     return 1;
                   2681: }
                   2682: &register_handler("home", \&is_home_handler, 0,1,0);
                   2683: 
                   2684: #
1.434     www      2685: #   Process an update request for a resource.
                   2686: #   A resource has been modified that we hold a subscription to.
1.225     foxr     2687: #   If the resource is not local, then we must update, or at least invalidate our
                   2688: #   cached copy of the resource. 
                   2689: # Parameters:
                   2690: #    $cmd      - The command that got us here.
                   2691: #    $tail     - Tail of the command (remaining parameters).
                   2692: #    $client   - File descriptor connected to client.
                   2693: # Returns
                   2694: #     0        - Requested to exit, caller should shut down.
                   2695: #     1        - Continue processing.
                   2696: # Implicit inputs:
                   2697: #    The authentication systems describe above have their own forms of implicit
                   2698: #    input into the authentication process that are described above.
                   2699: #
                   2700: sub update_resource_handler {
                   2701: 
                   2702:     my ($cmd, $tail, $client) = @_;
                   2703:    
                   2704:     my $userinput = "$cmd:$tail";
                   2705:    
                   2706:     my $fname= $tail;		# This allows interactive testing
                   2707: 
                   2708: 
                   2709:     my $ownership=ishome($fname);
                   2710:     if ($ownership eq 'not_owner') {
                   2711: 	if (-e $fname) {
1.434     www      2712:             # Delete preview file, if exists
                   2713:             unlink("$fname.tmp");
                   2714:             # Get usage stats
1.225     foxr     2715: 	    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
                   2716: 		$atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
                   2717: 	    my $now=time;
                   2718: 	    my $since=$now-$atime;
1.434     www      2719:             # If the file has not been used within lonExpire seconds,
                   2720:             # unsubscribe from it and delete local copy
1.225     foxr     2721: 	    if ($since>$perlvar{'lonExpire'}) {
1.365     albertel 2722: 		my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
1.308     albertel 2723: 		&devalidate_meta_cache($fname);
1.225     foxr     2724: 		unlink("$fname");
1.334     albertel 2725: 		unlink("$fname.meta");
1.225     foxr     2726: 	    } else {
1.434     www      2727:             # Yes, this is in active use. Get a fresh copy. Since it might be in
                   2728:             # very active use and huge (like a movie), copy it to "in.transfer" filename first.
1.225     foxr     2729: 		my $transname="$fname.in.transfer";
1.365     albertel 2730: 		my $remoteurl=&Apache::lonnet::reply("sub:$fname","$clientname");
1.225     foxr     2731: 		my $response;
1.537     raeburn  2732: # FIXME: cannot replicate files that take more than two minutes to transfer -- needs checking now 1200s timeout used
                   2733: # for LWP request.
                   2734: 		my $request=new HTTP::Request('GET',"$remoteurl");
                   2735:                 $response=&LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,0,1);
1.225     foxr     2736: 		if ($response->is_error()) {
1.541     raeburn  2737:                     my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
                   2738:                     &devalidate_meta_cache($fname);
                   2739:                     if (-e $transname) {
                   2740:                         unlink($transname);
                   2741:                     }
                   2742:                     unlink($fname);
1.225     foxr     2743: 		    my $message=$response->status_line;
                   2744: 		    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   2745: 		} else {
                   2746: 		    if ($remoteurl!~/\.meta$/) {
1.537     raeburn  2747: 			my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2748:                         my $mresponse = &LONCAPA::LWPReq::makerequest($clientname,$mrequest,$fname.'.meta',\%perlvar,120,0,1);
                   2749: 			if ($mresponse->is_error()) {
                   2750: 			    unlink($fname.'.meta');
1.225     foxr     2751: 			}
                   2752: 		    }
1.434     www      2753:                     # we successfully transfered, copy file over to real name
1.225     foxr     2754: 		    rename($transname,$fname);
1.308     albertel 2755: 		    &devalidate_meta_cache($fname);
1.225     foxr     2756: 		}
                   2757: 	    }
                   2758: 	    &Reply( $client, "ok\n", $userinput);
                   2759: 	} else {
                   2760: 	    &Failure($client, "not_found\n", $userinput);
                   2761: 	}
                   2762:     } else {
                   2763: 	&Failure($client, "rejected\n", $userinput);
                   2764:     }
                   2765:     return 1;
                   2766: }
                   2767: &register_handler("update", \&update_resource_handler, 0 ,1, 0);
                   2768: 
1.308     albertel 2769: sub devalidate_meta_cache {
                   2770:     my ($url) = @_;
                   2771:     use Cache::Memcached;
                   2772:     my $memcache = new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.365     albertel 2773:     $url = &Apache::lonnet::declutter($url);
1.308     albertel 2774:     $url =~ s-\.meta$--;
                   2775:     my $id = &escape('meta:'.$url);
                   2776:     $memcache->delete($id);
                   2777: }
                   2778: 
1.225     foxr     2779: #
1.226     foxr     2780: #   Fetch a user file from a remote server to the user's home directory
                   2781: #   userfiles subdir.
1.225     foxr     2782: # Parameters:
                   2783: #    $cmd      - The command that got us here.
                   2784: #    $tail     - Tail of the command (remaining parameters).
                   2785: #    $client   - File descriptor connected to client.
                   2786: # Returns
                   2787: #     0        - Requested to exit, caller should shut down.
                   2788: #     1        - Continue processing.
                   2789: #
                   2790: sub fetch_user_file_handler {
                   2791: 
                   2792:     my ($cmd, $tail, $client) = @_;
                   2793: 
                   2794:     my $userinput = "$cmd:$tail";
                   2795:     my $fname           = $tail;
1.232     foxr     2796:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
1.225     foxr     2797:     my $udir=&propath($udom,$uname).'/userfiles';
                   2798:     unless (-e $udir) {
                   2799: 	mkdir($udir,0770); 
                   2800:     }
1.232     foxr     2801:     Debug("fetch user file for $fname");
1.225     foxr     2802:     if (-e $udir) {
                   2803: 	$ufile=~s/^[\.\~]+//;
1.232     foxr     2804: 
                   2805: 	# IF necessary, create the path right down to the file.
                   2806: 	# Note that any regular files in the way of this path are
                   2807: 	# wiped out to deal with some earlier folly of mine.
                   2808: 
1.267     raeburn  2809: 	if (!&mkpath($udir.'/'.$ufile)) {
1.264     albertel 2810: 	    &Failure($client, "unable_to_create\n", $userinput);	    
1.232     foxr     2811: 	}
                   2812: 
1.225     foxr     2813: 	my $destname=$udir.'/'.$ufile;
                   2814: 	my $transname=$udir.'/'.$ufile.'.in.transit';
1.476     raeburn  2815:         my $clientprotocol=$Apache::lonnet::protocol{$clientname};
                   2816:         $clientprotocol = 'http' if ($clientprotocol ne 'https');
1.486     raeburn  2817: 	my $clienthost = &Apache::lonnet::hostname($clientname);
                   2818: 	my $remoteurl=$clientprotocol.'://'.$clienthost.'/userfiles/'.$fname;
1.225     foxr     2819: 	my $response;
1.232     foxr     2820: 	Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
1.537     raeburn  2821: 	my $request=new HTTP::Request('GET',"$remoteurl");
                   2822:         my $verifycert = 1;
                   2823:         my @machine_ids = &Apache::lonnet::current_machine_ids();
                   2824:         if (grep(/^\Q$clientname\E$/,@machine_ids)) {
                   2825:             $verifycert = 0;
                   2826:         }
                   2827:         $response = &LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,$verifycert);
1.225     foxr     2828: 	if ($response->is_error()) {
                   2829: 	    unlink($transname);
                   2830: 	    my $message=$response->status_line;
                   2831: 	    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   2832: 	    &Failure($client, "failed\n", $userinput);
                   2833: 	} else {
1.232     foxr     2834: 	    Debug("Renaming $transname to $destname");
1.225     foxr     2835: 	    if (!rename($transname,$destname)) {
                   2836: 		&logthis("Unable to move $transname to $destname");
                   2837: 		unlink($transname);
                   2838: 		&Failure($client, "failed\n", $userinput);
                   2839: 	    } else {
1.495     raeburn  2840:                 if ($fname =~ /^default.+\.(page|sequence)$/) {
                   2841:                     my ($major,$minor) = split(/\./,$clientversion);
                   2842:                     if (($major < 2) || ($major == 2 && $minor < 11)) {
                   2843:                         my $now = time;
                   2844:                         &Apache::lonnet::do_cache_new('crschange',$udom.'_'.$uname,$now,600);
                   2845:                         my $key = &escape('internal.contentchange');
                   2846:                         my $what = "$key=$now";
                   2847:                         my $hashref = &tie_user_hash($udom,$uname,'environment',
                   2848:                                                      &GDBM_WRCREAT(),"P",$what);
                   2849:                         if ($hashref) {
                   2850:                             $hashref->{$key}=$now;
                   2851:                             if (!&untie_user_hash($hashref)) {
                   2852:                                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
                   2853:                                          "when updating internal.contentchange");
                   2854:                             }
                   2855:                         }
                   2856:                     }
                   2857:                 }
1.225     foxr     2858: 		&Reply($client, "ok\n", $userinput);
                   2859: 	    }
                   2860: 	}   
                   2861:     } else {
                   2862: 	&Failure($client, "not_home\n", $userinput);
                   2863:     }
                   2864:     return 1;
                   2865: }
                   2866: &register_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
                   2867: 
1.226     foxr     2868: #
                   2869: #   Remove a file from a user's home directory userfiles subdirectory.
                   2870: # Parameters:
                   2871: #    cmd   - the Lond request keyword that got us here.
                   2872: #    tail  - the part of the command past the keyword.
                   2873: #    client- File descriptor connected with the client.
                   2874: #
                   2875: # Returns:
                   2876: #    1    - Continue processing.
                   2877: sub remove_user_file_handler {
                   2878:     my ($cmd, $tail, $client) = @_;
                   2879: 
                   2880:     my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2881: 
                   2882:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2883:     if ($ufile =~m|/\.\./|) {
                   2884: 	# any files paths with /../ in them refuse 
                   2885: 	# to deal with
                   2886: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2887:     } else {
                   2888: 	my $udir = &propath($udom,$uname);
                   2889: 	if (-e $udir) {
                   2890: 	    my $file=$udir.'/userfiles/'.$ufile;
                   2891: 	    if (-e $file) {
1.253     foxr     2892: 		#
                   2893: 		#   If the file is a regular file unlink is fine...
1.520     raeburn  2894: 		#   However it's possible the client wants a dir 
                   2895: 		#   removed, in which case rmdir is more appropriate.
                   2896: 		#   Note: rmdir will only remove an empty directory.
1.253     foxr     2897: 		#
1.240     banghart 2898: 	        if (-f $file){
1.241     albertel 2899: 		    unlink($file);
1.520     raeburn  2900:                     # for html files remove the associated .bak file 
                   2901:                     # which may have been created by the editor.
                   2902:                     if ($ufile =~ m{^((docs|supplemental)/(?:\d+|default)/\d+(?:|/.+)/)[^/]+\.x?html?$}i) {
                   2903:                         my $path = $1;
                   2904:                         if (-e $file.'.bak') {
                   2905:                             unlink($file.'.bak');
                   2906:                         }
                   2907:                     }
1.241     albertel 2908: 		} elsif(-d $file) {
                   2909: 		    rmdir($file);
1.240     banghart 2910: 		}
1.226     foxr     2911: 		if (-e $file) {
1.253     foxr     2912: 		    #  File is still there after we deleted it ?!?
                   2913: 
1.226     foxr     2914: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2915: 		} else {
                   2916: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2917: 		}
                   2918: 	    } else {
                   2919: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2920: 	    }
                   2921: 	} else {
                   2922: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2923: 	}
                   2924:     }
                   2925:     return 1;
                   2926: }
                   2927: &register_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
                   2928: 
1.236     albertel 2929: #
                   2930: #   make a directory in a user's home directory userfiles subdirectory.
                   2931: # Parameters:
                   2932: #    cmd   - the Lond request keyword that got us here.
                   2933: #    tail  - the part of the command past the keyword.
                   2934: #    client- File descriptor connected with the client.
                   2935: #
                   2936: # Returns:
                   2937: #    1    - Continue processing.
                   2938: sub mkdir_user_file_handler {
                   2939:     my ($cmd, $tail, $client) = @_;
                   2940: 
                   2941:     my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2942:     $dir=&unescape($dir);
                   2943:     my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2944:     if ($ufile =~m|/\.\./|) {
                   2945: 	# any files paths with /../ in them refuse 
                   2946: 	# to deal with
                   2947: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2948:     } else {
                   2949: 	my $udir = &propath($udom,$uname);
                   2950: 	if (-e $udir) {
1.264     albertel 2951: 	    my $newdir=$udir.'/userfiles/'.$ufile.'/';
                   2952: 	    if (!&mkpath($newdir)) {
                   2953: 		&Failure($client, "failed\n", "$cmd:$tail");
1.236     albertel 2954: 	    }
1.264     albertel 2955: 	    &Reply($client, "ok\n", "$cmd:$tail");
1.236     albertel 2956: 	} else {
                   2957: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2958: 	}
                   2959:     }
                   2960:     return 1;
                   2961: }
                   2962: &register_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
                   2963: 
1.237     albertel 2964: #
                   2965: #   rename a file in a user's home directory userfiles subdirectory.
                   2966: # Parameters:
                   2967: #    cmd   - the Lond request keyword that got us here.
                   2968: #    tail  - the part of the command past the keyword.
                   2969: #    client- File descriptor connected with the client.
                   2970: #
                   2971: # Returns:
                   2972: #    1    - Continue processing.
                   2973: sub rename_user_file_handler {
                   2974:     my ($cmd, $tail, $client) = @_;
                   2975: 
                   2976:     my ($udom,$uname,$old,$new) = split(/:/, $tail);
                   2977:     $old=&unescape($old);
                   2978:     $new=&unescape($new);
                   2979:     if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
                   2980: 	# any files paths with /../ in them refuse to deal with
                   2981: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2982:     } else {
                   2983: 	my $udir = &propath($udom,$uname);
                   2984: 	if (-e $udir) {
                   2985: 	    my $oldfile=$udir.'/userfiles/'.$old;
                   2986: 	    my $newfile=$udir.'/userfiles/'.$new;
                   2987: 	    if (-e $newfile) {
                   2988: 		&Failure($client, "exists\n", "$cmd:$tail");
                   2989: 	    } elsif (! -e $oldfile) {
                   2990: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2991: 	    } else {
                   2992: 		if (!rename($oldfile,$newfile)) {
                   2993: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2994: 		} else {
                   2995: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2996: 		}
                   2997: 	    }
                   2998: 	} else {
                   2999: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   3000: 	}
                   3001:     }
                   3002:     return 1;
                   3003: }
                   3004: &register_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
                   3005: 
1.227     foxr     3006: #
1.382     albertel 3007: #  Checks if the specified user has an active session on the server
                   3008: #  return ok if so, not_found if not
                   3009: #
                   3010: # Parameters:
                   3011: #   cmd      - The request keyword that dispatched to tus.
                   3012: #   tail     - The tail of the request (colon separated parameters).
                   3013: #   client   - Filehandle open on the client.
                   3014: # Return:
                   3015: #    1.
                   3016: sub user_has_session_handler {
                   3017:     my ($cmd, $tail, $client) = @_;
                   3018: 
                   3019:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
                   3020:     
                   3021:     opendir(DIR,$perlvar{'lonIDsDir'});
                   3022:     my $filename;
                   3023:     while ($filename=readdir(DIR)) {
                   3024: 	last if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/);
                   3025:     }
                   3026:     if ($filename) {
                   3027: 	&Reply($client, "ok\n", "$cmd:$tail");
                   3028:     } else {
                   3029: 	&Failure($client, "not_found\n", "$cmd:$tail");
                   3030:     }
                   3031:     return 1;
                   3032: 
                   3033: }
                   3034: &register_handler("userhassession", \&user_has_session_handler, 0,1,0);
                   3035: 
                   3036: #
1.263     albertel 3037: #  Authenticate access to a user file by checking that the token the user's 
                   3038: #  passed also exists in their session file
1.227     foxr     3039: #
                   3040: # Parameters:
                   3041: #   cmd      - The request keyword that dispatched to tus.
                   3042: #   tail     - The tail of the request (colon separated parameters).
                   3043: #   client   - Filehandle open on the client.
                   3044: # Return:
                   3045: #    1.
                   3046: sub token_auth_user_file_handler {
                   3047:     my ($cmd, $tail, $client) = @_;
                   3048: 
                   3049:     my ($fname, $session) = split(/:/, $tail);
                   3050:     
                   3051:     chomp($session);
1.393     raeburn  3052:     my $reply="non_auth";
1.343     albertel 3053:     my $file = $perlvar{'lonIDsDir'}.'/'.$session.'.id';
                   3054:     if (open(ENVIN,"$file")) {
1.332     albertel 3055: 	flock(ENVIN,LOCK_SH);
1.343     albertel 3056: 	tie(my %disk_env,'GDBM_File',"$file",&GDBM_READER(),0640);
                   3057: 	if (exists($disk_env{"userfile.$fname"})) {
1.393     raeburn  3058: 	    $reply="ok";
1.343     albertel 3059: 	} else {
                   3060: 	    foreach my $envname (keys(%disk_env)) {
                   3061: 		if ($envname=~ m|^userfile\.\Q$fname\E|) {
1.393     raeburn  3062: 		    $reply="ok";
1.343     albertel 3063: 		    last;
                   3064: 		}
                   3065: 	    }
1.227     foxr     3066: 	}
1.343     albertel 3067: 	untie(%disk_env);
1.227     foxr     3068: 	close(ENVIN);
1.387     albertel 3069: 	&Reply($client, \$reply, "$cmd:$tail");
1.227     foxr     3070:     } else {
                   3071: 	&Failure($client, "invalid_token\n", "$cmd:$tail");
                   3072:     }
                   3073:     return 1;
                   3074: 
                   3075: }
                   3076: &register_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
1.229     foxr     3077: 
                   3078: #
                   3079: #   Unsubscribe from a resource.
                   3080: #
                   3081: # Parameters:
                   3082: #    $cmd      - The command that got us here.
                   3083: #    $tail     - Tail of the command (remaining parameters).
                   3084: #    $client   - File descriptor connected to client.
                   3085: # Returns
                   3086: #     0        - Requested to exit, caller should shut down.
                   3087: #     1        - Continue processing.
                   3088: #
                   3089: sub unsubscribe_handler {
                   3090:     my ($cmd, $tail, $client) = @_;
                   3091: 
                   3092:     my $userinput= "$cmd:$tail";
                   3093:     
                   3094:     my ($fname) = split(/:/,$tail); # Split in case there's extrs.
                   3095: 
                   3096:     &Debug("Unsubscribing $fname");
                   3097:     if (-e $fname) {
                   3098: 	&Debug("Exists");
                   3099: 	&Reply($client, &unsub($fname,$clientip), $userinput);
                   3100:     } else {
                   3101: 	&Failure($client, "not_found\n", $userinput);
                   3102:     }
                   3103:     return 1;
                   3104: }
                   3105: &register_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
1.263     albertel 3106: 
1.230     foxr     3107: #   Subscribe to a resource
                   3108: #
                   3109: # Parameters:
                   3110: #    $cmd      - The command that got us here.
                   3111: #    $tail     - Tail of the command (remaining parameters).
                   3112: #    $client   - File descriptor connected to client.
                   3113: # Returns
                   3114: #     0        - Requested to exit, caller should shut down.
                   3115: #     1        - Continue processing.
                   3116: #
                   3117: sub subscribe_handler {
                   3118:     my ($cmd, $tail, $client)= @_;
                   3119: 
                   3120:     my $userinput  = "$cmd:$tail";
                   3121: 
                   3122:     &Reply( $client, &subscribe($userinput,$clientip), $userinput);
                   3123: 
                   3124:     return 1;
                   3125: }
                   3126: &register_handler("sub", \&subscribe_handler, 0, 1, 0);
                   3127: 
                   3128: #
1.379     albertel 3129: #   Determine the latest version of a resource (it looks for the highest
                   3130: #   past version and then returns that +1)
1.230     foxr     3131: #
                   3132: # Parameters:
                   3133: #    $cmd      - The command that got us here.
                   3134: #    $tail     - Tail of the command (remaining parameters).
1.379     albertel 3135: #                 (Should consist of an absolute path to a file)
1.230     foxr     3136: #    $client   - File descriptor connected to client.
                   3137: # Returns
                   3138: #     0        - Requested to exit, caller should shut down.
                   3139: #     1        - Continue processing.
                   3140: #
                   3141: sub current_version_handler {
                   3142:     my ($cmd, $tail, $client) = @_;
                   3143: 
                   3144:     my $userinput= "$cmd:$tail";
                   3145:    
                   3146:     my $fname   = $tail;
                   3147:     &Reply( $client, &currentversion($fname)."\n", $userinput);
                   3148:     return 1;
                   3149: 
                   3150: }
                   3151: &register_handler("currentversion", \&current_version_handler, 0, 1, 0);
                   3152: 
                   3153: #  Make an entry in a user's activity log.
                   3154: #
                   3155: # Parameters:
                   3156: #    $cmd      - The command that got us here.
                   3157: #    $tail     - Tail of the command (remaining parameters).
                   3158: #    $client   - File descriptor connected to client.
                   3159: # Returns
                   3160: #     0        - Requested to exit, caller should shut down.
                   3161: #     1        - Continue processing.
                   3162: #
                   3163: sub activity_log_handler {
                   3164:     my ($cmd, $tail, $client) = @_;
                   3165: 
                   3166: 
                   3167:     my $userinput= "$cmd:$tail";
                   3168: 
                   3169:     my ($udom,$uname,$what)=split(/:/,$tail);
                   3170:     chomp($what);
                   3171:     my $proname=&propath($udom,$uname);
                   3172:     my $now=time;
                   3173:     my $hfh;
                   3174:     if ($hfh=IO::File->new(">>$proname/activity.log")) { 
                   3175: 	print $hfh "$now:$clientname:$what\n";
                   3176: 	&Reply( $client, "ok\n", $userinput); 
                   3177:     } else {
                   3178: 	&Failure($client, "error: ".($!+0)." IO::File->new Failed "
                   3179: 		 ."while attempting log\n", 
                   3180: 		 $userinput);
                   3181:     }
                   3182: 
                   3183:     return 1;
                   3184: }
1.263     albertel 3185: &register_handler("log", \&activity_log_handler, 0, 1, 0);
1.230     foxr     3186: 
                   3187: #
                   3188: #   Put a namespace entry in a user profile hash.
                   3189: #   My druthers would be for this to be an encrypted interaction too.
                   3190: #   anything that might be an inadvertent covert channel about either
                   3191: #   user authentication or user personal information....
                   3192: #
                   3193: # Parameters:
                   3194: #    $cmd      - The command that got us here.
                   3195: #    $tail     - Tail of the command (remaining parameters).
                   3196: #    $client   - File descriptor connected to client.
                   3197: # Returns
                   3198: #     0        - Requested to exit, caller should shut down.
                   3199: #     1        - Continue processing.
                   3200: #
                   3201: sub put_user_profile_entry {
                   3202:     my ($cmd, $tail, $client)  = @_;
1.229     foxr     3203: 
1.230     foxr     3204:     my $userinput = "$cmd:$tail";
                   3205:     
1.242     raeburn  3206:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
1.230     foxr     3207:     if ($namespace ne 'roles') {
                   3208: 	chomp($what);
                   3209: 	my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3210: 				  &GDBM_WRCREAT(),"P",$what);
                   3211: 	if($hashref) {
                   3212: 	    my @pairs=split(/\&/,$what);
                   3213: 	    foreach my $pair (@pairs) {
                   3214: 		my ($key,$value)=split(/=/,$pair);
                   3215: 		$hashref->{$key}=$value;
                   3216: 	    }
1.311     albertel 3217: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     3218: 		&Reply( $client, "ok\n", $userinput);
                   3219: 	    } else {
                   3220: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3221: 			"while attempting put\n", 
                   3222: 			$userinput);
                   3223: 	    }
                   3224: 	} else {
1.316     albertel 3225: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.230     foxr     3226: 		     "while attempting put\n", $userinput);
                   3227: 	}
                   3228:     } else {
                   3229:         &Failure( $client, "refused\n", $userinput);
                   3230:     }
                   3231:     
                   3232:     return 1;
                   3233: }
                   3234: &register_handler("put", \&put_user_profile_entry, 0, 1, 0);
                   3235: 
1.283     albertel 3236: #   Put a piece of new data in hash, returns error if entry already exists
                   3237: # Parameters:
                   3238: #    $cmd      - The command that got us here.
                   3239: #    $tail     - Tail of the command (remaining parameters).
                   3240: #    $client   - File descriptor connected to client.
                   3241: # Returns
                   3242: #     0        - Requested to exit, caller should shut down.
                   3243: #     1        - Continue processing.
                   3244: #
                   3245: sub newput_user_profile_entry {
                   3246:     my ($cmd, $tail, $client)  = @_;
                   3247: 
                   3248:     my $userinput = "$cmd:$tail";
                   3249: 
                   3250:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
                   3251:     if ($namespace eq 'roles') {
                   3252:         &Failure( $client, "refused\n", $userinput);
                   3253: 	return 1;
                   3254:     }
                   3255: 
                   3256:     chomp($what);
                   3257: 
                   3258:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3259: 				 &GDBM_WRCREAT(),"N",$what);
                   3260:     if(!$hashref) {
1.316     albertel 3261: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.283     albertel 3262: 		  "while attempting put\n", $userinput);
                   3263: 	return 1;
                   3264:     }
                   3265: 
                   3266:     my @pairs=split(/\&/,$what);
                   3267:     foreach my $pair (@pairs) {
                   3268: 	my ($key,$value)=split(/=/,$pair);
                   3269: 	if (exists($hashref->{$key})) {
1.513     raeburn  3270:             if (!&untie_user_hash($hashref)) {
                   3271:                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
                   3272:                          "while attempting newput - early out as key exists");
                   3273:             }
                   3274:             &Failure($client, "key_exists: ".$key."\n",$userinput);
                   3275:             return 1;
1.283     albertel 3276: 	}
                   3277:     }
                   3278: 
                   3279:     foreach my $pair (@pairs) {
                   3280: 	my ($key,$value)=split(/=/,$pair);
                   3281: 	$hashref->{$key}=$value;
                   3282:     }
                   3283: 
1.311     albertel 3284:     if (&untie_user_hash($hashref)) {
1.283     albertel 3285: 	&Reply( $client, "ok\n", $userinput);
                   3286:     } else {
                   3287: 	&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3288: 		 "while attempting put\n", 
                   3289: 		 $userinput);
                   3290:     }
                   3291:     return 1;
                   3292: }
                   3293: &register_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
                   3294: 
1.230     foxr     3295: # 
                   3296: #   Increment a profile entry in the user history file.
                   3297: #   The history contains keyword value pairs.  In this case,
                   3298: #   The value itself is a pair of numbers.  The first, the current value
                   3299: #   the second an increment that this function applies to the current
                   3300: #   value.
                   3301: #
                   3302: # Parameters:
                   3303: #    $cmd      - The command that got us here.
                   3304: #    $tail     - Tail of the command (remaining parameters).
                   3305: #    $client   - File descriptor connected to client.
                   3306: # Returns
                   3307: #     0        - Requested to exit, caller should shut down.
                   3308: #     1        - Continue processing.
                   3309: #
                   3310: sub increment_user_value_handler {
                   3311:     my ($cmd, $tail, $client) = @_;
                   3312:     
                   3313:     my $userinput   = "$cmd:$tail";
                   3314:     
                   3315:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
                   3316:     if ($namespace ne 'roles') {
                   3317:         chomp($what);
                   3318: 	my $hashref = &tie_user_hash($udom, $uname,
                   3319: 				     $namespace, &GDBM_WRCREAT(),
                   3320: 				     "P",$what);
                   3321: 	if ($hashref) {
                   3322: 	    my @pairs=split(/\&/,$what);
                   3323: 	    foreach my $pair (@pairs) {
                   3324: 		my ($key,$value)=split(/=/,$pair);
1.284     raeburn  3325:                 $value = &unescape($value);
1.230     foxr     3326: 		# We could check that we have a number...
                   3327: 		if (! defined($value) || $value eq '') {
                   3328: 		    $value = 1;
                   3329: 		}
                   3330: 		$hashref->{$key}+=$value;
1.284     raeburn  3331:                 if ($namespace eq 'nohist_resourcetracker') {
                   3332:                     if ($hashref->{$key} < 0) {
                   3333:                         $hashref->{$key} = 0;
                   3334:                     }
                   3335:                 }
1.230     foxr     3336: 	    }
1.311     albertel 3337: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     3338: 		&Reply( $client, "ok\n", $userinput);
                   3339: 	    } else {
                   3340: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3341: 			 "while attempting inc\n", $userinput);
                   3342: 	    }
                   3343: 	} else {
                   3344: 	    &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3345: 		     "while attempting inc\n", $userinput);
                   3346: 	}
                   3347:     } else {
                   3348: 	&Failure($client, "refused\n", $userinput);
                   3349:     }
                   3350:     
                   3351:     return 1;
                   3352: }
                   3353: &register_handler("inc", \&increment_user_value_handler, 0, 1, 0);
                   3354: 
                   3355: #
                   3356: #   Put a new role for a user.  Roles are LonCAPA's packaging of permissions.
                   3357: #   Each 'role' a user has implies a set of permissions.  Adding a new role
                   3358: #   for a person grants the permissions packaged with that role
                   3359: #   to that user when the role is selected.
                   3360: #
                   3361: # Parameters:
                   3362: #    $cmd       - The command string (rolesput).
                   3363: #    $tail      - The remainder of the request line.  For rolesput this
                   3364: #                 consists of a colon separated list that contains:
                   3365: #                 The domain and user that is granting the role (logged).
                   3366: #                 The domain and user that is getting the role.
                   3367: #                 The roles being granted as a set of & separated pairs.
                   3368: #                 each pair a key value pair.
                   3369: #    $client    - File descriptor connected to the client.
                   3370: # Returns:
                   3371: #     0         - If the daemon should exit
                   3372: #     1         - To continue processing.
                   3373: #
                   3374: #
                   3375: sub roles_put_handler {
                   3376:     my ($cmd, $tail, $client) = @_;
                   3377: 
                   3378:     my $userinput  = "$cmd:$tail";
                   3379: 
                   3380:     my ( $exedom, $exeuser, $udom, $uname,  $what) = split(/:/,$tail);
                   3381:     
                   3382: 
                   3383:     my $namespace='roles';
                   3384:     chomp($what);
                   3385:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3386: 				 &GDBM_WRCREAT(), "P",
                   3387: 				 "$exedom:$exeuser:$what");
                   3388:     #
                   3389:     #  Log the attempt to set a role.  The {}'s here ensure that the file 
                   3390:     #  handle is open for the minimal amount of time.  Since the flush
                   3391:     #  is done on close this improves the chances the log will be an un-
                   3392:     #  corrupted ordered thing.
                   3393:     if ($hashref) {
1.261     foxr     3394: 	my $pass_entry = &get_auth_type($udom, $uname);
                   3395: 	my ($auth_type,$pwd)  = split(/:/, $pass_entry);
                   3396: 	$auth_type = $auth_type.":";
1.230     foxr     3397: 	my @pairs=split(/\&/,$what);
                   3398: 	foreach my $pair (@pairs) {
                   3399: 	    my ($key,$value)=split(/=/,$pair);
                   3400: 	    &manage_permissions($key, $udom, $uname,
1.260     foxr     3401: 			       $auth_type);
1.230     foxr     3402: 	    $hashref->{$key}=$value;
                   3403: 	}
1.311     albertel 3404: 	if (&untie_user_hash($hashref)) {
1.230     foxr     3405: 	    &Reply($client, "ok\n", $userinput);
                   3406: 	} else {
                   3407: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3408: 		     "while attempting rolesput\n", $userinput);
                   3409: 	}
                   3410:     } else {
                   3411: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3412: 		 "while attempting rolesput\n", $userinput);
                   3413:     }
                   3414:     return 1;
                   3415: }
                   3416: &register_handler("rolesput", \&roles_put_handler, 1,1,0);  # Encoded client only.
                   3417: 
                   3418: #
1.231     foxr     3419: #   Deletes (removes) a role for a user.   This is equivalent to removing
                   3420: #  a permissions package associated with the role from the user's profile.
                   3421: #
                   3422: # Parameters:
                   3423: #     $cmd                 - The command (rolesdel)
                   3424: #     $tail                - The remainder of the request line. This consists
                   3425: #                             of:
                   3426: #                             The domain and user requesting the change (logged)
                   3427: #                             The domain and user being changed.
                   3428: #                             The roles being revoked.  These are shipped to us
                   3429: #                             as a bunch of & separated role name keywords.
                   3430: #     $client              - The file handle open on the client.
                   3431: # Returns:
                   3432: #     1                    - Continue processing
                   3433: #     0                    - Exit.
                   3434: #
                   3435: sub roles_delete_handler {
                   3436:     my ($cmd, $tail, $client)  = @_;
                   3437: 
                   3438:     my $userinput    = "$cmd:$tail";
                   3439:    
                   3440:     my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
                   3441:     &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
                   3442: 	   "what = ".$what);
                   3443:     my $namespace='roles';
                   3444:     chomp($what);
                   3445:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3446: 				 &GDBM_WRCREAT(), "D",
                   3447: 				 "$exedom:$exeuser:$what");
                   3448:     
                   3449:     if ($hashref) {
                   3450: 	my @rolekeys=split(/\&/,$what);
                   3451: 	
                   3452: 	foreach my $key (@rolekeys) {
                   3453: 	    delete $hashref->{$key};
                   3454: 	}
1.315     albertel 3455: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3456: 	    &Reply($client, "ok\n", $userinput);
                   3457: 	} else {
                   3458: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3459: 		     "while attempting rolesdel\n", $userinput);
                   3460: 	}
                   3461:     } else {
                   3462:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3463: 		 "while attempting rolesdel\n", $userinput);
                   3464:     }
                   3465:     
                   3466:     return 1;
                   3467: }
                   3468: &register_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
                   3469: 
                   3470: # Unencrypted get from a user's profile database.  See 
                   3471: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
                   3472: # This function retrieves a keyed item from a specific named database in the
                   3473: # user's directory.
                   3474: #
                   3475: # Parameters:
                   3476: #   $cmd             - Command request keyword (get).
                   3477: #   $tail            - Tail of the command.  This is a colon separated list
                   3478: #                      consisting of the domain and username that uniquely
                   3479: #                      identifies the profile,
                   3480: #                      The 'namespace' which selects the gdbm file to 
                   3481: #                      do the lookup in, 
                   3482: #                      & separated list of keys to lookup.  Note that
                   3483: #                      the values are returned as an & separated list too.
                   3484: #   $client          - File descriptor open on the client.
                   3485: # Returns:
                   3486: #   1       - Continue processing.
                   3487: #   0       - Exit.
                   3488: #
                   3489: sub get_profile_entry {
                   3490:     my ($cmd, $tail, $client) = @_;
                   3491: 
                   3492:     my $userinput= "$cmd:$tail";
                   3493:    
                   3494:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   3495:     chomp($what);
1.255     foxr     3496: 
1.390     raeburn  3497: 
1.255     foxr     3498:     my $replystring = read_profile($udom, $uname, $namespace, $what);
                   3499:     my ($first) = split(/:/,$replystring);
                   3500:     if($first ne "error") {
1.387     albertel 3501: 	&Reply($client, \$replystring, $userinput);
1.231     foxr     3502:     } else {
1.255     foxr     3503: 	&Failure($client, $replystring." while attempting get\n", $userinput);
1.231     foxr     3504:     }
                   3505:     return 1;
1.255     foxr     3506: 
                   3507: 
1.231     foxr     3508: }
                   3509: &register_handler("get", \&get_profile_entry, 0,1,0);
                   3510: 
                   3511: #
                   3512: #  Process the encrypted get request.  Note that the request is sent
                   3513: #  in clear, but the reply is encrypted.  This is a small covert channel:
                   3514: #  information about the sensitive keys is given to the snooper.  Just not
                   3515: #  information about the values of the sensitive key.  Hmm if I wanted to
                   3516: #  know these I'd snoop for the egets. Get the profile item names from them
                   3517: #  and then issue a get for them since there's no enforcement of the
                   3518: #  requirement of an encrypted get for particular profile items.  If I
                   3519: #  were re-doing this, I'd force the request to be encrypted as well as the
                   3520: #  reply.  I'd also just enforce encrypted transactions for all gets since
                   3521: #  that would prevent any covert channel snooping.
                   3522: #
                   3523: #  Parameters:
                   3524: #     $cmd               - Command keyword of request (eget).
1.536     raeburn  3525: #     $tail              - Tail of the command.  See GetProfileEntry
                   3526: #                          for more information about this.
1.231     foxr     3527: #     $client            - File open on the client.
                   3528: #  Returns:
                   3529: #     1      - Continue processing
                   3530: #     0      - server should exit.
                   3531: sub get_profile_entry_encrypted {
                   3532:     my ($cmd, $tail, $client) = @_;
                   3533: 
                   3534:     my $userinput = "$cmd:$tail";
                   3535:    
1.339     albertel 3536:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
1.231     foxr     3537:     chomp($what);
1.255     foxr     3538:     my $qresult = read_profile($udom, $uname, $namespace, $what);
                   3539:     my ($first) = split(/:/, $qresult);
                   3540:     if($first ne "error") {
                   3541: 	
                   3542: 	if ($cipher) {
                   3543: 	    my $cmdlength=length($qresult);
                   3544: 	    $qresult.="         ";
                   3545: 	    my $encqresult='';
                   3546: 	    for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   3547: 		$encqresult.= unpack("H16", 
                   3548: 				     $cipher->encrypt(substr($qresult,
                   3549: 							     $encidx,
                   3550: 							     8)));
                   3551: 	    }
                   3552: 	    &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
                   3553: 	} else {
1.231     foxr     3554: 		&Failure( $client, "error:no_key\n", $userinput);
                   3555: 	    }
                   3556:     } else {
1.255     foxr     3557: 	&Failure($client, "$qresult while attempting eget\n", $userinput);
                   3558: 
1.231     foxr     3559:     }
                   3560:     
                   3561:     return 1;
                   3562: }
1.255     foxr     3563: &register_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
1.263     albertel 3564: 
1.231     foxr     3565: #
                   3566: #   Deletes a key in a user profile database.
                   3567: #   
                   3568: #   Parameters:
                   3569: #       $cmd                  - Command keyword (del).
                   3570: #       $tail                 - Command tail.  IN this case a colon
                   3571: #                               separated list containing:
                   3572: #                               The domain and user that identifies uniquely
                   3573: #                               the identity of the user.
                   3574: #                               The profile namespace (name of the profile
                   3575: #                               database file).
                   3576: #                               & separated list of keywords to delete.
                   3577: #       $client              - File open on client socket.
                   3578: # Returns:
                   3579: #     1   - Continue processing
                   3580: #     0   - Exit server.
                   3581: #
                   3582: #
                   3583: sub delete_profile_entry {
                   3584:     my ($cmd, $tail, $client) = @_;
                   3585: 
                   3586:     my $userinput = "cmd:$tail";
                   3587: 
                   3588:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   3589:     chomp($what);
                   3590:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3591: 				 &GDBM_WRCREAT(),
                   3592: 				 "D",$what);
                   3593:     if ($hashref) {
                   3594:         my @keys=split(/\&/,$what);
                   3595: 	foreach my $key (@keys) {
                   3596: 	    delete($hashref->{$key});
                   3597: 	}
1.315     albertel 3598: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3599: 	    &Reply($client, "ok\n", $userinput);
                   3600: 	} else {
                   3601: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3602: 		    "while attempting del\n", $userinput);
                   3603: 	}
                   3604:     } else {
                   3605: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3606: 		 "while attempting del\n", $userinput);
                   3607:     }
                   3608:     return 1;
                   3609: }
                   3610: &register_handler("del", \&delete_profile_entry, 0, 1, 0);
1.263     albertel 3611: 
1.231     foxr     3612: #
                   3613: #  List the set of keys that are defined in a profile database file.
                   3614: #  A successful reply from this will contain an & separated list of
                   3615: #  the keys. 
                   3616: # Parameters:
                   3617: #     $cmd              - Command request (keys).
                   3618: #     $tail             - Remainder of the request, a colon separated
                   3619: #                         list containing domain/user that identifies the
                   3620: #                         user being queried, and the database namespace
                   3621: #                         (database filename essentially).
                   3622: #     $client           - File open on the client.
                   3623: #  Returns:
                   3624: #    1    - Continue processing.
                   3625: #    0    - Exit the server.
                   3626: #
                   3627: sub get_profile_keys {
                   3628:     my ($cmd, $tail, $client) = @_;
                   3629: 
                   3630:     my $userinput = "$cmd:$tail";
                   3631: 
                   3632:     my ($udom,$uname,$namespace)=split(/:/,$tail);
                   3633:     my $qresult='';
                   3634:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3635: 				  &GDBM_READER());
                   3636:     if ($hashref) {
                   3637: 	foreach my $key (keys %$hashref) {
                   3638: 	    $qresult.="$key&";
                   3639: 	}
1.315     albertel 3640: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3641: 	    $qresult=~s/\&$//;
1.387     albertel 3642: 	    &Reply($client, \$qresult, $userinput);
1.231     foxr     3643: 	} else {
                   3644: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3645: 		    "while attempting keys\n", $userinput);
                   3646: 	}
                   3647:     } else {
                   3648: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3649: 		 "while attempting keys\n", $userinput);
                   3650:     }
                   3651:    
                   3652:     return 1;
                   3653: }
                   3654: &register_handler("keys", \&get_profile_keys, 0, 1, 0);
                   3655: 
                   3656: #
                   3657: #   Dump the contents of a user profile database.
                   3658: #   Note that this constitutes a very large covert channel too since
                   3659: #   the dump will return sensitive information that is not encrypted.
                   3660: #   The naive security assumption is that the session negotiation ensures
                   3661: #   our client is trusted and I don't believe that's assured at present.
                   3662: #   Sure want badly to go to ssl or tls.  Of course if my peer isn't really
                   3663: #   a LonCAPA node they could have negotiated an encryption key too so >sigh<.
                   3664: # 
                   3665: #  Parameters:
                   3666: #     $cmd           - The command request keyword (currentdump).
                   3667: #     $tail          - Remainder of the request, consisting of a colon
                   3668: #                      separated list that has the domain/username and
                   3669: #                      the namespace to dump (database file).
                   3670: #     $client        - file open on the remote client.
                   3671: # Returns:
                   3672: #     1    - Continue processing.
                   3673: #     0    - Exit the server.
                   3674: #
                   3675: sub dump_profile_database {
                   3676:     my ($cmd, $tail, $client) = @_;
                   3677: 
1.494     droeschl 3678:     my $res = LONCAPA::Lond::dump_profile_database($tail);
                   3679: 
                   3680:     if ($res =~ /^error:/) {
                   3681:         Failure($client, \$res, "$cmd:$tail");
                   3682:     } else {
                   3683:         Reply($client, \$res, "$cmd:$tail");
                   3684:     }
                   3685: 
                   3686:     return 1;  
                   3687: 
                   3688:     #TODO remove 
1.231     foxr     3689:     my $userinput = "$cmd:$tail";
                   3690:    
                   3691:     my ($udom,$uname,$namespace) = split(/:/,$tail);
                   3692:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3693: 				 &GDBM_READER());
                   3694:     if ($hashref) {
                   3695: 	# Structure of %data:
                   3696: 	# $data{$symb}->{$parameter}=$value;
                   3697: 	# $data{$symb}->{'v.'.$parameter}=$version;
                   3698: 	# since $parameter will be unescaped, we do not
                   3699:  	# have to worry about silly parameter names...
                   3700: 	
                   3701:         my $qresult='';
                   3702: 	my %data = ();                     # A hash of anonymous hashes..
                   3703: 	while (my ($key,$value) = each(%$hashref)) {
                   3704: 	    my ($v,$symb,$param) = split(/:/,$key);
                   3705: 	    next if ($v eq 'version' || $symb eq 'keys');
                   3706: 	    next if (exists($data{$symb}) && 
                   3707: 		     exists($data{$symb}->{$param}) &&
                   3708: 		     $data{$symb}->{'v.'.$param} > $v);
                   3709: 	    $data{$symb}->{$param}=$value;
                   3710: 	    $data{$symb}->{'v.'.$param}=$v;
                   3711: 	}
1.311     albertel 3712: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3713: 	    while (my ($symb,$param_hash) = each(%data)) {
                   3714: 		while(my ($param,$value) = each (%$param_hash)){
                   3715: 		    next if ($param =~ /^v\./);       # Ignore versions...
                   3716: 		    #
                   3717: 		    #   Just dump the symb=value pairs separated by &
                   3718: 		    #
                   3719: 		    $qresult.=$symb.':'.$param.'='.$value.'&';
                   3720: 		}
                   3721: 	    }
                   3722: 	    chop($qresult);
1.387     albertel 3723: 	    &Reply($client , \$qresult, $userinput);
1.231     foxr     3724: 	} else {
                   3725: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3726: 		     "while attempting currentdump\n", $userinput);
                   3727: 	}
                   3728:     } else {
                   3729: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3730: 		"while attempting currentdump\n", $userinput);
                   3731:     }
                   3732: 
                   3733:     return 1;
                   3734: }
                   3735: &register_handler("currentdump", \&dump_profile_database, 0, 1, 0);
                   3736: 
                   3737: #
                   3738: #   Dump a profile database with an optional regular expression
                   3739: #   to match against the keys.  In this dump, no effort is made
                   3740: #   to separate symb from version information. Presumably the
                   3741: #   databases that are dumped by this command are of a different
                   3742: #   structure.  Need to look at this and improve the documentation of
                   3743: #   both this and the currentdump handler.
                   3744: # Parameters:
                   3745: #    $cmd                     - The command keyword.
                   3746: #    $tail                    - All of the characters after the $cmd:
                   3747: #                               These are expected to be a colon
                   3748: #                               separated list containing:
                   3749: #                               domain/user - identifying the user.
                   3750: #                               namespace   - identifying the database.
                   3751: #                               regexp      - optional regular expression
                   3752: #                                             that is matched against
                   3753: #                                             database keywords to do
                   3754: #                                             selective dumps.
1.488     raeburn  3755: #                               range       - optional range of entries
                   3756: #                                             e.g., 10-20 would return the
                   3757: #                                             10th to 19th items, etc.  
1.231     foxr     3758: #   $client                   - Channel open on the client.
                   3759: # Returns:
                   3760: #    1    - Continue processing.
                   3761: # Side effects:
                   3762: #    response is written to $client.
                   3763: #
                   3764: sub dump_with_regexp {
                   3765:     my ($cmd, $tail, $client) = @_;
                   3766: 
1.494     droeschl 3767:     my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
1.490     droeschl 3768:     
                   3769:     if ($res =~ /^error:/) {
                   3770:         Failure($client, \$res, "$cmd:$tail");
                   3771:     } else {
                   3772:         Reply($client, \$res, "$cmd:$tail");
                   3773:     }
1.231     foxr     3774: 
                   3775:     return 1;
                   3776: }
                   3777: &register_handler("dump", \&dump_with_regexp, 0, 1, 0);
                   3778: 
                   3779: #  Store a set of key=value pairs associated with a versioned name.
                   3780: #
                   3781: #  Parameters:
                   3782: #    $cmd                - Request command keyword.
                   3783: #    $tail               - Tail of the request.  This is a colon
                   3784: #                          separated list containing:
                   3785: #                          domain/user - User and authentication domain.
                   3786: #                          namespace   - Name of the database being modified
                   3787: #                          rid         - Resource keyword to modify.
                   3788: #                          what        - new value associated with rid.
1.512     raeburn  3789: #                          laststore   - (optional) version=timestamp
                   3790: #                                        for most recent transaction for rid
                   3791: #                                        in namespace, when cstore was called
1.231     foxr     3792: #
                   3793: #    $client             - Socket open on the client.
                   3794: #
                   3795: #
                   3796: #  Returns:
                   3797: #      1 (keep on processing).
                   3798: #  Side-Effects:
                   3799: #    Writes to the client
1.512     raeburn  3800: #    Successful storage will cause either 'ok', or, if $laststore was included
                   3801: #    in the tail of the request, and the version number for the last transaction
                   3802: #    is larger than the version in $laststore, delay:$numtrans , where $numtrans
                   3803: #    is the number of store evevnts recorded for rid in namespace since
                   3804: #    lonnet::store() was called by the client.
                   3805: #
1.231     foxr     3806: sub store_handler {
                   3807:     my ($cmd, $tail, $client) = @_;
                   3808:  
                   3809:     my $userinput = "$cmd:$tail";
1.512     raeburn  3810:     chomp($tail);
                   3811:     my ($udom,$uname,$namespace,$rid,$what,$laststore) =split(/:/,$tail);
1.231     foxr     3812:     if ($namespace ne 'roles') {
                   3813: 
                   3814: 	my @pairs=split(/\&/,$what);
                   3815: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
1.268     albertel 3816: 				       &GDBM_WRCREAT(), "S",
1.231     foxr     3817: 				       "$rid:$what");
                   3818: 	if ($hashref) {
                   3819: 	    my $now = time;
1.512     raeburn  3820:             my $numtrans;
                   3821:             if ($laststore) {
                   3822:                 my ($previousversion,$previoustime) = split(/\=/,$laststore);
                   3823:                 my ($lastversion,$lasttime) = (0,0);
                   3824:                 $lastversion = $hashref->{"version:$rid"};
                   3825:                 if ($lastversion) {
                   3826:                     $lasttime = $hashref->{"$lastversion:$rid:timestamp"};
                   3827:                 }
                   3828:                 if (($previousversion) && ($previousversion !~ /\D/)) {
                   3829:                     if (($lastversion > $previousversion) && ($lasttime >= $previoustime)) {
                   3830:                         $numtrans = $lastversion - $previousversion;
                   3831:                     }
                   3832:                 } elsif ($lastversion) {
                   3833:                     $numtrans = $lastversion;
                   3834:                 }
                   3835:                 if ($numtrans) {
                   3836:                     $numtrans =~ s/D//g;
                   3837:                 }
                   3838:             }
1.231     foxr     3839: 	    $hashref->{"version:$rid"}++;
                   3840: 	    my $version=$hashref->{"version:$rid"};
                   3841: 	    my $allkeys=''; 
                   3842: 	    foreach my $pair (@pairs) {
                   3843: 		my ($key,$value)=split(/=/,$pair);
                   3844: 		$allkeys.=$key.':';
                   3845: 		$hashref->{"$version:$rid:$key"}=$value;
                   3846: 	    }
                   3847: 	    $hashref->{"$version:$rid:timestamp"}=$now;
                   3848: 	    $allkeys.='timestamp';
                   3849: 	    $hashref->{"$version:keys:$rid"}=$allkeys;
1.311     albertel 3850: 	    if (&untie_user_hash($hashref)) {
1.512     raeburn  3851:                 my $msg = 'ok';
                   3852:                 if ($numtrans) {
                   3853:                     $msg = 'delay:'.$numtrans;
                   3854:                 }
                   3855: 		&Reply($client, "$msg\n", $userinput);
1.231     foxr     3856: 	    } else {
                   3857: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3858: 			"while attempting store\n", $userinput);
                   3859: 	    }
                   3860: 	} else {
                   3861: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3862: 		     "while attempting store\n", $userinput);
                   3863: 	}
                   3864:     } else {
                   3865: 	&Failure($client, "refused\n", $userinput);
                   3866:     }
                   3867: 
                   3868:     return 1;
                   3869: }
                   3870: &register_handler("store", \&store_handler, 0, 1, 0);
1.263     albertel 3871: 
1.323     albertel 3872: #  Modify a set of key=value pairs associated with a versioned name.
                   3873: #
                   3874: #  Parameters:
                   3875: #    $cmd                - Request command keyword.
                   3876: #    $tail               - Tail of the request.  This is a colon
                   3877: #                          separated list containing:
                   3878: #                          domain/user - User and authentication domain.
                   3879: #                          namespace   - Name of the database being modified
                   3880: #                          rid         - Resource keyword to modify.
                   3881: #                          v           - Version item to modify
                   3882: #                          what        - new value associated with rid.
                   3883: #
                   3884: #    $client             - Socket open on the client.
                   3885: #
                   3886: #
                   3887: #  Returns:
                   3888: #      1 (keep on processing).
                   3889: #  Side-Effects:
                   3890: #    Writes to the client
                   3891: sub putstore_handler {
                   3892:     my ($cmd, $tail, $client) = @_;
                   3893:  
                   3894:     my $userinput = "$cmd:$tail";
                   3895: 
                   3896:     my ($udom,$uname,$namespace,$rid,$v,$what) =split(/:/,$tail);
                   3897:     if ($namespace ne 'roles') {
                   3898: 
                   3899: 	chomp($what);
                   3900: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
                   3901: 				       &GDBM_WRCREAT(), "M",
                   3902: 				       "$rid:$v:$what");
                   3903: 	if ($hashref) {
                   3904: 	    my $now = time;
                   3905: 	    my %data = &hash_extract($what);
                   3906: 	    my @allkeys;
                   3907: 	    while (my($key,$value) = each(%data)) {
                   3908: 		push(@allkeys,$key);
                   3909: 		$hashref->{"$v:$rid:$key"} = $value;
                   3910: 	    }
                   3911: 	    my $allkeys = join(':',@allkeys);
                   3912: 	    $hashref->{"$v:keys:$rid"}=$allkeys;
                   3913: 
                   3914: 	    if (&untie_user_hash($hashref)) {
                   3915: 		&Reply($client, "ok\n", $userinput);
                   3916: 	    } else {
                   3917: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3918: 			"while attempting store\n", $userinput);
                   3919: 	    }
                   3920: 	} else {
                   3921: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3922: 		     "while attempting store\n", $userinput);
                   3923: 	}
                   3924:     } else {
                   3925: 	&Failure($client, "refused\n", $userinput);
                   3926:     }
                   3927: 
                   3928:     return 1;
                   3929: }
                   3930: &register_handler("putstore", \&putstore_handler, 0, 1, 0);
                   3931: 
                   3932: sub hash_extract {
                   3933:     my ($str)=@_;
                   3934:     my %hash;
                   3935:     foreach my $pair (split(/\&/,$str)) {
                   3936: 	my ($key,$value)=split(/=/,$pair);
                   3937: 	$hash{$key}=$value;
                   3938:     }
                   3939:     return (%hash);
                   3940: }
                   3941: sub hash_to_str {
                   3942:     my ($hash_ref)=@_;
                   3943:     my $str;
                   3944:     foreach my $key (keys(%$hash_ref)) {
                   3945: 	$str.=$key.'='.$hash_ref->{$key}.'&';
                   3946:     }
                   3947:     $str=~s/\&$//;
                   3948:     return $str;
                   3949: }
                   3950: 
1.231     foxr     3951: #
                   3952: #  Dump out all versions of a resource that has key=value pairs associated
                   3953: # with it for each version.  These resources are built up via the store
                   3954: # command.
                   3955: #
                   3956: #  Parameters:
                   3957: #     $cmd               - Command keyword.
                   3958: #     $tail              - Remainder of the request which consists of:
                   3959: #                          domain/user   - User and auth. domain.
                   3960: #                          namespace     - name of resource database.
                   3961: #                          rid           - Resource id.
                   3962: #    $client             - socket open on the client.
                   3963: #
                   3964: # Returns:
                   3965: #      1  indicating the caller should not yet exit.
                   3966: # Side-effects:
                   3967: #   Writes a reply to the client.
                   3968: #   The reply is a string of the following shape:
                   3969: #   version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
                   3970: #    Where the 1 above represents version 1.
                   3971: #    this continues for all pairs of keys in all versions.
                   3972: #
                   3973: #
                   3974: #    
                   3975: #
                   3976: sub restore_handler {
                   3977:     my ($cmd, $tail, $client) = @_;
                   3978: 
                   3979:     my $userinput = "$cmd:$tail";	# Only used for logging purposes.
1.351     banghart 3980:     my ($udom,$uname,$namespace,$rid) = split(/:/,$tail);
1.352     albertel 3981:     $namespace=~s/\//\_/g;
1.350     albertel 3982:     $namespace = &LONCAPA::clean_username($namespace);
1.349     albertel 3983: 
1.231     foxr     3984:     chomp($rid);
                   3985:     my $qresult='';
1.309     albertel 3986:     my $hashref = &tie_user_hash($udom, $uname, $namespace, &GDBM_READER());
                   3987:     if ($hashref) {
                   3988: 	my $version=$hashref->{"version:$rid"};
1.231     foxr     3989: 	$qresult.="version=$version&";
                   3990: 	my $scope;
                   3991: 	for ($scope=1;$scope<=$version;$scope++) {
1.309     albertel 3992: 	    my $vkeys=$hashref->{"$scope:keys:$rid"};
1.231     foxr     3993: 	    my @keys=split(/:/,$vkeys);
                   3994: 	    my $key;
                   3995: 	    $qresult.="$scope:keys=$vkeys&";
                   3996: 	    foreach $key (@keys) {
1.309     albertel 3997: 		$qresult.="$scope:$key=".$hashref->{"$scope:$rid:$key"}."&";
1.231     foxr     3998: 	    }                                  
                   3999: 	}
1.311     albertel 4000: 	if (&untie_user_hash($hashref)) {
1.231     foxr     4001: 	    $qresult=~s/\&$//;
1.387     albertel 4002: 	    &Reply( $client, \$qresult, $userinput);
1.231     foxr     4003: 	} else {
                   4004: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4005: 		    "while attempting restore\n", $userinput);
                   4006: 	}
                   4007:     } else {
                   4008: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4009: 		"while attempting restore\n", $userinput);
                   4010:     }
                   4011:   
                   4012:     return 1;
                   4013: 
                   4014: 
                   4015: }
                   4016: &register_handler("restore", \&restore_handler, 0,1,0);
1.234     foxr     4017: 
                   4018: #
1.324     raeburn  4019: #   Add a chat message to a synchronous discussion board.
1.234     foxr     4020: #
                   4021: # Parameters:
                   4022: #    $cmd                - Request keyword.
                   4023: #    $tail               - Tail of the command. A colon separated list
                   4024: #                          containing:
                   4025: #                          cdom    - Domain on which the chat board lives
1.324     raeburn  4026: #                          cnum    - Course containing the chat board.
                   4027: #                          newpost - Body of the posting.
                   4028: #                          group   - Optional group, if chat board is only 
                   4029: #                                    accessible in a group within the course 
1.234     foxr     4030: #   $client              - Socket open on the client.
                   4031: # Returns:
                   4032: #   1    - Indicating caller should keep on processing.
                   4033: #
                   4034: # Side-effects:
                   4035: #   writes a reply to the client.
                   4036: #
                   4037: #
                   4038: sub send_chat_handler {
                   4039:     my ($cmd, $tail, $client) = @_;
                   4040: 
                   4041:     
                   4042:     my $userinput = "$cmd:$tail";
                   4043: 
1.324     raeburn  4044:     my ($cdom,$cnum,$newpost,$group)=split(/\:/,$tail);
                   4045:     &chat_add($cdom,$cnum,$newpost,$group);
1.234     foxr     4046:     &Reply($client, "ok\n", $userinput);
                   4047: 
                   4048:     return 1;
                   4049: }
                   4050: &register_handler("chatsend", \&send_chat_handler, 0, 1, 0);
1.263     albertel 4051: 
1.234     foxr     4052: #
1.324     raeburn  4053: #   Retrieve the set of chat messages from a discussion board.
1.234     foxr     4054: #
                   4055: #  Parameters:
                   4056: #    $cmd             - Command keyword that initiated the request.
                   4057: #    $tail            - Remainder of the request after the command
                   4058: #                       keyword.  In this case a colon separated list of
                   4059: #                       chat domain    - Which discussion board.
                   4060: #                       chat id        - Discussion thread(?)
                   4061: #                       domain/user    - Authentication domain and username
                   4062: #                                        of the requesting person.
1.324     raeburn  4063: #                       group          - Optional course group containing
                   4064: #                                        the board.      
1.234     foxr     4065: #   $client           - Socket open on the client program.
                   4066: # Returns:
                   4067: #    1     - continue processing
                   4068: # Side effects:
                   4069: #    Response is written to the client.
                   4070: #
                   4071: sub retrieve_chat_handler {
                   4072:     my ($cmd, $tail, $client) = @_;
                   4073: 
                   4074: 
                   4075:     my $userinput = "$cmd:$tail";
                   4076: 
1.324     raeburn  4077:     my ($cdom,$cnum,$udom,$uname,$group)=split(/\:/,$tail);
1.234     foxr     4078:     my $reply='';
1.324     raeburn  4079:     foreach (&get_chat($cdom,$cnum,$udom,$uname,$group)) {
1.234     foxr     4080: 	$reply.=&escape($_).':';
                   4081:     }
                   4082:     $reply=~s/\:$//;
1.387     albertel 4083:     &Reply($client, \$reply, $userinput);
1.234     foxr     4084: 
                   4085: 
                   4086:     return 1;
                   4087: }
                   4088: &register_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
                   4089: 
                   4090: #
                   4091: #  Initiate a query of an sql database.  SQL query repsonses get put in
                   4092: #  a file for later retrieval.  This prevents sql query results from
                   4093: #  bottlenecking the system.  Note that with loncnew, perhaps this is
                   4094: #  less of an issue since multiple outstanding requests can be concurrently
                   4095: #  serviced.
                   4096: #
                   4097: #  Parameters:
1.535     raeburn  4098: #     $cmd       - Command keyword that initiated the request.
1.234     foxr     4099: #     $tail      - Remainder of the command after the keyword.
                   4100: #                  For this function, this consists of a query and
                   4101: #                  3 arguments that are self-documentingly labelled
                   4102: #                  in the original arg1, arg2, arg3.
                   4103: #     $client    - Socket open on the client.
                   4104: # Return:
                   4105: #    1   - Indicating processing should continue.
                   4106: # Side-effects:
                   4107: #    a reply is written to $client.
                   4108: #
                   4109: sub send_query_handler {
                   4110:     my ($cmd, $tail, $client) = @_;
                   4111: 
                   4112:     my $userinput = "$cmd:$tail";
                   4113: 
                   4114:     my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
                   4115:     $query=~s/\n*$//g;
1.534     raeburn  4116:     if (($query eq 'usersearch') || ($query eq 'instdirsearch')) {
                   4117:         my $usersearchconf = &get_usersearch_config($currentdomainid,'directorysrch');
                   4118:         my $earlyout;
                   4119:         if (ref($usersearchconf) eq 'HASH') {
                   4120:             if ($currentdomainid eq $clienthomedom) {
                   4121:                 if ($query eq 'usersearch') {
                   4122:                     if ($usersearchconf->{'lcavailable'} eq '0') {
                   4123:                         $earlyout = 1;
                   4124:                     }
                   4125:                 } else {
                   4126:                     if ($usersearchconf->{'available'} eq '0') {
                   4127:                         $earlyout = 1;
                   4128:                     }
                   4129:                 }
                   4130:             } else {
                   4131:                 if ($query eq 'usersearch') {
                   4132:                     if ($usersearchconf->{'lclocalonly'}) {
                   4133:                         $earlyout = 1;
                   4134:                     }
                   4135:                 } else {
                   4136:                     if ($usersearchconf->{'localonly'}) {
                   4137:                         $earlyout = 1;
                   4138:                     }
                   4139:                 }
                   4140:             }
                   4141:         }
                   4142:         if ($earlyout) {
                   4143:             &Reply($client, "query_not_authorized\n");
                   4144:             return 1;
                   4145:         }
                   4146:     }
1.234     foxr     4147:     &Reply($client, "". &sql_reply("$clientname\&$query".
                   4148: 				"\&$arg1"."\&$arg2"."\&$arg3")."\n",
                   4149: 	  $userinput);
                   4150:     
                   4151:     return 1;
                   4152: }
                   4153: &register_handler("querysend", \&send_query_handler, 0, 1, 0);
                   4154: 
                   4155: #
                   4156: #   Add a reply to an sql query.  SQL queries are done asyncrhonously.
                   4157: #   The query is submitted via a "querysend" transaction.
                   4158: #   There it is passed on to the lonsql daemon, queued and issued to
                   4159: #   mysql.
                   4160: #     This transaction is invoked when the sql transaction is complete
                   4161: #   it stores the query results in flie and indicates query completion.
                   4162: #   presumably local software then fetches this response... I'm guessing
                   4163: #   the sequence is: lonc does a querysend, we ask lonsql to do it.
                   4164: #   lonsql on completion of the query interacts with the lond of our
                   4165: #   client to do a query reply storing two files:
                   4166: #    - id     - The results of the query.
                   4167: #    - id.end - Indicating the transaction completed. 
                   4168: #    NOTE: id is a unique id assigned to the query and querysend time.
                   4169: # Parameters:
                   4170: #    $cmd        - Command keyword that initiated this request.
                   4171: #    $tail       - Remainder of the tail.  In this case that's a colon
                   4172: #                  separated list containing the query Id and the 
                   4173: #                  results of the query.
                   4174: #    $client     - Socket open on the client.
                   4175: # Return:
                   4176: #    1           - Indicating that we should continue processing.
                   4177: # Side effects:
                   4178: #    ok written to the client.
                   4179: #
                   4180: sub reply_query_handler {
                   4181:     my ($cmd, $tail, $client) = @_;
                   4182: 
                   4183: 
                   4184:     my $userinput = "$cmd:$tail";
                   4185: 
1.339     albertel 4186:     my ($id,$reply)=split(/:/,$tail); 
1.234     foxr     4187:     my $store;
                   4188:     my $execdir=$perlvar{'lonDaemons'};
                   4189:     if ($store=IO::File->new(">$execdir/tmp/$id")) {
                   4190: 	$reply=~s/\&/\n/g;
                   4191: 	print $store $reply;
                   4192: 	close $store;
                   4193: 	my $store2=IO::File->new(">$execdir/tmp/$id.end");
                   4194: 	print $store2 "done\n";
                   4195: 	close $store2;
                   4196: 	&Reply($client, "ok\n", $userinput);
                   4197:     } else {
                   4198: 	&Failure($client, "error: ".($!+0)
                   4199: 		." IO::File->new Failed ".
                   4200: 		"while attempting queryreply\n", $userinput);
                   4201:     }
                   4202:  
                   4203: 
                   4204:     return 1;
                   4205: }
                   4206: &register_handler("queryreply", \&reply_query_handler, 0, 1, 0);
                   4207: 
                   4208: #
                   4209: #  Process the courseidput request.  Not quite sure what this means
                   4210: #  at the system level sense.  It appears a gdbm file in the 
                   4211: #  /home/httpd/lonUsers/$domain/nohist_courseids is tied and
                   4212: #  a set of entries made in that database.
                   4213: #
                   4214: # Parameters:
                   4215: #   $cmd      - The command keyword that initiated this request.
                   4216: #   $tail     - Tail of the command.  In this case consists of a colon
                   4217: #               separated list contaning the domain to apply this to and
                   4218: #               an ampersand separated list of keyword=value pairs.
1.272     raeburn  4219: #               Each value is a colon separated list that includes:  
                   4220: #               description, institutional code and course owner.
                   4221: #               For backward compatibility with versions included
                   4222: #               in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
                   4223: #               code and/or course owner are preserved from the existing 
                   4224: #               record when writing a new record in response to 1.1 or 
                   4225: #               1.2 implementations of lonnet::flushcourselogs().   
                   4226: #                      
1.234     foxr     4227: #   $client   - Socket open on the client.
                   4228: # Returns:
                   4229: #   1    - indicating that processing should continue
                   4230: #
                   4231: # Side effects:
                   4232: #   reply is written to the client.
                   4233: #
                   4234: sub put_course_id_handler {
                   4235:     my ($cmd, $tail, $client) = @_;
                   4236: 
                   4237: 
                   4238:     my $userinput = "$cmd:$tail";
                   4239: 
1.266     raeburn  4240:     my ($udom, $what) = split(/:/, $tail,2);
1.234     foxr     4241:     chomp($what);
                   4242:     my $now=time;
                   4243:     my @pairs=split(/\&/,$what);
                   4244: 
                   4245:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   4246:     if ($hashref) {
                   4247: 	foreach my $pair (@pairs) {
1.271     raeburn  4248:             my ($key,$courseinfo) = split(/=/,$pair,2);
                   4249:             $courseinfo =~ s/=/:/g;
1.384     raeburn  4250:             if (defined($hashref->{$key})) {
                   4251:                 my $value = &Apache::lonnet::thaw_unescape($hashref->{$key});
                   4252:                 if (ref($value) eq 'HASH') {
                   4253:                     my @items = ('description','inst_code','owner','type');
                   4254:                     my @new_items = split(/:/,$courseinfo,-1);
                   4255:                     my %storehash; 
                   4256:                     for (my $i=0; $i<@new_items; $i++) {
1.391     raeburn  4257:                         $storehash{$items[$i]} = &unescape($new_items[$i]);
1.384     raeburn  4258:                     }
                   4259:                     $hashref->{$key} = 
                   4260:                         &Apache::lonnet::freeze_escape(\%storehash);
                   4261:                     my $unesc_key = &unescape($key);
                   4262:                     $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
                   4263:                     next;
1.383     raeburn  4264:                 }
1.384     raeburn  4265:             }
                   4266:             my @current_items = split(/:/,$hashref->{$key},-1);
                   4267:             shift(@current_items); # remove description
                   4268:             pop(@current_items);   # remove last access
                   4269:             my $numcurrent = scalar(@current_items);
                   4270:             if ($numcurrent > 3) {
                   4271:                 $numcurrent = 3;
                   4272:             }
                   4273:             my @new_items = split(/:/,$courseinfo,-1);
                   4274:             my $numnew = scalar(@new_items);
                   4275:             if ($numcurrent > 0) {
                   4276:                 if ($numnew <= $numcurrent) { # flushcourselogs() from pre 2.2 
                   4277:                     for (my $j=$numcurrent-$numnew; $j>=0; $j--) {
                   4278:                         $courseinfo .= ':'.$current_items[$numcurrent-$j-1];
1.333     raeburn  4279:                     }
1.272     raeburn  4280:                 }
                   4281:             }
1.384     raeburn  4282:             $hashref->{$key}=$courseinfo.':'.$now;
1.234     foxr     4283: 	}
1.311     albertel 4284: 	if (&untie_domain_hash($hashref)) {
1.253     foxr     4285: 	    &Reply( $client, "ok\n", $userinput);
1.234     foxr     4286: 	} else {
1.253     foxr     4287: 	    &Failure($client, "error: ".($!+0)
1.234     foxr     4288: 		     ." untie(GDBM) Failed ".
                   4289: 		     "while attempting courseidput\n", $userinput);
                   4290: 	}
                   4291:     } else {
1.253     foxr     4292: 	&Failure($client, "error: ".($!+0)
1.234     foxr     4293: 		 ." tie(GDBM) Failed ".
                   4294: 		 "while attempting courseidput\n", $userinput);
                   4295:     }
                   4296: 
                   4297:     return 1;
                   4298: }
                   4299: &register_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
                   4300: 
1.383     raeburn  4301: sub put_course_id_hash_handler {
                   4302:     my ($cmd, $tail, $client) = @_;
                   4303:     my $userinput = "$cmd:$tail";
1.384     raeburn  4304:     my ($udom,$mode,$what) = split(/:/, $tail,3);
1.383     raeburn  4305:     chomp($what);
                   4306:     my $now=time;
                   4307:     my @pairs=split(/\&/,$what);
1.384     raeburn  4308:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
1.383     raeburn  4309:     if ($hashref) {
                   4310:         foreach my $pair (@pairs) {
                   4311:             my ($key,$value)=split(/=/,$pair);
1.384     raeburn  4312:             my $unesc_key = &unescape($key);
                   4313:             if ($mode ne 'timeonly') {
                   4314:                 if (!defined($hashref->{&escape('lasttime:'.$unesc_key)})) {
                   4315:                     my $curritems = &Apache::lonnet::thaw_unescape($key); 
                   4316:                     if (ref($curritems) ne 'HASH') {
                   4317:                         my @current_items = split(/:/,$hashref->{$key},-1);
                   4318:                         my $lasttime = pop(@current_items);
                   4319:                         $hashref->{&escape('lasttime:'.$unesc_key)} = $lasttime;
                   4320:                     } else {
                   4321:                         $hashref->{&escape('lasttime:'.$unesc_key)} = '';
                   4322:                     }
                   4323:                 } 
                   4324:                 $hashref->{$key} = $value;
                   4325:             }
                   4326:             if ($mode ne 'notime') {
                   4327:                 $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
                   4328:             }
1.383     raeburn  4329:         }
                   4330:         if (&untie_domain_hash($hashref)) {
                   4331:             &Reply($client, "ok\n", $userinput);
                   4332:         } else {
                   4333:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4334:                      "while attempting courseidputhash\n", $userinput);
                   4335:         }
                   4336:     } else {
                   4337:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4338:                   "while attempting courseidputhash\n", $userinput);
                   4339:     }
                   4340:     return 1;
                   4341: }
                   4342: &register_handler("courseidputhash", \&put_course_id_hash_handler, 0, 1, 0);
                   4343: 
1.234     foxr     4344: #  Retrieves the value of a course id resource keyword pattern
                   4345: #  defined since a starting date.  Both the starting date and the
                   4346: #  keyword pattern are optional.  If the starting date is not supplied it
                   4347: #  is treated as the beginning of time.  If the pattern is not found,
                   4348: #  it is treatred as "." matching everything.
                   4349: #
                   4350: #  Parameters:
                   4351: #     $cmd     - Command keyword that resulted in us being dispatched.
                   4352: #     $tail    - The remainder of the command that, in this case, consists
                   4353: #                of a colon separated list of:
                   4354: #                 domain   - The domain in which the course database is 
                   4355: #                            defined.
                   4356: #                 since    - Optional parameter describing the minimum
                   4357: #                            time of definition(?) of the resources that
                   4358: #                            will match the dump.
                   4359: #                 description - regular expression that is used to filter
                   4360: #                            the dump.  Only keywords matching this regexp
                   4361: #                            will be used.
1.272     raeburn  4362: #                 institutional code - optional supplied code to filter 
                   4363: #                            the dump. Only courses with an institutional code 
                   4364: #                            that match the supplied code will be returned.
1.336     raeburn  4365: #                 owner    - optional supplied username and domain of owner to
                   4366: #                            filter the dump.  Only courses for which the course
                   4367: #                            owner matches the supplied username and/or domain
                   4368: #                            will be returned. Pre-2.2.0 legacy entries from 
                   4369: #                            nohist_courseiddump will only contain usernames.
1.384     raeburn  4370: #                 type     - optional parameter for selection 
1.418     raeburn  4371: #                 regexp_ok - if 1 or -1 allow the supplied institutional code
                   4372: #                            filter to behave as a regular expression:
                   4373: #	                      1 will not exclude the course if the instcode matches the RE 
                   4374: #                            -1 will exclude the course if the instcode matches the RE
1.384     raeburn  4375: #                 rtn_as_hash - whether to return the information available for
                   4376: #                            each matched item as a frozen hash of all 
                   4377: #                            key, value pairs in the item's hash, or as a 
                   4378: #                            colon-separated list of (in order) description,
                   4379: #                            institutional code, and course owner.
1.404     raeburn  4380: #                 selfenrollonly - filter by courses allowing self-enrollment  
                   4381: #                                  now or in the future (selfenrollonly = 1).
                   4382: #                 catfilter - filter by course category, assigned to a course 
                   4383: #                             using manually defined categories (i.e., not
1.407     raeburn  4384: #                             self-cataloging based on on institutional code).   
1.404     raeburn  4385: #                 showhidden - include course in results even if course  
1.407     raeburn  4386: #                              was set to be excluded from course catalog (DC only).
1.404     raeburn  4387: #                 caller -  if set to 'coursecatalog', courses set to be hidden
                   4388: #                           from course catalog will be excluded from results (unless
                   4389: #                           overridden by "showhidden".
1.427     raeburn  4390: #                 cloner - escaped username:domain of course cloner (if picking course to
1.419     raeburn  4391: #                          clone).
                   4392: #                 cc_clone_list - escaped comma separated list of courses for which 
                   4393: #                                 course cloner has active CC role (and so can clone
                   4394: #                                 automatically).
1.427     raeburn  4395: #                 cloneonly - filter by courses for which cloner has rights to clone.
                   4396: #                 createdbefore - include courses for which creation date preceeded this date.
                   4397: #                 createdafter - include courses for which creation date followed this date.
                   4398: #                 creationcontext - include courses created in specified context 
1.404     raeburn  4399: #
1.445     raeburn  4400: #                 domcloner - flag to indicate if user can create CCs in course's domain.
1.505     raeburn  4401: #                             If so, ability to clone course is automatic.
                   4402: #                 hasuniquecode - filter by courses for which a six character unique code has 
                   4403: #                                 been set.
1.445     raeburn  4404: #
1.234     foxr     4405: #     $client  - The socket open on the client.
                   4406: # Returns:
                   4407: #    1     - Continue processing.
                   4408: # Side Effects:
                   4409: #   a reply is written to $client.
                   4410: sub dump_course_id_handler {
                   4411:     my ($cmd, $tail, $client) = @_;
1.494     droeschl 4412: 
                   4413:     my $res = LONCAPA::Lond::dump_course_id_handler($tail);
                   4414:     if ($res =~ /^error:/) {
                   4415:         Failure($client, \$res, "$cmd:$tail");
                   4416:     } else {
                   4417:         Reply($client, \$res, "$cmd:$tail");
                   4418:     }
                   4419: 
                   4420:     return 1;  
                   4421: 
                   4422:     #TODO remove
1.234     foxr     4423:     my $userinput = "$cmd:$tail";
                   4424: 
1.333     raeburn  4425:     my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter,
1.404     raeburn  4426:         $typefilter,$regexp_ok,$rtn_as_hash,$selfenrollonly,$catfilter,$showhidden,
1.427     raeburn  4427:         $caller,$cloner,$cc_clone_list,$cloneonly,$createdbefore,$createdafter,
1.505     raeburn  4428:         $creationcontext,$domcloner,$hasuniquecode) =split(/:/,$tail);
1.397     raeburn  4429:     my $now = time;
1.419     raeburn  4430:     my ($cloneruname,$clonerudom,%cc_clone);
1.234     foxr     4431:     if (defined($description)) {
                   4432: 	$description=&unescape($description);
                   4433:     } else {
                   4434: 	$description='.';
                   4435:     }
1.266     raeburn  4436:     if (defined($instcodefilter)) {
                   4437:         $instcodefilter=&unescape($instcodefilter);
                   4438:     } else {
                   4439:         $instcodefilter='.';
                   4440:     }
1.336     raeburn  4441:     my ($ownerunamefilter,$ownerdomfilter);
1.266     raeburn  4442:     if (defined($ownerfilter)) {
                   4443:         $ownerfilter=&unescape($ownerfilter);
1.336     raeburn  4444:         if ($ownerfilter ne '.' && defined($ownerfilter)) {
                   4445:             if ($ownerfilter =~ /^([^:]*):([^:]*)$/) {
                   4446:                  $ownerunamefilter = $1;
                   4447:                  $ownerdomfilter = $2;
                   4448:             } else {
                   4449:                 $ownerunamefilter = $ownerfilter;
                   4450:                 $ownerdomfilter = '';
                   4451:             }
                   4452:         }
1.266     raeburn  4453:     } else {
                   4454:         $ownerfilter='.';
                   4455:     }
1.336     raeburn  4456: 
1.282     raeburn  4457:     if (defined($coursefilter)) {
                   4458:         $coursefilter=&unescape($coursefilter);
                   4459:     } else {
                   4460:         $coursefilter='.';
                   4461:     }
1.333     raeburn  4462:     if (defined($typefilter)) {
                   4463:         $typefilter=&unescape($typefilter);
                   4464:     } else {
                   4465:         $typefilter='.';
                   4466:     }
1.344     raeburn  4467:     if (defined($regexp_ok)) {
                   4468:         $regexp_ok=&unescape($regexp_ok);
                   4469:     }
1.401     raeburn  4470:     if (defined($catfilter)) {
                   4471:         $catfilter=&unescape($catfilter);
                   4472:     }
1.419     raeburn  4473:     if (defined($cloner)) {
                   4474:         $cloner = &unescape($cloner);
                   4475:         ($cloneruname,$clonerudom) = ($cloner =~ /^($LONCAPA::match_username):($LONCAPA::match_domain)$/); 
                   4476:     }
                   4477:     if (defined($cc_clone_list)) {
                   4478:         $cc_clone_list = &unescape($cc_clone_list);
                   4479:         my @cc_cloners = split('&',$cc_clone_list);
                   4480:         foreach my $cid (@cc_cloners) {
                   4481:             my ($clonedom,$clonenum) = split(':',$cid);
                   4482:             next if ($clonedom ne $udom); 
                   4483:             $cc_clone{$clonedom.'_'.$clonenum} = 1;
                   4484:         } 
                   4485:     }
1.431     raeburn  4486:     if ($createdbefore ne '') {
1.427     raeburn  4487:         $createdbefore = &unescape($createdbefore);
                   4488:     } else {
                   4489:        $createdbefore = 0;
                   4490:     }
1.431     raeburn  4491:     if ($createdafter ne '') {
1.427     raeburn  4492:         $createdafter = &unescape($createdafter);
                   4493:     } else {
                   4494:         $createdafter = 0;
                   4495:     }
1.431     raeburn  4496:     if ($creationcontext ne '') {
1.427     raeburn  4497:         $creationcontext = &unescape($creationcontext);
                   4498:     } else {
                   4499:         $creationcontext = '.';
                   4500:     }
1.505     raeburn  4501:     unless ($hasuniquecode) {
                   4502:         $hasuniquecode = '.';
                   4503:     }
1.384     raeburn  4504:     my $unpack = 1;
1.485     raeburn  4505:     if ($description eq '.' && $instcodefilter eq '.' && $ownerfilter eq '.' && 
1.384     raeburn  4506:         $typefilter eq '.') {
                   4507:         $unpack = 0;
                   4508:     }
                   4509:     if (!defined($since)) { $since=0; }
1.234     foxr     4510:     my $qresult='';
                   4511:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   4512:     if ($hashref) {
1.384     raeburn  4513: 	while (my ($key,$value) = each(%$hashref)) {
1.397     raeburn  4514:             my ($unesc_key,$lasttime_key,$lasttime,$is_hash,%val,
1.427     raeburn  4515:                 %unesc_val,$selfenroll_end,$selfenroll_types,$created,
                   4516:                 $context);
1.384     raeburn  4517:             $unesc_key = &unescape($key);
                   4518:             if ($unesc_key =~ /^lasttime:/) {
                   4519:                 next;
                   4520:             } else {
                   4521:                 $lasttime_key = &escape('lasttime:'.$unesc_key);
                   4522:             }
                   4523:             if ($hashref->{$lasttime_key} ne '') {
                   4524:                 $lasttime = $hashref->{$lasttime_key};
                   4525:                 next if ($lasttime<$since);
                   4526:             }
1.419     raeburn  4527:             my ($canclone,$valchange);
1.384     raeburn  4528:             my $items = &Apache::lonnet::thaw_unescape($value);
                   4529:             if (ref($items) eq 'HASH') {
1.429     raeburn  4530:                 if ($hashref->{$lasttime_key} eq '') {
1.430     raeburn  4531:                     next if ($since > 1);
1.429     raeburn  4532:                 }
1.384     raeburn  4533:                 $is_hash =  1;
1.445     raeburn  4534:                 if ($domcloner) {
                   4535:                     $canclone = 1;
                   4536:                 } elsif (defined($clonerudom)) {
1.419     raeburn  4537:                     if ($items->{'cloners'}) {
                   4538:                         my @cloneable = split(',',$items->{'cloners'});
                   4539:                         if (@cloneable) {
                   4540:                             if (grep(/^\*$/,@cloneable))  {
                   4541:                                 $canclone = 1;
                   4542:                             } elsif (grep(/^\*:\Q$clonerudom\E$/,@cloneable)) {
                   4543:                                 $canclone = 1;
                   4544:                             } elsif (grep(/^\Q$cloneruname\E:\Q$clonerudom\E$/,@cloneable)) {
                   4545:                                 $canclone = 1;
                   4546:                             }
                   4547:                         }
                   4548:                         unless ($canclone) {
                   4549:                             if ($cloneruname ne '' && $clonerudom ne '') {
                   4550:                                 if ($cc_clone{$unesc_key}) {
                   4551:                                     $canclone = 1;
                   4552:                                     $items->{'cloners'} .= ','.$cloneruname.':'.
                   4553:                                                            $clonerudom;
                   4554:                                     $valchange = 1;
                   4555:                                 }
                   4556:                             }
                   4557:                         }
                   4558:                     } elsif (defined($cloneruname)) {
                   4559:                         if ($cc_clone{$unesc_key}) {
                   4560:                             $canclone = 1;
                   4561:                             $items->{'cloners'} = $cloneruname.':'.$clonerudom;
                   4562:                             $valchange = 1;
                   4563:                         }
1.437     raeburn  4564:                         unless ($canclone) {
                   4565:                             if ($items->{'owner'} =~ /:/) {
                   4566:                                 if ($items->{'owner'} eq $cloner) {
                   4567:                                     $canclone = 1;
                   4568:                                 }
1.444     raeburn  4569:                             } elsif ($cloner eq $items->{'owner'}.':'.$udom) {
1.437     raeburn  4570:                                 $canclone = 1;
                   4571:                             }
                   4572:                             if ($canclone) {
                   4573:                                 $items->{'cloners'} = $cloneruname.':'.$clonerudom;
                   4574:                                 $valchange = 1;
                   4575:                             }
                   4576:                         }
1.419     raeburn  4577:                     }
                   4578:                 }
1.384     raeburn  4579:                 if ($unpack || !$rtn_as_hash) {
                   4580:                     $unesc_val{'descr'} = $items->{'description'};
                   4581:                     $unesc_val{'inst_code'} = $items->{'inst_code'};
                   4582:                     $unesc_val{'owner'} = $items->{'owner'};
                   4583:                     $unesc_val{'type'} = $items->{'type'};
1.419     raeburn  4584:                     $unesc_val{'cloners'} = $items->{'cloners'};
1.427     raeburn  4585:                     $unesc_val{'created'} = $items->{'created'};
                   4586:                     $unesc_val{'context'} = $items->{'context'};
1.404     raeburn  4587:                 }
                   4588:                 $selfenroll_types = $items->{'selfenroll_types'};
                   4589:                 $selfenroll_end = $items->{'selfenroll_end_date'};
1.427     raeburn  4590:                 $created = $items->{'created'};
                   4591:                 $context = $items->{'context'};
1.505     raeburn  4592:                 if ($hasuniquecode ne '.') {
                   4593:                     next unless ($items->{'uniquecode'});
                   4594:                 }
1.404     raeburn  4595:                 if ($selfenrollonly) {
                   4596:                     next if (!$selfenroll_types);
                   4597:                     if (($selfenroll_end > 0) && ($selfenroll_end <= $now)) {
                   4598:                         next;
1.397     raeburn  4599:                     }
1.404     raeburn  4600:                 }
1.427     raeburn  4601:                 if ($creationcontext ne '.') {
                   4602:                     next if (($context ne '') && ($context ne $creationcontext));  
                   4603:                 }
                   4604:                 if ($createdbefore > 0) {
                   4605:                     next if (($created eq '') || ($created > $createdbefore));   
                   4606:                 }
                   4607:                 if ($createdafter > 0) {
                   4608:                     next if (($created eq '') || ($created <= $createdafter)); 
                   4609:                 }
1.404     raeburn  4610:                 if ($catfilter ne '') {
1.406     raeburn  4611:                     next if ($items->{'categories'} eq '');
                   4612:                     my @categories = split('&',$items->{'categories'}); 
1.407     raeburn  4613:                     next if (@categories == 0);
                   4614:                     my @subcats = split('&',$catfilter);
                   4615:                     my $matchcat = 0;
                   4616:                     foreach my $cat (@categories) {
                   4617:                         if (grep(/^\Q$cat\E$/,@subcats)) {
                   4618:                             $matchcat = 1;
                   4619:                             last;
                   4620:                         }
                   4621:                     }
                   4622:                     next if (!$matchcat);
1.404     raeburn  4623:                 }
                   4624:                 if ($caller eq 'coursecatalog') {
1.405     raeburn  4625:                     if ($items->{'hidefromcat'} eq 'yes') {
                   4626:                         next if !$showhidden;
1.401     raeburn  4627:                     }
1.384     raeburn  4628:                 }
1.383     raeburn  4629:             } else {
1.401     raeburn  4630:                 next if ($catfilter ne '');
1.419     raeburn  4631:                 next if ($selfenrollonly);
1.427     raeburn  4632:                 next if ($createdbefore || $createdafter);
                   4633:                 next if ($creationcontext ne '.');
1.419     raeburn  4634:                 if ((defined($clonerudom)) && (defined($cloneruname)))  {
                   4635:                     if ($cc_clone{$unesc_key}) {
                   4636:                         $canclone = 1;
                   4637:                         $val{'cloners'} = &escape($cloneruname.':'.$clonerudom);
                   4638:                     }
                   4639:                 }
1.384     raeburn  4640:                 $is_hash =  0;
1.388     raeburn  4641:                 my @courseitems = split(/:/,$value);
1.403     raeburn  4642:                 $lasttime = pop(@courseitems);
1.402     raeburn  4643:                 if ($hashref->{$lasttime_key} eq '') {
                   4644:                     next if ($lasttime<$since);
                   4645:                 }
1.384     raeburn  4646: 	        ($val{'descr'},$val{'inst_code'},$val{'owner'},$val{'type'}) = @courseitems;
1.383     raeburn  4647:             }
1.419     raeburn  4648:             if ($cloneonly) {
                   4649:                next unless ($canclone);
                   4650:             }
1.266     raeburn  4651:             my $match = 1;
1.384     raeburn  4652: 	    if ($description ne '.') {
                   4653:                 if (!$is_hash) {
                   4654:                     $unesc_val{'descr'} = &unescape($val{'descr'});
                   4655:                 }
                   4656:                 if (eval{$unesc_val{'descr'} !~ /\Q$description\E/i}) {
1.266     raeburn  4657:                     $match = 0;
1.384     raeburn  4658:                 }
1.266     raeburn  4659:             }
1.384     raeburn  4660:             if ($instcodefilter ne '.') {
                   4661:                 if (!$is_hash) {
                   4662:                     $unesc_val{'inst_code'} = &unescape($val{'inst_code'});
                   4663:                 }
1.418     raeburn  4664:                 if ($regexp_ok == 1) {
1.384     raeburn  4665:                     if (eval{$unesc_val{'inst_code'} !~ /$instcodefilter/}) {
1.344     raeburn  4666:                         $match = 0;
                   4667:                     }
1.418     raeburn  4668:                 } elsif ($regexp_ok == -1) {
                   4669:                     if (eval{$unesc_val{'inst_code'} =~ /$instcodefilter/}) {
                   4670:                         $match = 0;
                   4671:                     }
1.344     raeburn  4672:                 } else {
1.384     raeburn  4673:                     if (eval{$unesc_val{'inst_code'} !~ /\Q$instcodefilter\E/i}) {
1.344     raeburn  4674:                         $match = 0;
                   4675:                     }
1.266     raeburn  4676:                 }
1.234     foxr     4677: 	    }
1.384     raeburn  4678:             if ($ownerfilter ne '.') {
                   4679:                 if (!$is_hash) {
                   4680:                     $unesc_val{'owner'} = &unescape($val{'owner'});
                   4681:                 }
1.336     raeburn  4682:                 if (($ownerunamefilter ne '') && ($ownerdomfilter ne '')) {
1.384     raeburn  4683:                     if ($unesc_val{'owner'} =~ /:/) {
                   4684:                         if (eval{$unesc_val{'owner'} !~ 
                   4685:                              /\Q$ownerunamefilter\E:\Q$ownerdomfilter\E$/i}) {
1.336     raeburn  4686:                             $match = 0;
                   4687:                         } 
                   4688:                     } else {
1.384     raeburn  4689:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336     raeburn  4690:                             $match = 0;
                   4691:                         }
                   4692:                     }
                   4693:                 } elsif ($ownerunamefilter ne '') {
1.384     raeburn  4694:                     if ($unesc_val{'owner'} =~ /:/) {
                   4695:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E:[^:]+$/i}) {
1.336     raeburn  4696:                              $match = 0;
                   4697:                         }
                   4698:                     } else {
1.384     raeburn  4699:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336     raeburn  4700:                             $match = 0;
                   4701:                         }
                   4702:                     }
                   4703:                 } elsif ($ownerdomfilter ne '') {
1.384     raeburn  4704:                     if ($unesc_val{'owner'} =~ /:/) {
                   4705:                         if (eval{$unesc_val{'owner'} !~ /^[^:]+:\Q$ownerdomfilter\E/}) {
1.336     raeburn  4706:                              $match = 0;
                   4707:                         }
                   4708:                     } else {
                   4709:                         if ($ownerdomfilter ne $udom) {
                   4710:                             $match = 0;
                   4711:                         }
                   4712:                     }
1.266     raeburn  4713:                 }
                   4714:             }
1.384     raeburn  4715:             if ($coursefilter ne '.') {
                   4716:                 if (eval{$unesc_key !~ /^$udom(_)\Q$coursefilter\E$/}) {
1.282     raeburn  4717:                     $match = 0;
                   4718:                 }
                   4719:             }
1.384     raeburn  4720:             if ($typefilter ne '.') {
                   4721:                 if (!$is_hash) {
                   4722:                     $unesc_val{'type'} = &unescape($val{'type'});
                   4723:                 }
                   4724:                 if ($unesc_val{'type'} eq '') {
1.333     raeburn  4725:                     if ($typefilter ne 'Course') {
                   4726:                         $match = 0;
                   4727:                     }
1.383     raeburn  4728:                 } else {
1.384     raeburn  4729:                     if (eval{$unesc_val{'type'} !~ /^\Q$typefilter\E$/}) {
1.333     raeburn  4730:                         $match = 0;
                   4731:                     }
                   4732:                 }
                   4733:             }
1.266     raeburn  4734:             if ($match == 1) {
1.384     raeburn  4735:                 if ($rtn_as_hash) {
                   4736:                     if ($is_hash) {
1.419     raeburn  4737:                         if ($valchange) {
                   4738:                             my $newvalue = &Apache::lonnet::freeze_escape($items);
                   4739:                             $qresult.=$key.'='.$newvalue.'&';
                   4740:                         } else {
                   4741:                             $qresult.=$key.'='.$value.'&';
                   4742:                         }
1.384     raeburn  4743:                     } else {
1.388     raeburn  4744:                         my %rtnhash = ( 'description' => &unescape($val{'descr'}),
                   4745:                                         'inst_code' => &unescape($val{'inst_code'}),
                   4746:                                         'owner'     => &unescape($val{'owner'}),
                   4747:                                         'type'      => &unescape($val{'type'}),
1.419     raeburn  4748:                                         'cloners'   => &unescape($val{'cloners'}),
1.384     raeburn  4749:                                       );
                   4750:                         my $items = &Apache::lonnet::freeze_escape(\%rtnhash);
                   4751:                         $qresult.=$key.'='.$items.'&';
                   4752:                     }
1.383     raeburn  4753:                 } else {
1.384     raeburn  4754:                     if ($is_hash) {
                   4755:                         $qresult .= $key.'='.&escape($unesc_val{'descr'}).':'.
                   4756:                                     &escape($unesc_val{'inst_code'}).':'.
                   4757:                                     &escape($unesc_val{'owner'}).'&';
                   4758:                     } else {
                   4759:                         $qresult .= $key.'='.$val{'descr'}.':'.$val{'inst_code'}.
                   4760:                                     ':'.$val{'owner'}.'&';
                   4761:                     }
1.383     raeburn  4762:                 }
1.266     raeburn  4763:             }
1.234     foxr     4764: 	}
1.311     albertel 4765: 	if (&untie_domain_hash($hashref)) {
1.234     foxr     4766: 	    chop($qresult);
1.387     albertel 4767: 	    &Reply($client, \$qresult, $userinput);
1.234     foxr     4768: 	} else {
                   4769: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4770: 		    "while attempting courseiddump\n", $userinput);
                   4771: 	}
                   4772:     } else {
                   4773: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4774: 		"while attempting courseiddump\n", $userinput);
                   4775:     }
                   4776:     return 1;
                   4777: }
                   4778: &register_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
1.238     foxr     4779: 
1.438     raeburn  4780: sub course_lastaccess_handler {
                   4781:     my ($cmd, $tail, $client) = @_;
                   4782:     my $userinput = "$cmd:$tail";
                   4783:     my ($cdom,$cnum) = split(':',$tail); 
                   4784:     my (%lastaccess,$qresult);
                   4785:     my $hashref = &tie_domain_hash($cdom, "nohist_courseids", &GDBM_WRCREAT());
                   4786:     if ($hashref) {
                   4787:         while (my ($key,$value) = each(%$hashref)) {
                   4788:             my ($unesc_key,$lasttime);
                   4789:             $unesc_key = &unescape($key);
                   4790:             if ($cnum) {
                   4791:                 next unless ($unesc_key =~ /\Q$cdom\E_\Q$cnum\E$/);
                   4792:             }
                   4793:             if ($unesc_key =~ /^lasttime:($LONCAPA::match_domain\_$LONCAPA::match_courseid)/) {
                   4794:                 $lastaccess{$1} = $value;
                   4795:             } else {
                   4796:                 my $items = &Apache::lonnet::thaw_unescape($value);
                   4797:                 if (ref($items) eq 'HASH') {
                   4798:                     unless ($lastaccess{$unesc_key}) {
                   4799:                         $lastaccess{$unesc_key} = '';
                   4800:                     }
                   4801:                 } else {
                   4802:                     my @courseitems = split(':',$value);
                   4803:                     $lastaccess{$unesc_key} = pop(@courseitems);
                   4804:                 }
                   4805:             }
                   4806:         }
                   4807:         foreach my $cid (sort(keys(%lastaccess))) {
                   4808:             $qresult.=&escape($cid).'='.$lastaccess{$cid}.'&'; 
                   4809:         }
                   4810:         if (&untie_domain_hash($hashref)) {
                   4811:             if ($qresult) {
                   4812:                 chop($qresult);
                   4813:             }
                   4814:             &Reply($client, \$qresult, $userinput);
                   4815:         } else {
                   4816:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4817:                     "while attempting lastacourseaccess\n", $userinput);
                   4818:         }
                   4819:     } else {
                   4820:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4821:                 "while attempting lastcourseaccess\n", $userinput);
                   4822:     }
                   4823:     return 1;
                   4824: }
                   4825: &register_handler("courselastaccess",\&course_lastaccess_handler, 0, 1, 0);
                   4826: 
1.238     foxr     4827: #
1.348     raeburn  4828: # Puts an unencrypted entry in a namespace db file at the domain level 
                   4829: #
                   4830: # Parameters:
                   4831: #    $cmd      - The command that got us here.
                   4832: #    $tail     - Tail of the command (remaining parameters).
                   4833: #    $client   - File descriptor connected to client.
                   4834: # Returns
                   4835: #     0        - Requested to exit, caller should shut down.
                   4836: #     1        - Continue processing.
                   4837: #  Side effects:
                   4838: #     reply is written to $client.
                   4839: #
                   4840: sub put_domain_handler {
                   4841:     my ($cmd,$tail,$client) = @_;
                   4842: 
                   4843:     my $userinput = "$cmd:$tail";
                   4844: 
                   4845:     my ($udom,$namespace,$what) =split(/:/,$tail,3);
                   4846:     chomp($what);
                   4847:     my @pairs=split(/\&/,$what);
                   4848:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_WRCREAT(),
                   4849:                                    "P", $what);
                   4850:     if ($hashref) {
                   4851:         foreach my $pair (@pairs) {
                   4852:             my ($key,$value)=split(/=/,$pair);
                   4853:             $hashref->{$key}=$value;
                   4854:         }
                   4855:         if (&untie_domain_hash($hashref)) {
                   4856:             &Reply($client, "ok\n", $userinput);
                   4857:         } else {
                   4858:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4859:                      "while attempting putdom\n", $userinput);
                   4860:         }
                   4861:     } else {
                   4862:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4863:                   "while attempting putdom\n", $userinput);
                   4864:     }
                   4865: 
                   4866:     return 1;
                   4867: }
                   4868: &register_handler("putdom", \&put_domain_handler, 0, 1, 0);
                   4869: 
1.517     raeburn  4870: # Updates one or more entries in clickers.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 updating the entries,
                   4877: #                (b) the action required -- add or del -- and
                   4878: #                (c) a &-separated list of entries to add or delete.
                   4879: #    $client   - File descriptor connected to client.
                   4880: # Returns
                   4881: #     1        - Continue processing.
                   4882: #     0        - Requested to exit, caller should shut down.
                   4883: #  Side effects:
                   4884: #     reply is written to $client.
                   4885: #
                   4886: 
                   4887: 
                   4888: sub update_clickers {
                   4889:     my ($cmd, $tail, $client)  = @_;
                   4890: 
                   4891:     my $userinput = "$cmd:$tail";
                   4892:     my ($udom,$action,$what) =split(/:/,$tail,3);
                   4893:     chomp($what);
                   4894: 
                   4895:     my $hashref = &tie_domain_hash($udom, "clickers", &GDBM_WRCREAT(),
                   4896:                                  "U","$action:$what");
                   4897: 
                   4898:     if (!$hashref) {
                   4899:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4900:                   "while attempting updateclickers\n", $userinput);
                   4901:         return 1;
                   4902:     }
                   4903: 
                   4904:     my @pairs=split(/\&/,$what);
                   4905:     foreach my $pair (@pairs) {
                   4906:         my ($key,$value)=split(/=/,$pair);
                   4907:         if ($action eq 'add') {
                   4908:             if (exists($hashref->{$key})) {
                   4909:                 my @newvals = split(/,/,&unescape($value));
                   4910:                 my @currvals = split(/,/,&unescape($hashref->{$key}));
                   4911:                 my @merged = sort(keys(%{{map { $_ => 1 } (@newvals,@currvals)}}));
                   4912:                 $hashref->{$key}=&escape(join(',',@merged));
                   4913:             } else {
                   4914:                 $hashref->{$key}=$value;
                   4915:             }
                   4916:         } elsif ($action eq 'del') {
                   4917:             if (exists($hashref->{$key})) {
                   4918:                 my %current;
                   4919:                 map { $current{$_} = 1; } split(/,/,&unescape($hashref->{$key}));
                   4920:                 map { delete($current{$_}); } split(/,/,&unescape($value));
                   4921:                 if (keys(%current)) {
                   4922:                     $hashref->{$key}=&escape(join(',',sort(keys(%current))));
                   4923:                 } else {
                   4924:                     delete($hashref->{$key});
                   4925:                 }
                   4926:             }
                   4927:         }
                   4928:     }
                   4929:     if (&untie_user_hash($hashref)) {
                   4930:         &Reply( $client, "ok\n", $userinput);
                   4931:     } else {
                   4932:         &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   4933:                  "while attempting put\n",
                   4934:                  $userinput);
                   4935:     }
                   4936:     return 1;
                   4937: }
                   4938: &register_handler("updateclickers", \&update_clickers, 0, 1, 0);
                   4939: 
                   4940: 
                   4941: # Deletes one or more entries in a namespace db file at the domain level
                   4942: #
                   4943: # Parameters:
                   4944: #    $cmd      - The command that got us here.
                   4945: #    $tail     - Tail of the command (remaining parameters).
                   4946: #                In this case a colon separated list containing:
                   4947: #                (a) the domain for which we are deleting the entries,
                   4948: #                (b) &-separated list of keys to delete.  
                   4949: #    $client   - File descriptor connected to client.
                   4950: # Returns
                   4951: #     1        - Continue processing.
                   4952: #     0        - Requested to exit, caller should shut down.
                   4953: #  Side effects:
                   4954: #     reply is written to $client.
                   4955: #
                   4956: 
                   4957: sub del_domain_handler {
                   4958:     my ($cmd,$tail,$client) = @_;
                   4959: 
                   4960:     my $userinput = "$cmd:$tail";
                   4961: 
                   4962:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   4963:     chomp($what);
                   4964:     my $hashref = &tie_domain_hash($udom,$namespace,&GDBM_WRCREAT(),
                   4965:                                    "D", $what);
                   4966:     if ($hashref) {
                   4967:         my @keys=split(/\&/,$what);
                   4968:         foreach my $key (@keys) {
                   4969:             delete($hashref->{$key});
                   4970:         }
                   4971:         if (&untie_user_hash($hashref)) {
                   4972:             &Reply($client, "ok\n", $userinput);
                   4973:         } else {
                   4974:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4975:                     "while attempting deldom\n", $userinput);
                   4976:         }
                   4977:     } else {
                   4978:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4979:                  "while attempting deldom\n", $userinput);
                   4980:     }
                   4981:     return 1;
                   4982: }
                   4983: &register_handler("deldom", \&del_domain_handler, 0, 1, 0);
                   4984: 
                   4985: 
1.348     raeburn  4986: # Unencrypted get from the namespace database file at the domain level.
                   4987: # This function retrieves a keyed item from a specific named database in the
                   4988: # domain directory.
                   4989: #
                   4990: # Parameters:
                   4991: #   $cmd             - Command request keyword (get).
                   4992: #   $tail            - Tail of the command.  This is a colon separated list
                   4993: #                      consisting of the domain and the 'namespace' 
                   4994: #                      which selects the gdbm file to do the lookup in,
                   4995: #                      & separated list of keys to lookup.  Note that
                   4996: #                      the values are returned as an & separated list too.
                   4997: #   $client          - File descriptor open on the client.
                   4998: # Returns:
                   4999: #   1       - Continue processing.
                   5000: #   0       - Exit.
                   5001: #  Side effects:
                   5002: #     reply is written to $client.
                   5003: #
                   5004: 
                   5005: sub get_domain_handler {
                   5006:     my ($cmd, $tail, $client) = @_;
                   5007: 
1.461     foxr     5008: 
1.536     raeburn  5009:     my $userinput = "$cmd:$tail";
                   5010: 
                   5011:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   5012:     chomp($what);
                   5013:     if ($namespace =~ /^enc/) {
                   5014:         &Failure( $client, "refused\n", $userinput);
                   5015:     } else {
                   5016:         my @queries=split(/\&/,$what);
                   5017:         my $qresult='';
                   5018:         my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_READER());
                   5019:         if ($hashref) {
                   5020:             for (my $i=0;$i<=$#queries;$i++) {
                   5021:                 $qresult.="$hashref->{$queries[$i]}&";
                   5022:             }
                   5023:             if (&untie_domain_hash($hashref)) {
                   5024:                 $qresult=~s/\&$//;
                   5025:                 &Reply($client, \$qresult, $userinput);
                   5026:             } else {
                   5027:                 &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5028:                           "while attempting getdom\n",$userinput);
                   5029:             }
                   5030:         } else {
                   5031:             &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5032:                      "while attempting getdom\n",$userinput);
                   5033:         }
                   5034:     }
                   5035: 
                   5036:     return 1;
                   5037: }
                   5038: &register_handler("getdom", \&get_domain_handler, 0, 1, 0);
                   5039: 
                   5040: sub encrypted_get_domain_handler {
                   5041:     my ($cmd, $tail, $client) = @_;
                   5042: 
                   5043:     my $userinput = "$cmd:$tail";
1.348     raeburn  5044: 
                   5045:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   5046:     chomp($what);
                   5047:     my @queries=split(/\&/,$what);
                   5048:     my $qresult='';
                   5049:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_READER());
                   5050:     if ($hashref) {
                   5051:         for (my $i=0;$i<=$#queries;$i++) {
                   5052:             $qresult.="$hashref->{$queries[$i]}&";
                   5053:         }
                   5054:         if (&untie_domain_hash($hashref)) {
                   5055:             $qresult=~s/\&$//;
1.536     raeburn  5056:             if ($cipher) {
                   5057:                 my $cmdlength=length($qresult);
                   5058:                 $qresult.="         ";
                   5059:                 my $encqresult='';
                   5060:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   5061:                     $encqresult.= unpack("H16",
                   5062:                                          $cipher->encrypt(substr($qresult,
                   5063:                                                                  $encidx,
                   5064:                                                                  8)));
                   5065:                 }
                   5066:                 &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
                   5067:             } else {
                   5068:                 &Failure( $client, "error:no_key\n", $userinput);
                   5069:             }
1.348     raeburn  5070:         } else {
                   5071:             &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
1.536     raeburn  5072:                       "while attempting egetdom\n",$userinput);
1.348     raeburn  5073:         }
                   5074:     } else {
                   5075:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
1.536     raeburn  5076:                  "while attempting egetdom\n",$userinput);
1.348     raeburn  5077:     }
                   5078:     return 1;
                   5079: }
1.536     raeburn  5080: &register_handler("egetdom", \&encrypted_get_domain_handler, 1, 1, 0);
1.348     raeburn  5081: 
1.420     raeburn  5082: #
1.238     foxr     5083: #  Puts an id to a domains id database. 
                   5084: #
                   5085: #  Parameters:
                   5086: #   $cmd     - The command that triggered us.
                   5087: #   $tail    - Remainder of the request other than the command. This is a 
                   5088: #              colon separated list containing:
                   5089: #              $domain  - The domain for which we are writing the id.
                   5090: #              $pairs  - The id info to write... this is and & separated list
                   5091: #                        of keyword=value.
                   5092: #   $client  - Socket open on the client.
                   5093: #  Returns:
                   5094: #    1   - Continue processing.
                   5095: #  Side effects:
                   5096: #     reply is written to $client.
                   5097: #
                   5098: sub put_id_handler {
                   5099:     my ($cmd,$tail,$client) = @_;
                   5100: 
                   5101: 
                   5102:     my $userinput = "$cmd:$tail";
                   5103: 
                   5104:     my ($udom,$what)=split(/:/,$tail);
                   5105:     chomp($what);
                   5106:     my @pairs=split(/\&/,$what);
                   5107:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   5108: 				   "P", $what);
                   5109:     if ($hashref) {
                   5110: 	foreach my $pair (@pairs) {
                   5111: 	    my ($key,$value)=split(/=/,$pair);
                   5112: 	    $hashref->{$key}=$value;
                   5113: 	}
1.311     albertel 5114: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     5115: 	    &Reply($client, "ok\n", $userinput);
                   5116: 	} else {
                   5117: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5118: 		     "while attempting idput\n", $userinput);
                   5119: 	}
                   5120:     } else {
                   5121: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5122: 		  "while attempting idput\n", $userinput);
                   5123:     }
                   5124: 
                   5125:     return 1;
                   5126: }
1.263     albertel 5127: &register_handler("idput", \&put_id_handler, 0, 1, 0);
1.238     foxr     5128: 
                   5129: #
                   5130: #  Retrieves a set of id values from the id database.
                   5131: #  Returns an & separated list of results, one for each requested id to the
                   5132: #  client.
                   5133: #
                   5134: # Parameters:
                   5135: #   $cmd       - Command keyword that caused us to be dispatched.
                   5136: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5137: #               domain - the domain whose id table we dump
                   5138: #               ids      Consists of an & separated list of
                   5139: #                        id keywords whose values will be fetched.
                   5140: #                        nonexisting keywords will have an empty value.
                   5141: #   $client    - Socket open on the client.
                   5142: #
                   5143: # Returns:
                   5144: #    1 - indicating processing should continue.
                   5145: # Side effects:
                   5146: #   An & separated list of results is written to $client.
                   5147: #
                   5148: sub get_id_handler {
                   5149:     my ($cmd, $tail, $client) = @_;
                   5150: 
                   5151:     
                   5152:     my $userinput = "$client:$tail";
                   5153:     
                   5154:     my ($udom,$what)=split(/:/,$tail);
                   5155:     chomp($what);
                   5156:     my @queries=split(/\&/,$what);
                   5157:     my $qresult='';
                   5158:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
                   5159:     if ($hashref) {
                   5160: 	for (my $i=0;$i<=$#queries;$i++) {
                   5161: 	    $qresult.="$hashref->{$queries[$i]}&";
                   5162: 	}
1.311     albertel 5163: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     5164: 	    $qresult=~s/\&$//;
1.387     albertel 5165: 	    &Reply($client, \$qresult, $userinput);
1.238     foxr     5166: 	} else {
                   5167: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5168: 		      "while attempting idget\n",$userinput);
                   5169: 	}
                   5170:     } else {
                   5171: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5172: 		 "while attempting idget\n",$userinput);
                   5173:     }
                   5174:     
                   5175:     return 1;
                   5176: }
1.263     albertel 5177: &register_handler("idget", \&get_id_handler, 0, 1, 0);
1.238     foxr     5178: 
1.501     raeburn  5179: #   Deletes one or more ids in a domain's id database.
                   5180: #
                   5181: #   Parameters:
                   5182: #       $cmd                  - Command keyword (iddel).
                   5183: #       $tail                 - Command tail.  In this case a colon
                   5184: #                               separated list containing:
                   5185: #                               The domain for which we are deleting the id(s).
                   5186: #                               &-separated list of id(s) to delete.
                   5187: #       $client               - File open on client socket.
                   5188: # Returns:
                   5189: #     1   - Continue processing
                   5190: #     0   - Exit server.
                   5191: #     
                   5192: #
                   5193: 
                   5194: sub del_id_handler {
                   5195:     my ($cmd,$tail,$client) = @_;
                   5196: 
                   5197:     my $userinput = "$cmd:$tail";
                   5198: 
                   5199:     my ($udom,$what)=split(/:/,$tail);
                   5200:     chomp($what);
                   5201:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   5202:                                    "D", $what);
                   5203:     if ($hashref) {
                   5204:         my @keys=split(/\&/,$what);
                   5205:         foreach my $key (@keys) {
                   5206:             delete($hashref->{$key});
                   5207:         }
                   5208:         if (&untie_user_hash($hashref)) {
                   5209:             &Reply($client, "ok\n", $userinput);
                   5210:         } else {
                   5211:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5212:                     "while attempting iddel\n", $userinput);
                   5213:         }
                   5214:     } else {
                   5215:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5216:                  "while attempting iddel\n", $userinput);
                   5217:     }
                   5218:     return 1;
                   5219: }
                   5220: &register_handler("iddel", \&del_id_handler, 0, 1, 0);
                   5221: 
1.238     foxr     5222: #
1.299     raeburn  5223: # Puts broadcast e-mail sent by Domain Coordinator in nohist_dcmail database 
                   5224: #
                   5225: # Parameters
                   5226: #   $cmd       - Command keyword that caused us to be dispatched.
                   5227: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5228: #               domain - the domain whose dcmail we are recording
                   5229: #               email    Consists of key=value pair 
                   5230: #                        where key is unique msgid
                   5231: #                        and value is message (in XML)
                   5232: #   $client    - Socket open on the client.
                   5233: #
                   5234: # Returns:
                   5235: #    1 - indicating processing should continue.
                   5236: # Side effects
                   5237: #     reply is written to $client.
                   5238: #
                   5239: sub put_dcmail_handler {
                   5240:     my ($cmd,$tail,$client) = @_;
                   5241:     my $userinput = "$cmd:$tail";
1.463     foxr     5242: 
                   5243: 
1.299     raeburn  5244:     my ($udom,$what)=split(/:/,$tail);
                   5245:     chomp($what);
                   5246:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   5247:     if ($hashref) {
                   5248:         my ($key,$value)=split(/=/,$what);
                   5249:         $hashref->{$key}=$value;
                   5250:     }
1.311     albertel 5251:     if (&untie_domain_hash($hashref)) {
1.299     raeburn  5252:         &Reply($client, "ok\n", $userinput);
                   5253:     } else {
                   5254:         &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5255:                  "while attempting dcmailput\n", $userinput);
                   5256:     }
                   5257:     return 1;
                   5258: }
                   5259: &register_handler("dcmailput", \&put_dcmail_handler, 0, 1, 0);
                   5260: 
                   5261: #
                   5262: # Retrieves broadcast e-mail from nohist_dcmail database
                   5263: # Returns to client an & separated list of key=value pairs,
                   5264: # where key is msgid and value is message information.
                   5265: #
                   5266: # Parameters
                   5267: #   $cmd       - Command keyword that caused us to be dispatched.
                   5268: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5269: #               domain - the domain whose dcmail table we dump
                   5270: #               startfilter - beginning of time window 
                   5271: #               endfilter - end of time window
                   5272: #               sendersfilter - & separated list of username:domain 
                   5273: #                 for senders to search for.
                   5274: #   $client    - Socket open on the client.
                   5275: #
                   5276: # Returns:
                   5277: #    1 - indicating processing should continue.
                   5278: # Side effects
                   5279: #     reply (& separated list of msgid=messageinfo pairs) is 
                   5280: #     written to $client.
                   5281: #
                   5282: sub dump_dcmail_handler {
                   5283:     my ($cmd, $tail, $client) = @_;
                   5284:                                                                                 
                   5285:     my $userinput = "$cmd:$tail";
                   5286:     my ($udom,$startfilter,$endfilter,$sendersfilter) = split(/:/,$tail);
                   5287:     chomp($sendersfilter);
                   5288:     my @senders = ();
                   5289:     if (defined($startfilter)) {
                   5290:         $startfilter=&unescape($startfilter);
                   5291:     } else {
                   5292:         $startfilter='.';
                   5293:     }
                   5294:     if (defined($endfilter)) {
                   5295:         $endfilter=&unescape($endfilter);
                   5296:     } else {
                   5297:         $endfilter='.';
                   5298:     }
                   5299:     if (defined($sendersfilter)) {
                   5300:         $sendersfilter=&unescape($sendersfilter);
1.300     albertel 5301: 	@senders = map { &unescape($_) } split(/\&/,$sendersfilter);
1.299     raeburn  5302:     }
                   5303: 
                   5304:     my $qresult='';
                   5305:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   5306:     if ($hashref) {
                   5307:         while (my ($key,$value) = each(%$hashref)) {
                   5308:             my $match = 1;
1.303     albertel 5309:             my ($timestamp,$subj,$uname,$udom) = 
                   5310: 		split(/:/,&unescape(&unescape($key)),5); # yes, twice really
1.299     raeburn  5311:             $subj = &unescape($subj);
                   5312:             unless ($startfilter eq '.' || !defined($startfilter)) {
                   5313:                 if ($timestamp < $startfilter) {
                   5314:                     $match = 0;
                   5315:                 }
                   5316:             }
                   5317:             unless ($endfilter eq '.' || !defined($endfilter)) {
                   5318:                 if ($timestamp > $endfilter) {
                   5319:                     $match = 0;
                   5320:                 }
                   5321:             }
                   5322:             unless (@senders < 1) {
                   5323:                 unless (grep/^$uname:$udom$/,@senders) {
                   5324:                     $match = 0;
                   5325:                 }
                   5326:             }
                   5327:             if ($match == 1) {
                   5328:                 $qresult.=$key.'='.$value.'&';
                   5329:             }
                   5330:         }
1.311     albertel 5331:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5332:             chop($qresult);
1.387     albertel 5333:             &Reply($client, \$qresult, $userinput);
1.299     raeburn  5334:         } else {
                   5335:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5336:                     "while attempting dcmaildump\n", $userinput);
                   5337:         }
                   5338:     } else {
                   5339:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5340:                 "while attempting dcmaildump\n", $userinput);
                   5341:     }
                   5342:     return 1;
                   5343: }
                   5344: 
                   5345: &register_handler("dcmaildump", \&dump_dcmail_handler, 0, 1, 0);
                   5346: 
                   5347: #
                   5348: # Puts domain roles in nohist_domainroles database
                   5349: #
                   5350: # Parameters
                   5351: #   $cmd       - Command keyword that caused us to be dispatched.
                   5352: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5353: #               domain - the domain whose roles we are recording  
                   5354: #               role -   Consists of key=value pair
                   5355: #                        where key is unique role
                   5356: #                        and value is start/end date information
                   5357: #   $client    - Socket open on the client.
                   5358: #
                   5359: # Returns:
                   5360: #    1 - indicating processing should continue.
                   5361: # Side effects
                   5362: #     reply is written to $client.
                   5363: #
                   5364: 
                   5365: sub put_domainroles_handler {
                   5366:     my ($cmd,$tail,$client) = @_;
                   5367: 
                   5368:     my $userinput = "$cmd:$tail";
                   5369:     my ($udom,$what)=split(/:/,$tail);
                   5370:     chomp($what);
                   5371:     my @pairs=split(/\&/,$what);
                   5372:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   5373:     if ($hashref) {
                   5374:         foreach my $pair (@pairs) {
                   5375:             my ($key,$value)=split(/=/,$pair);
                   5376:             $hashref->{$key}=$value;
                   5377:         }
1.311     albertel 5378:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5379:             &Reply($client, "ok\n", $userinput);
                   5380:         } else {
                   5381:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5382:                      "while attempting domroleput\n", $userinput);
                   5383:         }
                   5384:     } else {
                   5385:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5386:                   "while attempting domroleput\n", $userinput);
                   5387:     }
                   5388:                                                                                   
                   5389:     return 1;
                   5390: }
                   5391: 
                   5392: &register_handler("domroleput", \&put_domainroles_handler, 0, 1, 0);
                   5393: 
                   5394: #
                   5395: # Retrieves domain roles from nohist_domainroles database
                   5396: # Returns to client an & separated list of key=value pairs,
                   5397: # where key is role and value is start and end date information.
                   5398: #
                   5399: # Parameters
                   5400: #   $cmd       - Command keyword that caused us to be dispatched.
                   5401: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5402: #               domain - the domain whose domain roles table we dump
                   5403: #   $client    - Socket open on the client.
                   5404: #
                   5405: # Returns:
                   5406: #    1 - indicating processing should continue.
                   5407: # Side effects
                   5408: #     reply (& separated list of role=start/end info pairs) is
                   5409: #     written to $client.
                   5410: #
                   5411: sub dump_domainroles_handler {
                   5412:     my ($cmd, $tail, $client) = @_;
                   5413:                                                                                            
                   5414:     my $userinput = "$cmd:$tail";
                   5415:     my ($udom,$startfilter,$endfilter,$rolesfilter) = split(/:/,$tail);
                   5416:     chomp($rolesfilter);
                   5417:     my @roles = ();
                   5418:     if (defined($startfilter)) {
                   5419:         $startfilter=&unescape($startfilter);
                   5420:     } else {
                   5421:         $startfilter='.';
                   5422:     }
                   5423:     if (defined($endfilter)) {
                   5424:         $endfilter=&unescape($endfilter);
                   5425:     } else {
                   5426:         $endfilter='.';
                   5427:     }
                   5428:     if (defined($rolesfilter)) {
                   5429:         $rolesfilter=&unescape($rolesfilter);
1.300     albertel 5430: 	@roles = split(/\&/,$rolesfilter);
1.299     raeburn  5431:     }
1.421     raeburn  5432: 
1.299     raeburn  5433:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   5434:     if ($hashref) {
                   5435:         my $qresult = '';
                   5436:         while (my ($key,$value) = each(%$hashref)) {
                   5437:             my $match = 1;
1.421     raeburn  5438:             my ($end,$start) = split(/:/,&unescape($value));
1.299     raeburn  5439:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,&unescape($key));
1.421     raeburn  5440:             unless (@roles < 1) {
                   5441:                 unless (grep/^\Q$trole\E$/,@roles) {
                   5442:                     $match = 0;
                   5443:                     next;
                   5444:                 }
                   5445:             }
1.299     raeburn  5446:             unless ($startfilter eq '.' || !defined($startfilter)) {
1.415     raeburn  5447:                 if ((defined($start)) && ($start >= $startfilter)) {
1.299     raeburn  5448:                     $match = 0;
1.421     raeburn  5449:                     next;
1.299     raeburn  5450:                 }
                   5451:             }
                   5452:             unless ($endfilter eq '.' || !defined($endfilter)) {
1.421     raeburn  5453:                 if ((defined($end)) && (($end > 0) && ($end <= $endfilter))) {
1.299     raeburn  5454:                     $match = 0;
1.421     raeburn  5455:                     next;
1.299     raeburn  5456:                 }
                   5457:             }
                   5458:             if ($match == 1) {
                   5459:                 $qresult.=$key.'='.$value.'&';
                   5460:             }
                   5461:         }
1.311     albertel 5462:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5463:             chop($qresult);
1.387     albertel 5464:             &Reply($client, \$qresult, $userinput);
1.299     raeburn  5465:         } else {
                   5466:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5467:                     "while attempting domrolesdump\n", $userinput);
                   5468:         }
                   5469:     } else {
                   5470:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5471:                 "while attempting domrolesdump\n", $userinput);
                   5472:     }
                   5473:     return 1;
                   5474: }
                   5475: 
                   5476: &register_handler("domrolesdump", \&dump_domainroles_handler, 0, 1, 0);
                   5477: 
                   5478: 
1.238     foxr     5479: #  Process the tmpput command I'm not sure what this does.. Seems to
                   5480: #  create a file in the lonDaemons/tmp directory of the form $id.tmp
                   5481: # where Id is the client's ip concatenated with a sequence number.
                   5482: # The file will contain some value that is passed in.  Is this e.g.
                   5483: # a login token?
                   5484: #
                   5485: # Parameters:
                   5486: #    $cmd     - The command that got us dispatched.
                   5487: #    $tail    - The remainder of the request following $cmd:
                   5488: #               In this case this will be the contents of the file.
                   5489: #    $client  - Socket connected to the client.
                   5490: # Returns:
                   5491: #    1 indicating processing can continue.
                   5492: # Side effects:
                   5493: #   A file is created in the local filesystem.
                   5494: #   A reply is sent to the client.
                   5495: sub tmp_put_handler {
                   5496:     my ($cmd, $what, $client) = @_;
                   5497: 
                   5498:     my $userinput = "$cmd:$what";	# Reconstruct for logging.
                   5499: 
1.347     raeburn  5500:     my ($record,$context) = split(/:/,$what);
                   5501:     if ($context ne '') {
                   5502:         chomp($context);
                   5503:         $context = &unescape($context);
                   5504:     }
                   5505:     my ($id,$store);
1.238     foxr     5506:     $tmpsnum++;
1.454     raeburn  5507:     if (($context eq 'resetpw') || ($context eq 'createaccount')) {
1.347     raeburn  5508:         $id = &md5_hex(&md5_hex(time.{}.rand().$$));
                   5509:     } else {
                   5510:         $id = $$.'_'.$clientip.'_'.$tmpsnum;
                   5511:     }
1.238     foxr     5512:     $id=~s/\W/\_/g;
1.347     raeburn  5513:     $record=~s/\n//g;
1.238     foxr     5514:     my $execdir=$perlvar{'lonDaemons'};
                   5515:     if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
1.347     raeburn  5516: 	print $store $record;
1.238     foxr     5517: 	close $store;
1.387     albertel 5518: 	&Reply($client, \$id, $userinput);
1.238     foxr     5519:     } else {
                   5520: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   5521: 		  "while attempting tmpput\n", $userinput);
                   5522:     }
                   5523:     return 1;
                   5524:   
                   5525: }
                   5526: &register_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
1.263     albertel 5527: 
1.238     foxr     5528: #   Processes the tmpget command.  This command returns the contents
                   5529: #  of a temporary resource file(?) created via tmpput.
                   5530: #
                   5531: # Paramters:
                   5532: #    $cmd      - Command that got us dispatched.
                   5533: #    $id       - Tail of the command, contain the id of the resource
                   5534: #                we want to fetch.
                   5535: #    $client   - socket open on the client.
                   5536: # Return:
                   5537: #    1         - Inidcating processing can continue.
                   5538: # Side effects:
                   5539: #   A reply is sent to the client.
                   5540: #
                   5541: sub tmp_get_handler {
                   5542:     my ($cmd, $id, $client) = @_;
                   5543: 
                   5544:     my $userinput = "$cmd:$id"; 
                   5545:     
                   5546: 
                   5547:     $id=~s/\W/\_/g;
                   5548:     my $store;
                   5549:     my $execdir=$perlvar{'lonDaemons'};
                   5550:     if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
                   5551: 	my $reply=<$store>;
1.387     albertel 5552: 	&Reply( $client, \$reply, $userinput);
1.238     foxr     5553: 	close $store;
                   5554:     } else {
                   5555: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   5556: 		  "while attempting tmpget\n", $userinput);
                   5557:     }
                   5558: 
                   5559:     return 1;
                   5560: }
                   5561: &register_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
1.263     albertel 5562: 
1.238     foxr     5563: #
                   5564: #  Process the tmpdel command.  This command deletes a temp resource
                   5565: #  created by the tmpput command.
                   5566: #
                   5567: # Parameters:
                   5568: #   $cmd      - Command that got us here.
                   5569: #   $id       - Id of the temporary resource created.
                   5570: #   $client   - socket open on the client process.
                   5571: #
                   5572: # Returns:
                   5573: #   1     - Indicating processing should continue.
                   5574: # Side Effects:
                   5575: #   A file is deleted
                   5576: #   A reply is sent to the client.
                   5577: sub tmp_del_handler {
                   5578:     my ($cmd, $id, $client) = @_;
                   5579:     
                   5580:     my $userinput= "$cmd:$id";
                   5581:     
                   5582:     chomp($id);
                   5583:     $id=~s/\W/\_/g;
                   5584:     my $execdir=$perlvar{'lonDaemons'};
                   5585:     if (unlink("$execdir/tmp/$id.tmp")) {
                   5586: 	&Reply($client, "ok\n", $userinput);
                   5587:     } else {
                   5588: 	&Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
                   5589: 		  "while attempting tmpdel\n", $userinput);
                   5590:     }
                   5591:     
                   5592:     return 1;
                   5593: 
                   5594: }
                   5595: &register_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
1.263     albertel 5596: 
1.238     foxr     5597: #
1.551     raeburn  5598: #  Process the delbalcookie command. This command deletes a balancer
                   5599: #  cookie in the lonBalancedir directory created by switchserver
                   5600: #
                   5601: # Parameters:
                   5602: #   $cmd      - Command that got us here.
                   5603: #   $cookie   - Cookie to be deleted.
                   5604: #   $client   - socket open on the client process.
                   5605: #
                   5606: # Returns:
                   5607: #   1     - Indicating processing should continue.
                   5608: # Side Effects:
                   5609: #   A cookie file is deleted from the lonBalancedir directory
                   5610: #   A reply is sent to the client.
                   5611: sub del_balcookie_handler {
                   5612:     my ($cmd, $cookie, $client) = @_;
                   5613: 
                   5614:     my $userinput= "$cmd:$cookie";
                   5615: 
                   5616:     chomp($cookie);
                   5617:     my $deleted = '';
                   5618:     if ($cookie =~ /^$LONCAPA::match_domain\_$LONCAPA::match_username\_[a-f0-9]{32}$/) {
                   5619:         my $execdir=$perlvar{'lonBalanceDir'};
                   5620:         if (-e "$execdir/$cookie.id") {
                   5621:             if (open(my $fh,'<',"$execdir/$cookie.id")) {
                   5622:                 my $dodelete;
                   5623:                 while (my $line = <$fh>) {
                   5624:                     chomp($line);
                   5625:                     if ($line eq $clientname) {
                   5626:                         $dodelete = 1;
1.554     raeburn  5627:                         last;
1.551     raeburn  5628:                     }
                   5629:                 }
1.554     raeburn  5630:                 close($fh);
1.551     raeburn  5631:                 if ($dodelete) {
                   5632:                     if (unlink("$execdir/$cookie.id")) {
                   5633:                         $deleted = 1;
                   5634:                     }
                   5635:                 }
                   5636:             }
                   5637:         }
                   5638:     }
                   5639:     if ($deleted) {
                   5640:         &Reply($client, "ok\n", $userinput);
                   5641:     } else {
                   5642:         &Failure( $client, "error: ".($!+0)."Unlinking cookie file Failed ".
                   5643:                   "while attempting delbalcookie\n", $userinput);
                   5644:     }
                   5645:     return 1;
                   5646: }
                   5647: &register_handler("delbalcookie", \&del_balcookie_handler, 0, 1, 0);
                   5648: 
                   5649: #
1.246     foxr     5650: #   Processes the setannounce command.  This command
                   5651: #   creates a file named announce.txt in the top directory of
                   5652: #   the documentn root and sets its contents.  The announce.txt file is
                   5653: #   printed in its entirety at the LonCAPA login page.  Note:
                   5654: #   once the announcement.txt fileis created it cannot be deleted.
                   5655: #   However, setting the contents of the file to empty removes the
                   5656: #   announcement from the login page of loncapa so who cares.
                   5657: #
                   5658: # Parameters:
                   5659: #    $cmd          - The command that got us dispatched.
                   5660: #    $announcement - The text of the announcement.
                   5661: #    $client       - Socket open on the client process.
                   5662: # Retunrns:
                   5663: #   1             - Indicating request processing should continue
                   5664: # Side Effects:
                   5665: #   The file {DocRoot}/announcement.txt is created.
                   5666: #   A reply is sent to $client.
                   5667: #
                   5668: sub set_announce_handler {
                   5669:     my ($cmd, $announcement, $client) = @_;
                   5670:   
                   5671:     my $userinput    = "$cmd:$announcement";
                   5672: 
                   5673:     chomp($announcement);
                   5674:     $announcement=&unescape($announcement);
                   5675:     if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
                   5676: 				'/announcement.txt')) {
                   5677: 	print $store $announcement;
                   5678: 	close $store;
                   5679: 	&Reply($client, "ok\n", $userinput);
                   5680:     } else {
                   5681: 	&Failure($client, "error: ".($!+0)."\n", $userinput);
                   5682:     }
                   5683: 
                   5684:     return 1;
                   5685: }
                   5686: &register_handler("setannounce", \&set_announce_handler, 0, 1, 0);
1.263     albertel 5687: 
1.246     foxr     5688: #
                   5689: #  Return the version of the daemon.  This can be used to determine
                   5690: #  the compatibility of cross version installations or, alternatively to
                   5691: #  simply know who's out of date and who isn't.  Note that the version
                   5692: #  is returned concatenated with the tail.
                   5693: # Parameters:
                   5694: #   $cmd        - the request that dispatched to us.
                   5695: #   $tail       - Tail of the request (client's version?).
                   5696: #   $client     - Socket open on the client.
                   5697: #Returns:
                   5698: #   1 - continue processing requests.
                   5699: # Side Effects:
                   5700: #   Replies with version to $client.
                   5701: sub get_version_handler {
                   5702:     my ($cmd, $tail, $client) = @_;
                   5703: 
                   5704:     my $userinput  = $cmd.$tail;
                   5705:     
                   5706:     &Reply($client, &version($userinput)."\n", $userinput);
                   5707: 
                   5708: 
                   5709:     return 1;
                   5710: }
                   5711: &register_handler("version", \&get_version_handler, 0, 1, 0);
1.263     albertel 5712: 
1.246     foxr     5713: #  Set the current host and domain.  This is used to support
                   5714: #  multihomed systems.  Each IP of the system, or even separate daemons
                   5715: #  on the same IP can be treated as handling a separate lonCAPA virtual
                   5716: #  machine.  This command selects the virtual lonCAPA.  The client always
                   5717: #  knows the right one since it is lonc and it is selecting the domain/system
                   5718: #  from the hosts.tab file.
                   5719: # Parameters:
                   5720: #    $cmd      - Command that dispatched us.
                   5721: #    $tail     - Tail of the command (domain/host requested).
                   5722: #    $socket   - Socket open on the client.
                   5723: #
                   5724: # Returns:
                   5725: #     1   - Indicates the program should continue to process requests.
                   5726: # Side-effects:
                   5727: #     The default domain/system context is modified for this daemon.
                   5728: #     a reply is sent to the client.
                   5729: #
                   5730: sub set_virtual_host_handler {
                   5731:     my ($cmd, $tail, $socket) = @_;
                   5732:   
                   5733:     my $userinput  ="$cmd:$tail";
                   5734: 
                   5735:     &Reply($client, &sethost($userinput)."\n", $userinput);
                   5736: 
                   5737: 
                   5738:     return 1;
                   5739: }
1.247     albertel 5740: &register_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
1.246     foxr     5741: 
                   5742: #  Process a request to exit:
                   5743: #   - "bye" is sent to the client.
                   5744: #   - The client socket is shutdown and closed.
                   5745: #   - We indicate to the caller that we should exit.
                   5746: # Formal Parameters:
                   5747: #   $cmd                - The command that got us here.
                   5748: #   $tail               - Tail of the command (empty).
                   5749: #   $client             - Socket open on the tail.
                   5750: # Returns:
                   5751: #   0      - Indicating the program should exit!!
                   5752: #
                   5753: sub exit_handler {
                   5754:     my ($cmd, $tail, $client) = @_;
                   5755: 
                   5756:     my $userinput = "$cmd:$tail";
                   5757: 
                   5758:     &logthis("Client $clientip ($clientname) hanging up: $userinput");
                   5759:     &Reply($client, "bye\n", $userinput);
                   5760:     $client->shutdown(2);        # shutdown the socket forcibly.
                   5761:     $client->close();
                   5762: 
                   5763:     return 0;
                   5764: }
1.248     foxr     5765: &register_handler("exit", \&exit_handler, 0,1,1);
                   5766: &register_handler("init", \&exit_handler, 0,1,1);
                   5767: &register_handler("quit", \&exit_handler, 0,1,1);
                   5768: 
                   5769: #  Determine if auto-enrollment is enabled.
                   5770: #  Note that the original had what I believe to be a defect.
                   5771: #  The original returned 0 if the requestor was not a registerd client.
                   5772: #  It should return "refused".
                   5773: # Formal Parameters:
                   5774: #   $cmd       - The command that invoked us.
                   5775: #   $tail      - The tail of the command (Extra command parameters.
                   5776: #   $client    - The socket open on the client that issued the request.
                   5777: # Returns:
                   5778: #    1         - Indicating processing should continue.
                   5779: #
                   5780: sub enrollment_enabled_handler {
                   5781:     my ($cmd, $tail, $client) = @_;
                   5782:     my $userinput = $cmd.":".$tail; # For logging purposes.
                   5783: 
                   5784:     
1.337     albertel 5785:     my ($cdom) = split(/:/, $tail, 2);   # Domain we're asking about.
                   5786: 
1.248     foxr     5787:     my $outcome  = &localenroll::run($cdom);
1.387     albertel 5788:     &Reply($client, \$outcome, $userinput);
1.248     foxr     5789: 
                   5790:     return 1;
                   5791: }
                   5792: &register_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
                   5793: 
1.417     raeburn  5794: #
1.423     raeburn  5795: #   Validate an institutional code used for a LON-CAPA course.          
1.417     raeburn  5796: #
                   5797: # Formal Parameters:
                   5798: #   $cmd          - The command request that got us dispatched.
                   5799: #   $tail         - The tail of the command.  In this case,
                   5800: #                   this is a colon separated set of words that will be split
                   5801: #                   into:
1.424     raeburn  5802: #                        $dom      - The domain for which the check of 
                   5803: #                                    institutional course code will occur.
                   5804: #
                   5805: #                        $instcode - The institutional code for the course
                   5806: #                                    being requested, or validated for rights
                   5807: #                                    to request.
                   5808: #
                   5809: #                        $owner    - The course requestor (who will be the
                   5810: #                                    course owner, in the form username:domain
                   5811: #
1.417     raeburn  5812: #   $client       - Socket open on the client.
                   5813: # Returns:
                   5814: #    1           - Indicating processing should continue.
                   5815: #
                   5816: sub validate_instcode_handler {
                   5817:     my ($cmd, $tail, $client) = @_;
                   5818:     my $userinput = "$cmd:$tail";
1.423     raeburn  5819:     my ($dom,$instcode,$owner) = split(/:/, $tail);
1.422     raeburn  5820:     $instcode = &unescape($instcode);
                   5821:     $owner = &unescape($owner);
1.498     raeburn  5822:     my ($outcome,$description,$credits) = 
1.426     raeburn  5823:         &localenroll::validate_instcode($dom,$instcode,$owner);
1.498     raeburn  5824:     my $result = &escape($outcome).'&'.&escape($description).'&'.
                   5825:                  &escape($credits);
1.426     raeburn  5826:     &Reply($client, \$result, $userinput);
1.417     raeburn  5827: 
                   5828:     return 1;
                   5829: }
                   5830: &register_handler("autovalidateinstcode", \&validate_instcode_handler, 0, 1, 0);
                   5831: 
1.248     foxr     5832: #   Get the official sections for which auto-enrollment is possible.
                   5833: #   Since the admin people won't know about 'unofficial sections' 
                   5834: #   we cannot auto-enroll on them.
                   5835: # Formal Parameters:
                   5836: #    $cmd     - The command request that got us dispatched here.
                   5837: #    $tail    - The remainder of the request.  In our case this
                   5838: #               will be split into:
                   5839: #               $coursecode   - The course name from the admin point of view.
                   5840: #               $cdom         - The course's domain(?).
                   5841: #    $client  - Socket open on the client.
                   5842: # Returns:
                   5843: #    1    - Indiciting processing should continue.
                   5844: #
                   5845: sub get_sections_handler {
                   5846:     my ($cmd, $tail, $client) = @_;
                   5847:     my $userinput = "$cmd:$tail";
                   5848: 
                   5849:     my ($coursecode, $cdom) = split(/:/, $tail);
                   5850:     my @secs = &localenroll::get_sections($coursecode,$cdom);
                   5851:     my $seclist = &escape(join(':',@secs));
                   5852: 
1.387     albertel 5853:     &Reply($client, \$seclist, $userinput);
1.248     foxr     5854:     
                   5855: 
                   5856:     return 1;
                   5857: }
                   5858: &register_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
                   5859: 
                   5860: #   Validate the owner of a new course section.  
                   5861: #
                   5862: # Formal Parameters:
                   5863: #   $cmd      - Command that got us dispatched.
                   5864: #   $tail     - the remainder of the command.  For us this consists of a
                   5865: #               colon separated string containing:
                   5866: #                  $inst    - Course Id from the institutions point of view.
                   5867: #                  $owner   - Proposed owner of the course.
                   5868: #                  $cdom    - Domain of the course (from the institutions
                   5869: #                             point of view?)..
                   5870: #   $client   - Socket open on the client.
                   5871: #
                   5872: # Returns:
                   5873: #   1        - Processing should continue.
                   5874: #
                   5875: sub validate_course_owner_handler {
                   5876:     my ($cmd, $tail, $client)  = @_;
                   5877:     my $userinput = "$cmd:$tail";
1.470     raeburn  5878:     my ($inst_course_id, $owner, $cdom, $coowners) = split(/:/, $tail);
                   5879:     
1.336     raeburn  5880:     $owner = &unescape($owner);
1.470     raeburn  5881:     $coowners = &unescape($coowners);
                   5882:     my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom,$coowners);
1.387     albertel 5883:     &Reply($client, \$outcome, $userinput);
1.248     foxr     5884: 
                   5885: 
                   5886: 
                   5887:     return 1;
                   5888: }
                   5889: &register_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
1.263     albertel 5890: 
1.248     foxr     5891: #
                   5892: #   Validate a course section in the official schedule of classes
                   5893: #   from the institutions point of view (part of autoenrollment).
                   5894: #
                   5895: # Formal Parameters:
                   5896: #   $cmd          - The command request that got us dispatched.
                   5897: #   $tail         - The tail of the command.  In this case,
                   5898: #                   this is a colon separated set of words that will be split
                   5899: #                   into:
                   5900: #                        $inst_course_id - The course/section id from the
                   5901: #                                          institutions point of view.
                   5902: #                        $cdom           - The domain from the institutions
                   5903: #                                          point of view.
                   5904: #   $client       - Socket open on the client.
                   5905: # Returns:
                   5906: #    1           - Indicating processing should continue.
                   5907: #
                   5908: sub validate_course_section_handler {
                   5909:     my ($cmd, $tail, $client) = @_;
                   5910:     my $userinput = "$cmd:$tail";
                   5911:     my ($inst_course_id, $cdom) = split(/:/, $tail);
                   5912: 
                   5913:     my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
1.387     albertel 5914:     &Reply($client, \$outcome, $userinput);
1.248     foxr     5915: 
                   5916: 
                   5917:     return 1;
                   5918: }
                   5919: &register_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
                   5920: 
                   5921: #
1.340     raeburn  5922: #   Validate course owner's access to enrollment data for specific class section. 
                   5923: #   
                   5924: #
                   5925: # Formal Parameters:
                   5926: #    $cmd     - The command request that got us dispatched.
                   5927: #    $tail    - The tail of the command.   In this case this is a colon separated
1.542     raeburn  5928: #               set of values that will be split into:
1.340     raeburn  5929: #               $inst_class  - Institutional code for the specific class section   
1.542     raeburn  5930: #               $ownerlist   - An escaped comma-separated list of username:domain 
                   5931: #                              of the course owner, and co-owner(s).
1.340     raeburn  5932: #               $cdom        - The domain of the course from the institution's
                   5933: #                              point of view.
                   5934: #    $client  - The socket open on the client.
                   5935: # Returns:
                   5936: #    1 - continue processing.
                   5937: #
                   5938: 
                   5939: sub validate_class_access_handler {
                   5940:     my ($cmd, $tail, $client) = @_;
                   5941:     my $userinput = "$cmd:$tail";
1.383     raeburn  5942:     my ($inst_class,$ownerlist,$cdom) = split(/:/, $tail);
1.392     raeburn  5943:     my $owners = &unescape($ownerlist);
1.341     albertel 5944:     my $outcome;
                   5945:     eval {
                   5946: 	local($SIG{__DIE__})='DEFAULT';
1.392     raeburn  5947: 	$outcome=&localenroll::check_section($inst_class,$owners,$cdom);
1.341     albertel 5948:     };
1.387     albertel 5949:     &Reply($client,\$outcome, $userinput);
1.340     raeburn  5950: 
                   5951:     return 1;
                   5952: }
                   5953: &register_handler("autovalidateclass_sec", \&validate_class_access_handler, 0, 1, 0);
                   5954: 
                   5955: #
1.542     raeburn  5956: #   Validate course owner or co-owners(s) access to enrollment data for all sections
                   5957: #   and crosslistings for a particular course.
                   5958: #
                   5959: #
                   5960: # Formal Parameters:
                   5961: #    $cmd     - The command request that got us dispatched.
                   5962: #    $tail    - The tail of the command.   In this case this is a colon separated
                   5963: #               set of values that will be split into:
                   5964: #               $ownerlist   - An escaped comma-separated list of username:domain
                   5965: #                              of the course owner, and co-owner(s).
                   5966: #               $cdom        - The domain of the course from the institution's
                   5967: #                              point of view.
                   5968: #               $classes     - Frozen hash of institutional course sections and
                   5969: #                              crosslistings.
                   5970: #    $client  - The socket open on the client.
                   5971: # Returns:
                   5972: #    1 - continue processing.
                   5973: #
                   5974: 
                   5975: sub validate_classes_handler {
                   5976:     my ($cmd, $tail, $client) = @_;
                   5977:     my $userinput = "$cmd:$tail";
                   5978:     my ($ownerlist,$cdom,$classes) = split(/:/, $tail);
                   5979:     my $classesref = &Apache::lonnet::thaw_unescape($classes);
                   5980:     my $owners = &unescape($ownerlist);
                   5981:     my $result;
                   5982:     eval {
                   5983:         local($SIG{__DIE__})='DEFAULT';
                   5984:         my %validations;
                   5985:         my $response = &localenroll::check_instclasses($owners,$cdom,$classesref,
                   5986:                                                        \%validations);
                   5987:         if ($response eq 'ok') {
                   5988:             foreach my $key (keys(%validations)) {
                   5989:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
                   5990:             }
                   5991:             $result =~ s/\&$//;
                   5992:         } else {
                   5993:             $result = 'error';
                   5994:         }
                   5995:     };
                   5996:     if (!$@) {
                   5997:         &Reply($client, \$result, $userinput);
                   5998:     } else {
                   5999:         &Failure($client,"unknown_cmd\n",$userinput);
                   6000:     }
                   6001:     return 1;
                   6002: }
                   6003: &register_handler("autovalidateinstclasses", \&validate_classes_handler, 0, 1, 0);
                   6004: 
                   6005: #
1.340     raeburn  6006: #   Create a password for a new LON-CAPA user added by auto-enrollment.
                   6007: #   Only used for case where authentication method for new user is localauth
1.248     foxr     6008: #
                   6009: # Formal Parameters:
                   6010: #    $cmd     - The command request that got us dispatched.
                   6011: #    $tail    - The tail of the command.   In this case this is a colon separated
                   6012: #               set of words that will be split into:
1.340     raeburn  6013: #               $authparam - An authentication parameter (localauth parameter).
1.248     foxr     6014: #               $cdom      - The domain of the course from the institution's
                   6015: #                            point of view.
                   6016: #    $client  - The socket open on the client.
                   6017: # Returns:
                   6018: #    1 - continue processing.
                   6019: #
                   6020: sub create_auto_enroll_password_handler {
                   6021:     my ($cmd, $tail, $client) = @_;
                   6022:     my $userinput = "$cmd:$tail";
                   6023: 
                   6024:     my ($authparam, $cdom) = split(/:/, $userinput);
                   6025: 
                   6026:     my ($create_passwd,$authchk);
                   6027:     ($authparam,
                   6028:      $create_passwd,
                   6029:      $authchk) = &localenroll::create_password($authparam,$cdom);
                   6030: 
                   6031:     &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
                   6032: 	   $userinput);
                   6033: 
                   6034: 
                   6035:     return 1;
                   6036: }
                   6037: &register_handler("autocreatepassword", \&create_auto_enroll_password_handler, 
                   6038: 		  0, 1, 0);
                   6039: 
1.522     raeburn  6040: sub auto_export_grades_handler {
                   6041:     my ($cmd, $tail, $client) = @_;
                   6042:     my $userinput = "$cmd:$tail";
                   6043:     my ($cdom,$cnum,$info,$data) = split(/:/,$tail);
                   6044:     my $inforef = &Apache::lonnet::thaw_unescape($info);
                   6045:     my $dataref = &Apache::lonnet::thaw_unescape($data);
                   6046:     my ($outcome,$result);;
                   6047:     eval {
                   6048:         local($SIG{__DIE__})='DEFAULT';
                   6049:         my %rtnhash;
                   6050:         $outcome=&localenroll::export_grades($cdom,$cnum,$inforef,$dataref,\%rtnhash);
                   6051:         if ($outcome eq 'ok') {
                   6052:             foreach my $key (keys(%rtnhash)) {
                   6053:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
                   6054:             }
                   6055:             $result =~ s/\&$//;
                   6056:         }
                   6057:     };
                   6058:     if (!$@) {
                   6059:         if ($outcome eq 'ok') {
                   6060:             if ($cipher) {
                   6061:                 my $cmdlength=length($result);
                   6062:                 $result.="         ";
                   6063:                 my $encresult='';
                   6064:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   6065:                     $encresult.= unpack("H16",
                   6066:                                         $cipher->encrypt(substr($result,
                   6067:                                                                 $encidx,
                   6068:                                                                 8)));
                   6069:                 }
                   6070:                 &Reply( $client, "enc:$cmdlength:$encresult\n", $userinput);
                   6071:             } else {
                   6072:                 &Failure( $client, "error:no_key\n", $userinput);
                   6073:             }
                   6074:         } else {
                   6075:             &Reply($client, "$outcome\n", $userinput);
                   6076:         }
                   6077:     } else {
                   6078:         &Failure($client,"export_error\n",$userinput);
                   6079:     }
                   6080:     return 1;
                   6081: }
                   6082: &register_handler("autoexportgrades", \&auto_export_grades_handler,
1.536     raeburn  6083:                   1, 1, 0);
1.522     raeburn  6084: 
1.248     foxr     6085: #   Retrieve and remove temporary files created by/during autoenrollment.
                   6086: #
                   6087: # Formal Parameters:
                   6088: #    $cmd      - The command that got us dispatched.
                   6089: #    $tail     - The tail of the command.  In our case this is a colon 
                   6090: #                separated list that will be split into:
1.526     raeburn  6091: #                $filename - The name of the file to retrieve.
1.248     foxr     6092: #                            The filename is given as a path relative to
                   6093: #                            the LonCAPA temp file directory.
                   6094: #    $client   - Socket open on the client.
                   6095: #
                   6096: # Returns:
                   6097: #   1     - Continue processing.
                   6098: sub retrieve_auto_file_handler {
                   6099:     my ($cmd, $tail, $client)    = @_;
                   6100:     my $userinput                = "cmd:$tail";
                   6101: 
                   6102:     my ($filename)   = split(/:/, $tail);
                   6103: 
                   6104:     my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
1.521     raeburn  6105: 
                   6106:     if ($filename =~m{/\.\./}) {
                   6107:         &Failure($client, "refused\n", $userinput);
1.526     raeburn  6108:     } elsif ($filename !~ /^$LONCAPA::match_domain\_$LONCAPA::match_courseid\_.+_classlist\.xml$/) {
                   6109:         &Failure($client, "refused\n", $userinput);
1.521     raeburn  6110:     } elsif ( (-e $source) && ($filename ne '') ) {
1.248     foxr     6111: 	my $reply = '';
                   6112: 	if (open(my $fh,$source)) {
                   6113: 	    while (<$fh>) {
                   6114: 		chomp($_);
                   6115: 		$_ =~ s/^\s+//g;
                   6116: 		$_ =~ s/\s+$//g;
                   6117: 		$reply .= $_;
                   6118: 	    }
                   6119: 	    close($fh);
                   6120: 	    &Reply($client, &escape($reply)."\n", $userinput);
                   6121: 
                   6122: #   Does this have to be uncommented??!?  (RF).
                   6123: #
                   6124: #                                unlink($source);
                   6125: 	} else {
                   6126: 	    &Failure($client, "error\n", $userinput);
                   6127: 	}
                   6128:     } else {
                   6129: 	&Failure($client, "error\n", $userinput);
                   6130:     }
                   6131:     
                   6132: 
                   6133:     return 1;
                   6134: }
                   6135: &register_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
                   6136: 
1.423     raeburn  6137: sub crsreq_checks_handler {
                   6138:     my ($cmd, $tail, $client) = @_;
                   6139:     my $userinput = "$cmd:$tail";
                   6140:     my $dom = $tail;
                   6141:     my $result;
1.519     raeburn  6142:     my @reqtypes = ('official','unofficial','community','textbook','placement');
1.423     raeburn  6143:     eval {
                   6144:         local($SIG{__DIE__})='DEFAULT';
                   6145:         my %validations;
1.424     raeburn  6146:         my $response = &localenroll::crsreq_checks($dom,\@reqtypes,
                   6147:                                                    \%validations);
1.423     raeburn  6148:         if ($response eq 'ok') { 
                   6149:             foreach my $key (keys(%validations)) {
                   6150:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
                   6151:             }
                   6152:             $result =~ s/\&$//;
                   6153:         } else {
                   6154:             $result = 'error';
                   6155:         }
                   6156:     };
                   6157:     if (!$@) {
                   6158:         &Reply($client, \$result, $userinput);
                   6159:     } else {
                   6160:         &Failure($client,"unknown_cmd\n",$userinput);
                   6161:     }
                   6162:     return 1;
                   6163: }
                   6164: &register_handler("autocrsreqchecks", \&crsreq_checks_handler, 0, 1, 0);
                   6165: 
                   6166: sub validate_crsreq_handler {
                   6167:     my ($cmd, $tail, $client) = @_;
                   6168:     my $userinput = "$cmd:$tail";
1.508     raeburn  6169:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$customdata) = split(/:/, $tail);
1.423     raeburn  6170:     $instcode = &unescape($instcode);
                   6171:     $owner = &unescape($owner);
                   6172:     $crstype = &unescape($crstype);
                   6173:     $inststatuslist = &unescape($inststatuslist);
                   6174:     $instcode = &unescape($instcode);
                   6175:     $instseclist = &unescape($instseclist);
1.508     raeburn  6176:     my $custominfo = &Apache::lonnet::thaw_unescape($customdata);
1.423     raeburn  6177:     my $outcome;
                   6178:     eval {
                   6179:         local($SIG{__DIE__})='DEFAULT';
                   6180:         $outcome = &localenroll::validate_crsreq($dom,$owner,$crstype,
                   6181:                                                  $inststatuslist,$instcode,
1.508     raeburn  6182:                                                  $instseclist,$custominfo);
1.423     raeburn  6183:     };
                   6184:     if (!$@) {
                   6185:         &Reply($client, \$outcome, $userinput);
                   6186:     } else {
                   6187:         &Failure($client,"unknown_cmd\n",$userinput);
                   6188:     }
                   6189:     return 1;
                   6190: }
                   6191: &register_handler("autocrsreqvalidation", \&validate_crsreq_handler, 0, 1, 0);
                   6192: 
1.506     raeburn  6193: sub crsreq_update_handler {
                   6194:     my ($cmd, $tail, $client) = @_;
                   6195:     my $userinput = "$cmd:$tail";
1.509     raeburn  6196:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,$code,
                   6197:         $accessstart,$accessend,$infohashref) =
1.506     raeburn  6198:         split(/:/, $tail);
                   6199:     $crstype = &unescape($crstype);
                   6200:     $action = &unescape($action);
                   6201:     $ownername = &unescape($ownername);
                   6202:     $ownerdomain = &unescape($ownerdomain);
                   6203:     $fullname = &unescape($fullname);
                   6204:     $title = &unescape($title);
                   6205:     $code = &unescape($code);
1.509     raeburn  6206:     $accessstart = &unescape($accessstart);
                   6207:     $accessend = &unescape($accessend);
1.506     raeburn  6208:     my $incoming = &Apache::lonnet::thaw_unescape($infohashref);
                   6209:     my ($result,$outcome);
                   6210:     eval {
                   6211:         local($SIG{__DIE__})='DEFAULT';
                   6212:         my %rtnhash;
                   6213:         $outcome = &localenroll::crsreq_updates($cdom,$cnum,$crstype,$action,
                   6214:                                                 $ownername,$ownerdomain,$fullname,
1.509     raeburn  6215:                                                 $title,$code,$accessstart,$accessend,
                   6216:                                                 $incoming,\%rtnhash);
1.506     raeburn  6217:         if ($outcome eq 'ok') {
1.515     raeburn  6218:             my @posskeys = qw(createdweb createdmsg createdcustomized createdactions queuedweb queuedmsg formitems reviewweb validationjs onload javascript);
1.506     raeburn  6219:             foreach my $key (keys(%rtnhash)) {
                   6220:                 if (grep(/^\Q$key\E/,@posskeys)) {
                   6221:                     $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
                   6222:                 }
                   6223:             }
                   6224:             $result =~ s/\&$//;
                   6225:         }
                   6226:     };
                   6227:     if (!$@) {
                   6228:         if ($outcome eq 'ok') {
                   6229:             &Reply($client, \$result, $userinput);
                   6230:         } else {
                   6231:             &Reply($client, "format_error\n", $userinput);
                   6232:         }
                   6233:     } else {
                   6234:         &Failure($client,"unknown_cmd\n",$userinput);
                   6235:     }
                   6236:     return 1;
                   6237: }
                   6238: &register_handler("autocrsrequpdate", \&crsreq_update_handler, 0, 1, 0);
                   6239: 
1.248     foxr     6240: #
                   6241: #   Read and retrieve institutional code format (for support form).
                   6242: # Formal Parameters:
                   6243: #    $cmd        - Command that dispatched us.
                   6244: #    $tail       - Tail of the command.  In this case it conatins 
                   6245: #                  the course domain and the coursename.
                   6246: #    $client     - Socket open on the client.
                   6247: # Returns:
                   6248: #    1     - Continue processing.
                   6249: #
                   6250: sub get_institutional_code_format_handler {
                   6251:     my ($cmd, $tail, $client)   = @_;
                   6252:     my $userinput               = "$cmd:$tail";
                   6253: 
                   6254:     my $reply;
                   6255:     my($cdom,$course) = split(/:/,$tail);
                   6256:     my @pairs = split/\&/,$course;
                   6257:     my %instcodes = ();
                   6258:     my %codes = ();
                   6259:     my @codetitles = ();
                   6260:     my %cat_titles = ();
                   6261:     my %cat_order = ();
                   6262:     foreach (@pairs) {
                   6263: 	my ($key,$value) = split/=/,$_;
                   6264: 	$instcodes{&unescape($key)} = &unescape($value);
                   6265:     }
                   6266:     my $formatreply = &localenroll::instcode_format($cdom,
                   6267: 						    \%instcodes,
                   6268: 						    \%codes,
                   6269: 						    \@codetitles,
                   6270: 						    \%cat_titles,
                   6271: 						    \%cat_order);
                   6272:     if ($formatreply eq 'ok') {
1.365     albertel 6273: 	my $codes_str = &Apache::lonnet::hash2str(%codes);
                   6274: 	my $codetitles_str = &Apache::lonnet::array2str(@codetitles);
                   6275: 	my $cat_titles_str = &Apache::lonnet::hash2str(%cat_titles);
                   6276: 	my $cat_order_str = &Apache::lonnet::hash2str(%cat_order);
1.248     foxr     6277: 	&Reply($client,
                   6278: 	       $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
                   6279: 	       .$cat_order_str."\n",
                   6280: 	       $userinput);
                   6281:     } else {
                   6282: 	# this else branch added by RF since if not ok, lonc will
                   6283: 	# hang waiting on reply until timeout.
                   6284: 	#
                   6285: 	&Reply($client, "format_error\n", $userinput);
                   6286:     }
                   6287:     
                   6288:     return 1;
                   6289: }
1.265     albertel 6290: &register_handler("autoinstcodeformat",
                   6291: 		  \&get_institutional_code_format_handler,0,1,0);
1.246     foxr     6292: 
1.345     raeburn  6293: sub get_institutional_defaults_handler {
                   6294:     my ($cmd, $tail, $client)   = @_;
                   6295:     my $userinput               = "$cmd:$tail";
                   6296: 
                   6297:     my $dom = $tail;
                   6298:     my %defaults_hash;
                   6299:     my @code_order;
                   6300:     my $outcome;
                   6301:     eval {
                   6302:         local($SIG{__DIE__})='DEFAULT';
                   6303:         $outcome = &localenroll::instcode_defaults($dom,\%defaults_hash,
                   6304:                                                    \@code_order);
                   6305:     };
                   6306:     if (!$@) {
                   6307:         if ($outcome eq 'ok') {
                   6308:             my $result='';
                   6309:             while (my ($key,$value) = each(%defaults_hash)) {
                   6310:                 $result.=&escape($key).'='.&escape($value).'&';
                   6311:             }
                   6312:             $result .= 'code_order='.&escape(join('&',@code_order));
1.387     albertel 6313:             &Reply($client,\$result,$userinput);
1.345     raeburn  6314:         } else {
                   6315:             &Reply($client,"error\n", $userinput);
                   6316:         }
                   6317:     } else {
                   6318:         &Failure($client,"unknown_cmd\n",$userinput);
                   6319:     }
                   6320: }
                   6321: &register_handler("autoinstcodedefaults",
                   6322:                   \&get_institutional_defaults_handler,0,1,0);
                   6323: 
1.416     raeburn  6324: sub get_possible_instcodes_handler {
                   6325:     my ($cmd, $tail, $client)   = @_;
                   6326:     my $userinput               = "$cmd:$tail";
                   6327: 
                   6328:     my $reply;
                   6329:     my $cdom = $tail;
1.417     raeburn  6330:     my (@codetitles,%cat_titles,%cat_order,@code_order);
1.416     raeburn  6331:     my $formatreply = &localenroll::possible_instcodes($cdom,
                   6332:                                                        \@codetitles,
                   6333:                                                        \%cat_titles,
1.417     raeburn  6334:                                                        \%cat_order,
                   6335:                                                        \@code_order);
1.416     raeburn  6336:     if ($formatreply eq 'ok') {
                   6337:         my $result = join('&',map {&escape($_);} (@codetitles)).':';
1.417     raeburn  6338:         $result .= join('&',map {&escape($_);} (@code_order)).':';
1.416     raeburn  6339:         foreach my $key (keys(%cat_titles)) {
                   6340:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_titles{$key}).'&';
                   6341:         }
                   6342:         $result =~ s/\&$//;
                   6343:         $result .= ':';
                   6344:         foreach my $key (keys(%cat_order)) {
                   6345:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_order{$key}).'&';
                   6346:         }
                   6347:         $result =~ s/\&$//;
                   6348:         &Reply($client,\$result,$userinput);
                   6349:     } else {
                   6350:         &Reply($client, "format_error\n", $userinput);
                   6351:     }
                   6352:     return 1;
                   6353: }
                   6354: &register_handler("autopossibleinstcodes",
                   6355:                   \&get_possible_instcodes_handler,0,1,0);
                   6356: 
1.381     raeburn  6357: sub get_institutional_user_rules {
                   6358:     my ($cmd, $tail, $client)   = @_;
                   6359:     my $userinput               = "$cmd:$tail";
                   6360:     my $dom = &unescape($tail);
                   6361:     my (%rules_hash,@rules_order);
                   6362:     my $outcome;
                   6363:     eval {
                   6364:         local($SIG{__DIE__})='DEFAULT';
                   6365:         $outcome = &localenroll::username_rules($dom,\%rules_hash,\@rules_order);
                   6366:     };
                   6367:     if (!$@) {
                   6368:         if ($outcome eq 'ok') {
                   6369:             my $result;
                   6370:             foreach my $key (keys(%rules_hash)) {
                   6371:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6372:             }
                   6373:             $result =~ s/\&$//;
                   6374:             $result .= ':';
                   6375:             if (@rules_order > 0) {
                   6376:                 foreach my $item (@rules_order) {
                   6377:                     $result .= &escape($item).'&';
                   6378:                 }
                   6379:             }
                   6380:             $result =~ s/\&$//;
1.387     albertel 6381:             &Reply($client,\$result,$userinput);
1.381     raeburn  6382:         } else {
                   6383:             &Reply($client,"error\n", $userinput);
                   6384:         }
                   6385:     } else {
                   6386:         &Failure($client,"unknown_cmd\n",$userinput);
                   6387:     }
                   6388: }
                   6389: &register_handler("instuserrules",\&get_institutional_user_rules,0,1,0);
                   6390: 
1.389     raeburn  6391: sub get_institutional_id_rules {
                   6392:     my ($cmd, $tail, $client)   = @_;
                   6393:     my $userinput               = "$cmd:$tail";
                   6394:     my $dom = &unescape($tail);
                   6395:     my (%rules_hash,@rules_order);
                   6396:     my $outcome;
                   6397:     eval {
                   6398:         local($SIG{__DIE__})='DEFAULT';
                   6399:         $outcome = &localenroll::id_rules($dom,\%rules_hash,\@rules_order);
                   6400:     };
                   6401:     if (!$@) {
                   6402:         if ($outcome eq 'ok') {
                   6403:             my $result;
                   6404:             foreach my $key (keys(%rules_hash)) {
                   6405:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6406:             }
                   6407:             $result =~ s/\&$//;
                   6408:             $result .= ':';
                   6409:             if (@rules_order > 0) {
                   6410:                 foreach my $item (@rules_order) {
                   6411:                     $result .= &escape($item).'&';
                   6412:                 }
                   6413:             }
                   6414:             $result =~ s/\&$//;
                   6415:             &Reply($client,\$result,$userinput);
                   6416:         } else {
                   6417:             &Reply($client,"error\n", $userinput);
                   6418:         }
                   6419:     } else {
                   6420:         &Failure($client,"unknown_cmd\n",$userinput);
                   6421:     }
                   6422: }
                   6423: &register_handler("instidrules",\&get_institutional_id_rules,0,1,0);
                   6424: 
1.397     raeburn  6425: sub get_institutional_selfcreate_rules {
1.396     raeburn  6426:     my ($cmd, $tail, $client)   = @_;
                   6427:     my $userinput               = "$cmd:$tail";
                   6428:     my $dom = &unescape($tail);
                   6429:     my (%rules_hash,@rules_order);
                   6430:     my $outcome;
                   6431:     eval {
                   6432:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  6433:         $outcome = &localenroll::selfcreate_rules($dom,\%rules_hash,\@rules_order);
1.396     raeburn  6434:     };
                   6435:     if (!$@) {
                   6436:         if ($outcome eq 'ok') {
                   6437:             my $result;
                   6438:             foreach my $key (keys(%rules_hash)) {
                   6439:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6440:             }
                   6441:             $result =~ s/\&$//;
                   6442:             $result .= ':';
                   6443:             if (@rules_order > 0) {
                   6444:                 foreach my $item (@rules_order) {
                   6445:                     $result .= &escape($item).'&';
                   6446:                 }
                   6447:             }
                   6448:             $result =~ s/\&$//;
                   6449:             &Reply($client,\$result,$userinput);
                   6450:         } else {
                   6451:             &Reply($client,"error\n", $userinput);
                   6452:         }
                   6453:     } else {
                   6454:         &Failure($client,"unknown_cmd\n",$userinput);
                   6455:     }
                   6456: }
1.397     raeburn  6457: &register_handler("instemailrules",\&get_institutional_selfcreate_rules,0,1,0);
1.396     raeburn  6458: 
1.381     raeburn  6459: 
                   6460: sub institutional_username_check {
                   6461:     my ($cmd, $tail, $client)   = @_;
                   6462:     my $userinput               = "$cmd:$tail";
                   6463:     my %rulecheck;
                   6464:     my $outcome;
                   6465:     my ($udom,$uname,@rules) = split(/:/,$tail);
                   6466:     $udom = &unescape($udom);
                   6467:     $uname = &unescape($uname);
                   6468:     @rules = map {&unescape($_);} (@rules);
                   6469:     eval {
                   6470:         local($SIG{__DIE__})='DEFAULT';
                   6471:         $outcome = &localenroll::username_check($udom,$uname,\@rules,\%rulecheck);
                   6472:     };
                   6473:     if (!$@) {
                   6474:         if ($outcome eq 'ok') {
                   6475:             my $result='';
                   6476:             foreach my $key (keys(%rulecheck)) {
                   6477:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6478:             }
1.387     albertel 6479:             &Reply($client,\$result,$userinput);
1.381     raeburn  6480:         } else {
                   6481:             &Reply($client,"error\n", $userinput);
                   6482:         }
                   6483:     } else {
                   6484:         &Failure($client,"unknown_cmd\n",$userinput);
                   6485:     }
                   6486: }
                   6487: &register_handler("instrulecheck",\&institutional_username_check,0,1,0);
                   6488: 
1.389     raeburn  6489: sub institutional_id_check {
                   6490:     my ($cmd, $tail, $client)   = @_;
                   6491:     my $userinput               = "$cmd:$tail";
                   6492:     my %rulecheck;
                   6493:     my $outcome;
                   6494:     my ($udom,$id,@rules) = split(/:/,$tail);
                   6495:     $udom = &unescape($udom);
                   6496:     $id = &unescape($id);
                   6497:     @rules = map {&unescape($_);} (@rules);
                   6498:     eval {
                   6499:         local($SIG{__DIE__})='DEFAULT';
                   6500:         $outcome = &localenroll::id_check($udom,$id,\@rules,\%rulecheck);
                   6501:     };
                   6502:     if (!$@) {
                   6503:         if ($outcome eq 'ok') {
                   6504:             my $result='';
                   6505:             foreach my $key (keys(%rulecheck)) {
                   6506:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6507:             }
                   6508:             &Reply($client,\$result,$userinput);
                   6509:         } else {
                   6510:             &Reply($client,"error\n", $userinput);
                   6511:         }
                   6512:     } else {
                   6513:         &Failure($client,"unknown_cmd\n",$userinput);
                   6514:     }
                   6515: }
                   6516: &register_handler("instidrulecheck",\&institutional_id_check,0,1,0);
1.345     raeburn  6517: 
1.397     raeburn  6518: sub institutional_selfcreate_check {
1.396     raeburn  6519:     my ($cmd, $tail, $client)   = @_;
                   6520:     my $userinput               = "$cmd:$tail";
                   6521:     my %rulecheck;
                   6522:     my $outcome;
                   6523:     my ($udom,$email,@rules) = split(/:/,$tail);
                   6524:     $udom = &unescape($udom);
                   6525:     $email = &unescape($email);
                   6526:     @rules = map {&unescape($_);} (@rules);
                   6527:     eval {
                   6528:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  6529:         $outcome = &localenroll::selfcreate_check($udom,$email,\@rules,\%rulecheck);
1.396     raeburn  6530:     };
                   6531:     if (!$@) {
                   6532:         if ($outcome eq 'ok') {
                   6533:             my $result='';
                   6534:             foreach my $key (keys(%rulecheck)) {
                   6535:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6536:             }
                   6537:             &Reply($client,\$result,$userinput);
                   6538:         } else {
                   6539:             &Reply($client,"error\n", $userinput);
                   6540:         }
                   6541:     } else {
                   6542:         &Failure($client,"unknown_cmd\n",$userinput);
                   6543:     }
                   6544: }
1.397     raeburn  6545: &register_handler("instselfcreatecheck",\&institutional_selfcreate_check,0,1,0);
1.396     raeburn  6546: 
1.317     raeburn  6547: # Get domain specific conditions for import of student photographs to a course
                   6548: #
                   6549: # Retrieves information from photo_permission subroutine in localenroll.
                   6550: # Returns outcome (ok) if no processing errors, and whether course owner is 
                   6551: # required to accept conditions of use (yes/no).
                   6552: #
                   6553: #    
                   6554: sub photo_permission_handler {
                   6555:     my ($cmd, $tail, $client)   = @_;
                   6556:     my $userinput               = "$cmd:$tail";
                   6557:     my $cdom = $tail;
                   6558:     my ($perm_reqd,$conditions);
1.320     albertel 6559:     my $outcome;
                   6560:     eval {
                   6561: 	local($SIG{__DIE__})='DEFAULT';
                   6562: 	$outcome = &localenroll::photo_permission($cdom,\$perm_reqd,
                   6563: 						  \$conditions);
                   6564:     };
                   6565:     if (!$@) {
                   6566: 	&Reply($client, &escape($outcome.':'.$perm_reqd.':'. $conditions)."\n",
                   6567: 	       $userinput);
                   6568:     } else {
                   6569: 	&Failure($client,"unknown_cmd\n",$userinput);
                   6570:     }
                   6571:     return 1;
1.317     raeburn  6572: }
                   6573: &register_handler("autophotopermission",\&photo_permission_handler,0,1,0);
                   6574: 
                   6575: #
                   6576: # Checks if student photo is available for a user in the domain, in the user's
                   6577: # directory (in /userfiles/internal/studentphoto.jpg).
                   6578: # Uses localstudentphoto:fetch() to ensure there is an up to date copy of
                   6579: # the student's photo.   
                   6580: 
                   6581: sub photo_check_handler {
                   6582:     my ($cmd, $tail, $client)   = @_;
                   6583:     my $userinput               = "$cmd:$tail";
                   6584:     my ($udom,$uname,$pid) = split(/:/,$tail);
                   6585:     $udom = &unescape($udom);
                   6586:     $uname = &unescape($uname);
                   6587:     $pid = &unescape($pid);
                   6588:     my $path=&propath($udom,$uname).'/userfiles/internal/';
                   6589:     if (!-e $path) {
                   6590:         &mkpath($path);
                   6591:     }
                   6592:     my $response;
                   6593:     my $result = &localstudentphoto::fetch($udom,$uname,$pid,\$response);
                   6594:     $result .= ':'.$response;
                   6595:     &Reply($client, &escape($result)."\n",$userinput);
1.320     albertel 6596:     return 1;
1.317     raeburn  6597: }
                   6598: &register_handler("autophotocheck",\&photo_check_handler,0,1,0);
                   6599: 
                   6600: #
                   6601: # Retrieve information from localenroll about whether to provide a button     
                   6602: # for users who have enbled import of student photos to initiate an 
                   6603: # update of photo files for registered students. Also include 
                   6604: # comment to display alongside button.  
                   6605: 
                   6606: sub photo_choice_handler {
                   6607:     my ($cmd, $tail, $client) = @_;
                   6608:     my $userinput             = "$cmd:$tail";
                   6609:     my $cdom                  = &unescape($tail);
1.320     albertel 6610:     my ($update,$comment);
                   6611:     eval {
                   6612: 	local($SIG{__DIE__})='DEFAULT';
                   6613: 	($update,$comment)    = &localenroll::manager_photo_update($cdom);
                   6614:     };
                   6615:     if (!$@) {
                   6616: 	&Reply($client,&escape($update).':'.&escape($comment)."\n",$userinput);
                   6617:     } else {
                   6618: 	&Failure($client,"unknown_cmd\n",$userinput);
                   6619:     }
                   6620:     return 1;
1.317     raeburn  6621: }
                   6622: &register_handler("autophotochoice",\&photo_choice_handler,0,1,0);
                   6623: 
1.265     albertel 6624: #
                   6625: # Gets a student's photo to exist (in the correct image type) in the user's 
                   6626: # directory.
                   6627: # Formal Parameters:
                   6628: #    $cmd     - The command request that got us dispatched.
                   6629: #    $tail    - A colon separated set of words that will be split into:
                   6630: #               $domain - student's domain
                   6631: #               $uname  - student username
                   6632: #               $type   - image type desired
                   6633: #    $client  - The socket open on the client.
                   6634: # Returns:
                   6635: #    1 - continue processing.
1.317     raeburn  6636: 
1.265     albertel 6637: sub student_photo_handler {
                   6638:     my ($cmd, $tail, $client) = @_;
1.317     raeburn  6639:     my ($domain,$uname,$ext,$type) = split(/:/, $tail);
1.265     albertel 6640: 
1.317     raeburn  6641:     my $path=&propath($domain,$uname). '/userfiles/internal/';
                   6642:     my $filename = 'studentphoto.'.$ext;
                   6643:     if ($type eq 'thumbnail') {
                   6644:         $filename = 'studentphoto_tn.'.$ext;
                   6645:     }
                   6646:     if (-e $path.$filename) {
1.265     albertel 6647: 	&Reply($client,"ok\n","$cmd:$tail");
                   6648: 	return 1;
                   6649:     }
                   6650:     &mkpath($path);
1.317     raeburn  6651:     my $file;
                   6652:     if ($type eq 'thumbnail') {
1.320     albertel 6653: 	eval {
                   6654: 	    local($SIG{__DIE__})='DEFAULT';
                   6655: 	    $file=&localstudentphoto::fetch_thumbnail($domain,$uname);
                   6656: 	};
1.317     raeburn  6657:     } else {
                   6658:         $file=&localstudentphoto::fetch($domain,$uname);
                   6659:     }
1.265     albertel 6660:     if (!$file) {
                   6661: 	&Failure($client,"unavailable\n","$cmd:$tail");
                   6662: 	return 1;
                   6663:     }
1.317     raeburn  6664:     if (!-e $path.$filename) { &convert_photo($file,$path.$filename); }
                   6665:     if (-e $path.$filename) {
1.265     albertel 6666: 	&Reply($client,"ok\n","$cmd:$tail");
                   6667: 	return 1;
                   6668:     }
                   6669:     &Failure($client,"unable_to_convert\n","$cmd:$tail");
                   6670:     return 1;
                   6671: }
                   6672: &register_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
1.246     foxr     6673: 
1.361     raeburn  6674: sub inst_usertypes_handler {
                   6675:     my ($cmd, $domain, $client) = @_;
                   6676:     my $res;
                   6677:     my $userinput = $cmd.":".$domain; # For logging purposes.
1.370     albertel 6678:     my (%typeshash,@order,$result);
                   6679:     eval {
                   6680: 	local($SIG{__DIE__})='DEFAULT';
                   6681: 	$result=&localenroll::inst_usertypes($domain,\%typeshash,\@order);
                   6682:     };
                   6683:     if ($result eq 'ok') {
1.361     raeburn  6684:         if (keys(%typeshash) > 0) {
                   6685:             foreach my $key (keys(%typeshash)) {
                   6686:                 $res.=&escape($key).'='.&escape($typeshash{$key}).'&';
                   6687:             }
                   6688:         }
                   6689:         $res=~s/\&$//;
                   6690:         $res .= ':';
                   6691:         if (@order > 0) {
                   6692:             foreach my $item (@order) {
                   6693:                 $res .= &escape($item).'&';
                   6694:             }
                   6695:         }
                   6696:         $res=~s/\&$//;
                   6697:     }
1.387     albertel 6698:     &Reply($client, \$res, $userinput);
1.361     raeburn  6699:     return 1;
                   6700: }
                   6701: &register_handler("inst_usertypes", \&inst_usertypes_handler, 0, 1, 0);
                   6702: 
1.264     albertel 6703: # mkpath makes all directories for a file, expects an absolute path with a
                   6704: # file or a trailing / if just a dir is passed
                   6705: # returns 1 on success 0 on failure
                   6706: sub mkpath {
                   6707:     my ($file)=@_;
                   6708:     my @parts=split(/\//,$file,-1);
                   6709:     my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
                   6710:     for (my $i=3;$i<= ($#parts-1);$i++) {
1.265     albertel 6711: 	$now.='/'.$parts[$i]; 
1.264     albertel 6712: 	if (!-e $now) {
                   6713: 	    if  (!mkdir($now,0770)) { return 0; }
                   6714: 	}
                   6715:     }
                   6716:     return 1;
                   6717: }
                   6718: 
1.207     foxr     6719: #---------------------------------------------------------------
                   6720: #
                   6721: #   Getting, decoding and dispatching requests:
                   6722: #
                   6723: #
                   6724: #   Get a Request:
                   6725: #   Gets a Request message from the client.  The transaction
                   6726: #   is defined as a 'line' of text.  We remove the new line
                   6727: #   from the text line.  
1.226     foxr     6728: #
1.211     albertel 6729: sub get_request {
1.207     foxr     6730:     my $input = <$client>;
                   6731:     chomp($input);
1.226     foxr     6732: 
1.234     foxr     6733:     &Debug("get_request: Request = $input\n");
1.207     foxr     6734: 
                   6735:     &status('Processing '.$clientname.':'.$input);
                   6736: 
                   6737:     return $input;
                   6738: }
1.212     foxr     6739: #---------------------------------------------------------------
                   6740: #
                   6741: #  Process a request.  This sub should shrink as each action
                   6742: #  gets farmed out into a separat sub that is registered 
                   6743: #  with the dispatch hash.  
                   6744: #
                   6745: # Parameters:
                   6746: #    user_input   - The request received from the client (lonc).
1.525     raeburn  6747: #
1.212     foxr     6748: # Returns:
                   6749: #    true to keep processing, false if caller should exit.
                   6750: #
                   6751: sub process_request {
1.525     raeburn  6752:     my ($userinput) = @_; # Easier for now to break style than to
                   6753:                           # fix all the userinput -> user_input.
1.212     foxr     6754:     my $wasenc    = 0;		# True if request was encrypted.
                   6755: # ------------------------------------------------------------ See if encrypted
1.322     albertel 6756:     # for command
                   6757:     # sethost:<server>
                   6758:     # <command>:<args>
                   6759:     #   we just send it to the processor
                   6760:     # for
                   6761:     # sethost:<server>:<command>:<args>
                   6762:     #  we do the implict set host and then do the command
                   6763:     if ($userinput =~ /^sethost:/) {
                   6764: 	(my $cmd,my $newid,$userinput) = split(':',$userinput,3);
                   6765: 	if (defined($userinput)) {
                   6766: 	    &sethost("$cmd:$newid");
                   6767: 	} else {
                   6768: 	    $userinput = "$cmd:$newid";
                   6769: 	}
                   6770:     }
                   6771: 
1.212     foxr     6772:     if ($userinput =~ /^enc/) {
                   6773: 	$userinput = decipher($userinput);
                   6774: 	$wasenc=1;
                   6775: 	if(!$userinput) {	# Cipher not defined.
1.251     foxr     6776: 	    &Failure($client, "error: Encrypted data without negotated key\n");
1.212     foxr     6777: 	    return 0;
                   6778: 	}
                   6779:     }
                   6780:     Debug("process_request: $userinput\n");
                   6781:     
1.213     foxr     6782:     #  
                   6783:     #   The 'correct way' to add a command to lond is now to
                   6784:     #   write a sub to execute it and Add it to the command dispatch
                   6785:     #   hash via a call to register_handler..  The comments to that
                   6786:     #   sub should give you enough to go on to show how to do this
                   6787:     #   along with the examples that are building up as this code
                   6788:     #   is getting refactored.   Until all branches of the
                   6789:     #   if/elseif monster below have been factored out into
                   6790:     #   separate procesor subs, if the dispatch hash is missing
                   6791:     #   the command keyword, we will fall through to the remainder
                   6792:     #   of the if/else chain below in order to keep this thing in 
                   6793:     #   working order throughout the transmogrification.
                   6794: 
                   6795:     my ($command, $tail) = split(/:/, $userinput, 2);
                   6796:     chomp($command);
                   6797:     chomp($tail);
                   6798:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
1.214     foxr     6799:     $command =~ s/(\r)//;	# And this too for parameterless commands.
                   6800:     if(!$tail) {
                   6801: 	$tail ="";		# defined but blank.
                   6802:     }
1.213     foxr     6803: 
                   6804:     &Debug("Command received: $command, encoded = $wasenc");
                   6805: 
                   6806:     if(defined $Dispatcher{$command}) {
                   6807: 
                   6808: 	my $dispatch_info = $Dispatcher{$command};
                   6809: 	my $handler       = $$dispatch_info[0];
                   6810: 	my $need_encode   = $$dispatch_info[1];
                   6811: 	my $client_types  = $$dispatch_info[2];
                   6812: 	Debug("Matched dispatch hash: mustencode: $need_encode "
                   6813: 	      ."ClientType $client_types");
                   6814:       
                   6815: 	#  Validate the request:
                   6816:       
                   6817: 	my $ok = 1;
                   6818: 	my $requesterprivs = 0;
                   6819: 	if(&isClient()) {
                   6820: 	    $requesterprivs |= $CLIENT_OK;
                   6821: 	}
                   6822: 	if(&isManager()) {
                   6823: 	    $requesterprivs |= $MANAGER_OK;
                   6824: 	}
                   6825: 	if($need_encode && (!$wasenc)) {
                   6826: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
                   6827: 	    $ok = 0;
                   6828: 	}
                   6829: 	if(($client_types & $requesterprivs) == 0) {
                   6830: 	    Debug("Client not privileged to do this operation");
                   6831: 	    $ok = 0;
                   6832: 	}
1.525     raeburn  6833:         if ($ok) {
1.535     raeburn  6834:             my $realcommand = $command;
                   6835:             if ($command eq 'querysend') {
                   6836:                 my ($query,$rest)=split(/\:/,$tail,2);
                   6837:                 $query=~s/\n*$//g;
                   6838:                 my @possqueries = 
                   6839:                     qw(userlog courselog fetchenrollment institutionalphotos usersearch instdirsearch getinstuser getmultinstusers);
                   6840:                 if (grep(/^\Q$query\E$/,@possqueries)) {
                   6841:                     $command .= '_'.$query;
                   6842:                 } elsif ($query eq 'prepare activity log') {
                   6843:                     $command .= '_activitylog';
                   6844:                 }
                   6845:             }
1.525     raeburn  6846:             if (ref($trust{$command}) eq 'HASH') {
                   6847:                 my $donechecks;
                   6848:                 if ($trust{$command}{'anywhere'}) {
                   6849:                    $donechecks = 1;
                   6850:                 } elsif ($trust{$command}{'manageronly'}) {
                   6851:                     unless (&isManager()) {
                   6852:                         $ok = 0;
                   6853:                     }
                   6854:                     $donechecks = 1;
                   6855:                 } elsif ($trust{$command}{'institutiononly'}) {
                   6856:                     unless ($clientsameinst) {
                   6857:                         $ok = 0;
                   6858:                     }
                   6859:                     $donechecks = 1;
                   6860:                 } elsif ($clientsameinst) {
                   6861:                     $donechecks = 1;
                   6862:                 }
                   6863:                 unless ($donechecks) {
                   6864:                     foreach my $rule (keys(%{$trust{$command}})) {
                   6865:                         next if ($rule eq 'remote');
                   6866:                         if ($trust{$command}{$rule}) {
                   6867:                             if ($clientprohibited{$rule}) {
                   6868:                                 $ok = 0;
                   6869:                             } else {
                   6870:                                 $ok = 1;
                   6871:                                 $donechecks = 1;
                   6872:                                 last;
                   6873:                             }
                   6874:                         }
                   6875:                     }
                   6876:                 }
                   6877:                 unless ($donechecks) {
                   6878:                     if ($trust{$command}{'remote'}) {
                   6879:                         if ($clientremoteok) {
                   6880:                             $ok = 1;
                   6881:                         } else {
                   6882:                             $ok = 0;
                   6883:                         } 
                   6884:                     }
                   6885:                 }
                   6886:             }
1.535     raeburn  6887:             $command = $realcommand;
1.525     raeburn  6888:         }
1.213     foxr     6889: 
                   6890: 	if($ok) {
                   6891: 	    Debug("Dispatching to handler $command $tail");
                   6892: 	    my $keep_going = &$handler($command, $tail, $client);
                   6893: 	    return $keep_going;
                   6894: 	} else {
                   6895: 	    Debug("Refusing to dispatch because client did not match requirements");
                   6896: 	    Failure($client, "refused\n", $userinput);
                   6897: 	    return 1;
                   6898: 	}
1.525     raeburn  6899:     }
1.213     foxr     6900: 
1.262     foxr     6901:     print $client "unknown_cmd\n";
1.212     foxr     6902: # -------------------------------------------------------------------- complete
                   6903:     Debug("process_request - returning 1");
                   6904:     return 1;
                   6905: }
1.207     foxr     6906: #
                   6907: #   Decipher encoded traffic
                   6908: #  Parameters:
                   6909: #     input      - Encoded data.
                   6910: #  Returns:
                   6911: #     Decoded data or undef if encryption key was not yet negotiated.
                   6912: #  Implicit input:
                   6913: #     cipher  - This global holds the negotiated encryption key.
                   6914: #
1.211     albertel 6915: sub decipher {
1.207     foxr     6916:     my ($input)  = @_;
                   6917:     my $output = '';
1.212     foxr     6918:     
                   6919:     
1.207     foxr     6920:     if($cipher) {
                   6921: 	my($enc, $enclength, $encinput) = split(/:/, $input);
                   6922: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
                   6923: 	    $output .= 
                   6924: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
                   6925: 	}
                   6926: 	return substr($output, 0, $enclength);
                   6927:     } else {
                   6928: 	return undef;
                   6929:     }
                   6930: }
                   6931: 
                   6932: #
                   6933: #   Register a command processor.  This function is invoked to register a sub
                   6934: #   to process a request.  Once registered, the ProcessRequest sub can automatically
                   6935: #   dispatch requests to an appropriate sub, and do the top level validity checking
                   6936: #   as well:
                   6937: #    - Is the keyword recognized.
                   6938: #    - Is the proper client type attempting the request.
                   6939: #    - Is the request encrypted if it has to be.
                   6940: #   Parameters:
                   6941: #    $request_name         - Name of the request being registered.
                   6942: #                           This is the command request that will match
                   6943: #                           against the hash keywords to lookup the information
                   6944: #                           associated with the dispatch information.
                   6945: #    $procedure           - Reference to a sub to call to process the request.
                   6946: #                           All subs get called as follows:
                   6947: #                             Procedure($cmd, $tail, $replyfd, $key)
                   6948: #                             $cmd    - the actual keyword that invoked us.
                   6949: #                             $tail   - the tail of the request that invoked us.
                   6950: #                             $replyfd- File descriptor connected to the client
                   6951: #    $must_encode          - True if the request must be encoded to be good.
                   6952: #    $client_ok            - True if it's ok for a client to request this.
                   6953: #    $manager_ok           - True if it's ok for a manager to request this.
                   6954: # Side effects:
                   6955: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
                   6956: #      - On failure, the program will die as it's a bad internal bug to try to 
                   6957: #        register a duplicate command handler.
                   6958: #
1.211     albertel 6959: sub register_handler {
1.212     foxr     6960:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
1.207     foxr     6961: 
                   6962:     #  Don't allow duplication#
                   6963:    
                   6964:     if (defined $Dispatcher{$request_name}) {
                   6965: 	die "Attempting to define a duplicate request handler for $request_name\n";
                   6966:     }
                   6967:     #   Build the client type mask:
                   6968:     
                   6969:     my $client_type_mask = 0;
                   6970:     if($client_ok) {
                   6971: 	$client_type_mask  |= $CLIENT_OK;
                   6972:     }
                   6973:     if($manager_ok) {
                   6974: 	$client_type_mask  |= $MANAGER_OK;
                   6975:     }
                   6976:    
                   6977:     #  Enter the hash:
                   6978:       
                   6979:     my @entry = ($procedure, $must_encode, $client_type_mask);
                   6980:    
                   6981:     $Dispatcher{$request_name} = \@entry;
                   6982:    
                   6983: }
                   6984: 
                   6985: 
                   6986: #------------------------------------------------------------------
                   6987: 
                   6988: 
                   6989: 
                   6990: 
1.141     foxr     6991: #
1.96      foxr     6992: #  Convert an error return code from lcpasswd to a string value.
                   6993: #
                   6994: sub lcpasswdstrerror {
                   6995:     my $ErrorCode = shift;
1.97      foxr     6996:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96      foxr     6997: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
                   6998:     } else {
1.98      foxr     6999: 	return $passwderrors[$ErrorCode];
1.96      foxr     7000:     }
                   7001: }
                   7002: 
1.23      harris41 7003: # grabs exception and records it to log before exiting
                   7004: sub catchexception {
1.27      albertel 7005:     my ($error)=@_;
1.25      www      7006:     $SIG{'QUIT'}='DEFAULT';
                   7007:     $SIG{__DIE__}='DEFAULT';
1.165     albertel 7008:     &status("Catching exception");
1.190     albertel 7009:     &logthis("<font color='red'>CRITICAL: "
1.373     albertel 7010:      ."ABNORMAL EXIT. Child $$ for server ".$perlvar{'lonHostID'}." died through "
1.27      albertel 7011:      ."a crash with this error msg->[$error]</font>");
1.57      www      7012:     &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27      albertel 7013:     if ($client) { print $client "error: $error\n"; }
1.59      www      7014:     $server->close();
1.27      albertel 7015:     die($error);
1.23      harris41 7016: }
1.63      www      7017: sub timeout {
1.165     albertel 7018:     &status("Handling Timeout");
1.190     albertel 7019:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
1.63      www      7020:     &catchexception('Timeout');
                   7021: }
1.22      harris41 7022: # -------------------------------- Set signal handlers to record abnormal exits
                   7023: 
1.226     foxr     7024: 
1.22      harris41 7025: $SIG{'QUIT'}=\&catchexception;
                   7026: $SIG{__DIE__}=\&catchexception;
                   7027: 
1.81      matthew  7028: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95      harris41 7029: &status("Read loncapa.conf and loncapa_apache.conf");
                   7030: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141     foxr     7031: %perlvar=%{$perlvarref};
1.80      harris41 7032: undef $perlvarref;
1.19      www      7033: 
1.35      harris41 7034: # ----------------------------- Make sure this process is running from user=www
                   7035: my $wwwid=getpwnam('www');
                   7036: if ($wwwid!=$<) {
1.134     albertel 7037:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   7038:    my $subj="LON: $currenthostid User ID mismatch";
1.550     raeburn  7039:    system("echo 'User ID mismatch.  lond must be run as user www.' |".
                   7040:           " mail -s '$subj' $emailto > /dev/null");
1.35      harris41 7041:    exit 1;
                   7042: }
                   7043: 
1.19      www      7044: # --------------------------------------------- Check if other instance running
                   7045: 
                   7046: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
                   7047: 
                   7048: if (-e $pidfile) {
                   7049:    my $lfh=IO::File->new("$pidfile");
                   7050:    my $pide=<$lfh>;
                   7051:    chomp($pide);
1.29      harris41 7052:    if (kill 0 => $pide) { die "already running"; }
1.19      www      7053: }
1.1       albertel 7054: 
                   7055: # ------------------------------------------------------------- Read hosts file
                   7056: 
                   7057: 
                   7058: 
                   7059: # establish SERVER socket, bind and listen.
                   7060: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
                   7061:                                 Type      => SOCK_STREAM,
                   7062:                                 Proto     => 'tcp',
1.469     foxr     7063:                                 ReuseAddr     => 1,
1.1       albertel 7064:                                 Listen    => 10 )
1.29      harris41 7065:   or die "making socket: $@\n";
1.1       albertel 7066: 
                   7067: # --------------------------------------------------------- Do global variables
                   7068: 
                   7069: # global variables
                   7070: 
1.134     albertel 7071: my %children               = ();       # keys are current child process IDs
1.1       albertel 7072: 
                   7073: sub REAPER {                        # takes care of dead children
                   7074:     $SIG{CHLD} = \&REAPER;
1.165     albertel 7075:     &status("Handling child death");
1.178     foxr     7076:     my $pid;
                   7077:     do {
                   7078: 	$pid = waitpid(-1,&WNOHANG());
                   7079: 	if (defined($children{$pid})) {
                   7080: 	    &logthis("Child $pid died");
                   7081: 	    delete($children{$pid});
1.183     albertel 7082: 	} elsif ($pid > 0) {
1.178     foxr     7083: 	    &logthis("Unknown Child $pid died");
                   7084: 	}
                   7085:     } while ( $pid > 0 );
                   7086:     foreach my $child (keys(%children)) {
                   7087: 	$pid = waitpid($child,&WNOHANG());
                   7088: 	if ($pid > 0) {
                   7089: 	    &logthis("Child $child - $pid looks like we missed it's death");
                   7090: 	    delete($children{$pid});
                   7091: 	}
1.176     albertel 7092:     }
1.165     albertel 7093:     &status("Finished Handling child death");
1.1       albertel 7094: }
                   7095: 
                   7096: sub HUNTSMAN {                      # signal handler for SIGINT
1.165     albertel 7097:     &status("Killing children (INT)");
1.1       albertel 7098:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
                   7099:     kill 'INT' => keys %children;
1.59      www      7100:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1       albertel 7101:     my $execdir=$perlvar{'lonDaemons'};
                   7102:     unlink("$execdir/logs/lond.pid");
1.190     albertel 7103:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.165     albertel 7104:     &status("Done killing children");
1.1       albertel 7105:     exit;                           # clean up with dignity
                   7106: }
                   7107: 
                   7108: sub HUPSMAN {                      # signal handler for SIGHUP
                   7109:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
1.165     albertel 7110:     &status("Killing children for restart (HUP)");
1.1       albertel 7111:     kill 'INT' => keys %children;
1.59      www      7112:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.190     albertel 7113:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.134     albertel 7114:     my $execdir=$perlvar{'lonDaemons'};
1.30      harris41 7115:     unlink("$execdir/logs/lond.pid");
1.165     albertel 7116:     &status("Restarting self (HUP)");
1.1       albertel 7117:     exec("$execdir/lond");         # here we go again
                   7118: }
                   7119: 
1.144     foxr     7120: #
1.148     foxr     7121: #  Reload the Apache daemon's state.
1.150     foxr     7122: #  This is done by invoking /home/httpd/perl/apachereload
                   7123: #  a setuid perl script that can be root for us to do this job.
1.148     foxr     7124: #
                   7125: sub ReloadApache {
1.473     raeburn  7126: # --------------------------- Handle case of another apachereload process (locking)
1.474     raeburn  7127:     if (&LONCAPA::try_to_lock('/tmp/lock_apachereload')) {
                   7128:         my $execdir = $perlvar{'lonDaemons'};
                   7129:         my $script  = $execdir."/apachereload";
                   7130:         system($script);
                   7131:         unlink('/tmp/lock_apachereload'); #  Remove the lock file.
                   7132:     }
1.148     foxr     7133: }
                   7134: 
                   7135: #
1.144     foxr     7136: #   Called in response to a USR2 signal.
                   7137: #   - Reread hosts.tab
                   7138: #   - All children connected to hosts that were removed from hosts.tab
                   7139: #     are killed via SIGINT
                   7140: #   - All children connected to previously existing hosts are sent SIGUSR1
                   7141: #   - Our internal hosts hash is updated to reflect the new contents of
                   7142: #     hosts.tab causing connections from hosts added to hosts.tab to
                   7143: #     now be honored.
                   7144: #
                   7145: sub UpdateHosts {
1.165     albertel 7146:     &status("Reload hosts.tab");
1.147     foxr     7147:     logthis('<font color="blue"> Updating connections </font>');
1.148     foxr     7148:     #
                   7149:     #  The %children hash has the set of IP's we currently have children
                   7150:     #  on.  These need to be matched against records in the hosts.tab
                   7151:     #  Any ip's no longer in the table get killed off they correspond to
                   7152:     #  either dropped or changed hosts.  Note that the re-read of the table
                   7153:     #  will take care of new and changed hosts as connections come into being.
                   7154: 
1.371     albertel 7155:     &Apache::lonnet::reset_hosts_info();
1.532     raeburn  7156:     my %active;
1.148     foxr     7157: 
1.368     albertel 7158:     foreach my $child (keys(%children)) {
1.148     foxr     7159: 	my $childip = $children{$child};
1.374     albertel 7160: 	if ($childip ne '127.0.0.1'
                   7161: 	    && !defined(&Apache::lonnet::get_hosts_from_ip($childip))) {
1.149     foxr     7162: 	    logthis('<font color="blue"> UpdateHosts killing child '
                   7163: 		    ." $child for ip $childip </font>");
1.148     foxr     7164: 	    kill('INT', $child);
1.149     foxr     7165: 	} else {
1.532     raeburn  7166:             $active{$child} = $childip;
1.149     foxr     7167: 	    logthis('<font color="green"> keeping child for ip '
                   7168: 		    ." $childip (pid=$child) </font>");
1.148     foxr     7169: 	}
                   7170:     }
1.532     raeburn  7171: 
                   7172:     my %oldconf = %secureconf;
                   7173:     my %connchange;
1.555     raeburn  7174:     if (lonssl::Read_Connect_Config(\%secureconf,\%perlvar,\%crlchecked) eq 'ok') {
1.545     raeburn  7175:         logthis('<font color="blue"> Reloaded SSL connection rules and cleared CRL checking history </font>');
1.532     raeburn  7176:     } else {
1.545     raeburn  7177:         logthis('<font color="yellow"> Failed to reload SSL connection rules and clear CRL checking history </font>');
1.532     raeburn  7178:     }
                   7179:     if ((ref($oldconf{'connfrom'}) eq 'HASH') && (ref($secureconf{'connfrom'}) eq 'HASH')) {
                   7180:         foreach my $type ('dom','intdom','other') {
                   7181:             if ((($oldconf{'connfrom'}{$type} eq 'no') && ($secureconf{'connfrom'}{$type} eq 'req')) ||
                   7182:                 (($oldconf{'connfrom'}{$type} eq 'req') && ($secureconf{'connfrom'}{$type} eq 'no'))) {
                   7183:                 $connchange{$type} = 1;
                   7184:             }
                   7185:         }
                   7186:     }
                   7187:     if (keys(%connchange)) {
                   7188:         foreach my $child (keys(%active)) {
                   7189:             my $childip = $active{$child};
                   7190:             if ($childip ne '127.0.0.1') {
                   7191:                 my $childhostname  = gethostbyaddr(Socket::inet_aton($childip),AF_INET);
                   7192:                 if ($childhostname ne '') {
                   7193:                     my $childlonhost = &Apache::lonnet::get_server_homeID($childhostname);
                   7194:                     my ($samedom,$sameinst) = &set_client_info($childlonhost);
                   7195:                     if ($samedom) {
                   7196:                         if ($connchange{'dom'}) {
                   7197:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7198:                                    ." $child for ip $childip </font>");
                   7199:                             kill('INT', $child);
                   7200:                         }
                   7201:                     } elsif ($sameinst) {
                   7202:                         if ($connchange{'intdom'}) {
                   7203:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7204:                                    ." $child for ip $childip </font>");
                   7205:                            kill('INT', $child);
                   7206:                         }
                   7207:                     } else {
                   7208:                         if ($connchange{'other'}) {
                   7209:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7210:                                    ." $child for ip $childip </font>");
                   7211:                             kill('INT', $child);
                   7212:                         }
                   7213:                     }
                   7214:                 }
                   7215:             }
                   7216:         }
                   7217:     }
1.148     foxr     7218:     ReloadApache;
1.165     albertel 7219:     &status("Finished reloading hosts.tab");
1.144     foxr     7220: }
                   7221: 
1.57      www      7222: sub checkchildren {
1.165     albertel 7223:     &status("Checking on the children (sending signals)");
1.57      www      7224:     &initnewstatus();
                   7225:     &logstatus();
                   7226:     &logthis('Going to check on the children');
1.134     albertel 7227:     my $docdir=$perlvar{'lonDocRoot'};
1.61      harris41 7228:     foreach (sort keys %children) {
1.221     albertel 7229: 	#sleep 1;
1.57      www      7230:         unless (kill 'USR1' => $_) {
                   7231: 	    &logthis ('Child '.$_.' is dead');
                   7232:             &logstatus($$.' is dead');
1.221     albertel 7233: 	    delete($children{$_});
1.57      www      7234:         } 
1.61      harris41 7235:     }
1.63      www      7236:     sleep 5;
1.212     foxr     7237:     $SIG{ALRM} = sub { Debug("timeout"); 
                   7238: 		       die "timeout";  };
1.113     albertel 7239:     $SIG{__DIE__} = 'DEFAULT';
1.165     albertel 7240:     &status("Checking on the children (waiting for reports)");
1.63      www      7241:     foreach (sort keys %children) {
                   7242:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113     albertel 7243:           eval {
                   7244:             alarm(300);
1.63      www      7245: 	    &logthis('Child '.$_.' did not respond');
1.67      albertel 7246: 	    kill 9 => $_;
1.131     albertel 7247: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   7248: 	    #$subj="LON: $currenthostid killed lond process $_";
                   7249: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
                   7250: 	    #$execdir=$perlvar{'lonDaemons'};
                   7251: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.221     albertel 7252: 	    delete($children{$_});
1.113     albertel 7253: 	    alarm(0);
                   7254: 	  }
1.63      www      7255:         }
                   7256:     }
1.113     albertel 7257:     $SIG{ALRM} = 'DEFAULT';
1.155     albertel 7258:     $SIG{__DIE__} = \&catchexception;
1.165     albertel 7259:     &status("Finished checking children");
1.221     albertel 7260:     &logthis('Finished Checking children');
1.57      www      7261: }
                   7262: 
1.1       albertel 7263: # --------------------------------------------------------------------- Logging
                   7264: 
                   7265: sub logthis {
                   7266:     my $message=shift;
                   7267:     my $execdir=$perlvar{'lonDaemons'};
                   7268:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
                   7269:     my $now=time;
                   7270:     my $local=localtime($now);
1.58      www      7271:     $lastlog=$local.': '.$message;
1.1       albertel 7272:     print $fh "$local ($$): $message\n";
                   7273: }
                   7274: 
1.77      foxr     7275: # ------------------------- Conditional log if $DEBUG true.
                   7276: sub Debug {
                   7277:     my $message = shift;
                   7278:     if($DEBUG) {
                   7279: 	&logthis($message);
                   7280:     }
                   7281: }
1.161     foxr     7282: 
                   7283: #
                   7284: #   Sub to do replies to client.. this gives a hook for some
                   7285: #   debug tracing too:
                   7286: #  Parameters:
                   7287: #     fd      - File open on client.
                   7288: #     reply   - Text to send to client.
                   7289: #     request - Original request from client.
                   7290: #
1.490     droeschl 7291: #NOTE $reply must be terminated by exactly *one* \n. If $reply is a reference
                   7292: #this is done automatically ($$reply must not contain any \n in this case). 
                   7293: #If $reply is a string the caller has to ensure this.
1.161     foxr     7294: sub Reply {
1.192     foxr     7295:     my ($fd, $reply, $request) = @_;
1.387     albertel 7296:     if (ref($reply)) {
                   7297: 	print $fd $$reply;
                   7298: 	print $fd "\n";
                   7299: 	if ($DEBUG) { Debug("Request was $request  Reply was $$reply"); }
                   7300:     } else {
                   7301: 	print $fd $reply;
                   7302: 	if ($DEBUG) { Debug("Request was $request  Reply was $reply"); }
                   7303:     }
1.212     foxr     7304:     $Transactions++;
                   7305: }
                   7306: 
                   7307: 
                   7308: #
                   7309: #    Sub to report a failure.
                   7310: #    This function:
                   7311: #     -   Increments the failure statistic counters.
                   7312: #     -   Invokes Reply to send the error message to the client.
                   7313: # Parameters:
                   7314: #    fd       - File descriptor open on the client
                   7315: #    reply    - Reply text to emit.
                   7316: #    request  - The original request message (used by Reply
                   7317: #               to debug if that's enabled.
                   7318: # Implicit outputs:
                   7319: #    $Failures- The number of failures is incremented.
                   7320: #    Reply (invoked here) sends a message to the 
                   7321: #    client:
                   7322: #
                   7323: sub Failure {
                   7324:     my $fd      = shift;
                   7325:     my $reply   = shift;
                   7326:     my $request = shift;
                   7327:    
                   7328:     $Failures++;
                   7329:     Reply($fd, $reply, $request);      # That's simple eh?
1.161     foxr     7330: }
1.57      www      7331: # ------------------------------------------------------------------ Log status
                   7332: 
                   7333: sub logstatus {
1.178     foxr     7334:     &status("Doing logging");
                   7335:     my $docdir=$perlvar{'lonDocRoot'};
                   7336:     {
                   7337: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
1.200     matthew  7338:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
1.178     foxr     7339:         $fh->close();
                   7340:     }
1.221     albertel 7341:     &status("Finished $$.txt");
                   7342:     {
                   7343: 	open(LOG,">>$docdir/lon-status/londstatus.txt");
                   7344: 	flock(LOG,LOCK_EX);
                   7345: 	print LOG $$."\t".$clientname."\t".$currenthostid."\t"
                   7346: 	    .$status."\t".$lastlog."\t $keymode\n";
1.275     albertel 7347: 	flock(LOG,LOCK_UN);
1.221     albertel 7348: 	close(LOG);
                   7349:     }
1.178     foxr     7350:     &status("Finished logging");
1.57      www      7351: }
                   7352: 
                   7353: sub initnewstatus {
                   7354:     my $docdir=$perlvar{'lonDocRoot'};
                   7355:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
1.460     foxr     7356:     my $now=time();
1.57      www      7357:     my $local=localtime($now);
                   7358:     print $fh "LOND status $local - parent $$\n\n";
1.64      www      7359:     opendir(DIR,"$docdir/lon-status/londchld");
1.134     albertel 7360:     while (my $filename=readdir(DIR)) {
1.64      www      7361:         unlink("$docdir/lon-status/londchld/$filename");
                   7362:     }
                   7363:     closedir(DIR);
1.57      www      7364: }
                   7365: 
                   7366: # -------------------------------------------------------------- Status setting
                   7367: 
                   7368: sub status {
                   7369:     my $what=shift;
                   7370:     my $now=time;
                   7371:     my $local=localtime($now);
1.178     foxr     7372:     $status=$local.': '.$what;
                   7373:     $0='lond: '.$what.' '.$local;
1.57      www      7374: }
1.11      www      7375: 
1.13      www      7376: # -------------------------------------------------------------- Talk to lonsql
                   7377: 
1.234     foxr     7378: sub sql_reply {
1.12      harris41 7379:     my ($cmd)=@_;
1.234     foxr     7380:     my $answer=&sub_sql_reply($cmd);
                   7381:     if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
1.12      harris41 7382:     return $answer;
                   7383: }
                   7384: 
1.234     foxr     7385: sub sub_sql_reply {
1.12      harris41 7386:     my ($cmd)=@_;
                   7387:     my $unixsock="mysqlsock";
                   7388:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
                   7389:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                   7390:                                       Type    => SOCK_STREAM,
                   7391:                                       Timeout => 10)
                   7392:        or return "con_lost";
1.319     www      7393:     print $sclient "$cmd:$currentdomainid\n";
1.12      harris41 7394:     my $answer=<$sclient>;
                   7395:     chomp($answer);
                   7396:     if (!$answer) { $answer="con_lost"; }
                   7397:     return $answer;
                   7398: }
                   7399: 
1.1       albertel 7400: # --------------------------------------- Is this the home server of an author?
1.11      www      7401: 
1.1       albertel 7402: sub ishome {
                   7403:     my $author=shift;
                   7404:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   7405:     my ($udom,$uname)=split(/\//,$author);
                   7406:     my $proname=propath($udom,$uname);
                   7407:     if (-e $proname) {
                   7408: 	return 'owner';
                   7409:     } else {
                   7410:         return 'not_owner';
                   7411:     }
                   7412: }
                   7413: 
                   7414: # ======================================================= Continue main program
                   7415: # ---------------------------------------------------- Fork once and dissociate
                   7416: 
1.134     albertel 7417: my $fpid=fork;
1.1       albertel 7418: exit if $fpid;
1.29      harris41 7419: die "Couldn't fork: $!" unless defined ($fpid);
1.1       albertel 7420: 
1.29      harris41 7421: POSIX::setsid() or die "Can't start new session: $!";
1.1       albertel 7422: 
                   7423: # ------------------------------------------------------- Write our PID on disk
                   7424: 
1.134     albertel 7425: my $execdir=$perlvar{'lonDaemons'};
1.1       albertel 7426: open (PIDSAVE,">$execdir/logs/lond.pid");
                   7427: print PIDSAVE "$$\n";
                   7428: close(PIDSAVE);
1.190     albertel 7429: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.57      www      7430: &status('Starting');
1.1       albertel 7431: 
1.106     foxr     7432: 
1.1       albertel 7433: 
                   7434: # ----------------------------------------------------- Install signal handlers
                   7435: 
1.57      www      7436: 
1.1       albertel 7437: $SIG{CHLD} = \&REAPER;
                   7438: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   7439: $SIG{HUP}  = \&HUPSMAN;
1.57      www      7440: $SIG{USR1} = \&checkchildren;
1.144     foxr     7441: $SIG{USR2} = \&UpdateHosts;
1.106     foxr     7442: 
1.148     foxr     7443: #  Read the host hashes:
1.368     albertel 7444: &Apache::lonnet::load_hosts_tab();
1.447     raeburn  7445: my %iphost = &Apache::lonnet::get_iphost(1);
1.106     foxr     7446: 
1.480     raeburn  7447: $dist=`$perlvar{'lonDaemons'}/distprobe`;
1.286     albertel 7448: 
1.471     raeburn  7449: my $arch = `uname -i`;
1.475     raeburn  7450: chomp($arch);
1.471     raeburn  7451: if ($arch eq 'unknown') {
                   7452:     $arch = `uname -m`;
1.475     raeburn  7453:     chomp($arch);
1.471     raeburn  7454: }
                   7455: 
1.555     raeburn  7456: unless (lonssl::Read_Connect_Config(\%secureconf,\%perlvar,\%crlchecked) eq 'ok') {
1.532     raeburn  7457:     &logthis('<font color="blue">No connectionrules table. Will fallback to loncapa.conf</font>');
                   7458: }
                   7459: 
1.106     foxr     7460: # --------------------------------------------------------------
                   7461: #   Accept connections.  When a connection comes in, it is validated
                   7462: #   and if good, a child process is created to process transactions
                   7463: #   along the connection.
                   7464: 
1.1       albertel 7465: while (1) {
1.165     albertel 7466:     &status('Starting accept');
1.106     foxr     7467:     $client = $server->accept() or next;
1.165     albertel 7468:     &status('Accepted '.$client.' off to spawn');
1.386     albertel 7469:     make_new_child($client);
1.165     albertel 7470:     &status('Finished spawning');
1.1       albertel 7471: }
                   7472: 
1.212     foxr     7473: sub make_new_child {
                   7474:     my $pid;
                   7475: #    my $cipher;     # Now global
                   7476:     my $sigset;
1.178     foxr     7477: 
1.212     foxr     7478:     $client = shift;
                   7479:     &status('Starting new child '.$client);
                   7480:     &logthis('<font color="green"> Attempting to start child ('.$client.
                   7481: 	     ")</font>");    
                   7482:     # block signal for fork
                   7483:     $sigset = POSIX::SigSet->new(SIGINT);
                   7484:     sigprocmask(SIG_BLOCK, $sigset)
                   7485:         or die "Can't block SIGINT for fork: $!\n";
1.178     foxr     7486: 
1.212     foxr     7487:     die "fork: $!" unless defined ($pid = fork);
1.178     foxr     7488: 
1.212     foxr     7489:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
                   7490: 	                               # connection liveness.
1.178     foxr     7491: 
1.212     foxr     7492:     #
                   7493:     #  Figure out who we're talking to so we can record the peer in 
                   7494:     #  the pid hash.
                   7495:     #
                   7496:     my $caller = getpeername($client);
                   7497:     my ($port,$iaddr);
                   7498:     if (defined($caller) && length($caller) > 0) {
                   7499: 	($port,$iaddr)=unpack_sockaddr_in($caller);
                   7500:     } else {
                   7501: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
                   7502:     }
                   7503:     if (defined($iaddr)) {
                   7504: 	$clientip  = inet_ntoa($iaddr);
                   7505: 	Debug("Connected with $clientip");
                   7506:     } else {
                   7507: 	&logthis("Unable to determine clientip");
                   7508: 	$clientip='Unavailable';
                   7509:     }
                   7510:     
                   7511:     if ($pid) {
                   7512:         # Parent records the child's birth and returns.
                   7513:         sigprocmask(SIG_UNBLOCK, $sigset)
                   7514:             or die "Can't unblock SIGINT for fork: $!\n";
                   7515:         $children{$pid} = $clientip;
                   7516:         &status('Started child '.$pid);
1.462     foxr     7517: 	close($client);
1.212     foxr     7518:         return;
                   7519:     } else {
                   7520:         # Child can *not* return from this subroutine.
                   7521:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
                   7522:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
                   7523:                                 #don't get intercepted
                   7524:         $SIG{USR1}= \&logstatus;
                   7525:         $SIG{ALRM}= \&timeout;
1.468     foxr     7526: 	#
                   7527: 	# Block sigpipe as it gets thrownon socket disconnect and we want to 
                   7528: 	# deal with that as a read faiure instead.
                   7529: 	#
                   7530: 	my $blockset = POSIX::SigSet->new(SIGPIPE);
                   7531: 	sigprocmask(SIG_BLOCK, $blockset);
                   7532: 
1.212     foxr     7533:         $lastlog='Forked ';
                   7534:         $status='Forked';
1.178     foxr     7535: 
1.212     foxr     7536:         # unblock signals
                   7537:         sigprocmask(SIG_UNBLOCK, $sigset)
                   7538:             or die "Can't unblock SIGINT for fork: $!\n";
1.178     foxr     7539: 
1.212     foxr     7540: #        my $tmpsnum=0;            # Now global
                   7541: #---------------------------------------------------- kerberos 5 initialization
                   7542:         &Authen::Krb5::init_context();
1.511     raeburn  7543: 
                   7544:         my $no_ets;
1.559   ! raeburn  7545:         if ($dist =~ /^(?:centos|rhes|scientific|oracle)(\d+)$/) {
1.511     raeburn  7546:             if ($1 >= 7) {
                   7547:                 $no_ets = 1;
                   7548:             }
                   7549:         } elsif ($dist =~ /^suse(\d+\.\d+)$/) {
                   7550:             if (($1 eq '9.3') || ($1 >= 12.2)) {
                   7551:                 $no_ets = 1; 
                   7552:             }
1.514     raeburn  7553:         } elsif ($dist =~ /^sles(\d+)$/) {
                   7554:             if ($1 > 11) {
                   7555:                 $no_ets = 1;
                   7556:             }
1.511     raeburn  7557:         } elsif ($dist =~ /^fedora(\d+)$/) {
                   7558:             if ($1 < 7) {
                   7559:                 $no_ets = 1;
                   7560:             }
                   7561:         }
                   7562:         unless ($no_ets) {
1.286     albertel 7563: 	    &Authen::Krb5::init_ets();
                   7564: 	}
1.209     albertel 7565: 
1.212     foxr     7566: 	&status('Accepted connection');
                   7567: # =============================================================================
                   7568:             # do something with the connection
                   7569: # -----------------------------------------------------------------------------
                   7570: 	# see if we know client and 'check' for spoof IP by ineffective challenge
1.178     foxr     7571: 
1.278     albertel 7572: 	my $outsideip=$clientip;
                   7573: 	if ($clientip eq '127.0.0.1') {
1.368     albertel 7574: 	    $outsideip=&Apache::lonnet::get_host_ip($perlvar{'lonHostID'});
1.278     albertel 7575: 	}
1.412     foxr     7576: 	&ReadManagerTable();
1.368     albertel 7577: 	my $clientrec=defined(&Apache::lonnet::get_hosts_from_ip($outsideip));
1.278     albertel 7578: 	my $ismanager=($managers{$outsideip}    ne undef);
1.432     raeburn  7579: 	$clientname  = "[unknown]";
1.212     foxr     7580: 	if($clientrec) {	# Establish client type.
                   7581: 	    $ConnectionType = "client";
1.368     albertel 7582: 	    $clientname = (&Apache::lonnet::get_hosts_from_ip($outsideip))[-1];
1.212     foxr     7583: 	    if($ismanager) {
                   7584: 		$ConnectionType = "both";
                   7585: 	    }
                   7586: 	} else {
                   7587: 	    $ConnectionType = "manager";
1.278     albertel 7588: 	    $clientname = $managers{$outsideip};
1.212     foxr     7589: 	}
1.556     raeburn  7590: 	my $clientok;
1.178     foxr     7591: 
1.212     foxr     7592: 	if ($clientrec || $ismanager) {
                   7593: 	    &status("Waiting for init from $clientip $clientname");
                   7594: 	    &logthis('<font color="yellow">INFO: Connection, '.
                   7595: 		     $clientip.
                   7596: 		  " ($clientname) connection type = $ConnectionType </font>" );
                   7597: 	    &status("Connecting $clientip  ($clientname))"); 
                   7598: 	    my $remotereq=<$client>;
                   7599: 	    chomp($remotereq);
                   7600: 	    Debug("Got init: $remotereq");
1.337     albertel 7601: 
1.212     foxr     7602: 	    if ($remotereq =~ /^init/) {
                   7603: 		&sethost("sethost:$perlvar{'lonHostID'}");
                   7604: 		#
                   7605: 		#  If the remote is attempting a local init... give that a try:
                   7606: 		#
1.432     raeburn  7607: 		(my $i, my $inittype, $clientversion) = split(/:/, $remotereq);
1.492     droeschl 7608:         # For LON-CAPA 2.9, the  client session will have sent its LON-CAPA
                   7609:         # version when initiating the connection. For LON-CAPA 2.8 and older,
                   7610:         # the version is retrieved from the global %loncaparevs in lonnet.pm.            
1.494     droeschl 7611:         # $clientversion contains path to keyfile if $inittype eq 'local'
                   7612:         # it's overridden below in this case
1.492     droeschl 7613:         $clientversion ||= $Apache::lonnet::loncaparevs{$clientname};
1.209     albertel 7614: 
1.212     foxr     7615: 		# If the connection type is ssl, but I didn't get my
                   7616: 		# certificate files yet, then I'll drop  back to 
                   7617: 		# insecure (if allowed).
1.532     raeburn  7618: 
                   7619:                 if ($inittype eq "ssl") {
                   7620:                     my $context;
                   7621:                     if ($clientsamedom) {
                   7622:                         $context = 'dom';
                   7623:                         if ($secureconf{'connfrom'}{'dom'} eq 'no') {
                   7624:                             $inittype = "";
                   7625:                         }
                   7626:                     } elsif ($clientsameinst) {
                   7627:                         $context = 'intdom';
                   7628:                         if ($secureconf{'connfrom'}{'intdom'} eq 'no') {
                   7629:                             $inittype = "";
                   7630:                         }
                   7631:                     } else {
                   7632:                         $context = 'other';
                   7633:                         if ($secureconf{'connfrom'}{'other'} eq 'no') {
                   7634:                             $inittype = "";
                   7635:                         }
                   7636:                     }
                   7637:                     if ($inittype eq '') {
                   7638:                         &logthis("<font color=\"blue\"> Domain config set "
                   7639:                                 ."to no ssl for $clientname (context: $context)"
                   7640:                                 ." -- trying insecure auth</font>");
                   7641:                     }
                   7642:                 }
                   7643: 
1.212     foxr     7644: 		if($inittype eq "ssl") {
                   7645: 		    my ($ca, $cert) = lonssl::CertificateFile;
                   7646: 		    my $kfile       = lonssl::KeyFile;
                   7647: 		    if((!$ca)   || 
                   7648: 		       (!$cert) || 
                   7649: 		       (!$kfile)) {
                   7650: 			$inittype = ""; # This forces insecure attempt.
                   7651: 			&logthis("<font color=\"blue\"> Certificates not "
                   7652: 				 ."installed -- trying insecure auth</font>");
1.224     foxr     7653: 		    } else {	# SSL certificates are in place so
1.212     foxr     7654: 		    }		# Leave the inittype alone.
                   7655: 		}
                   7656: 
                   7657: 		if($inittype eq "local") {
1.432     raeburn  7658:                     $clientversion = $perlvar{'lonVersion'};
1.212     foxr     7659: 		    my $key = LocalConnection($client, $remotereq);
                   7660: 		    if($key) {
                   7661: 			Debug("Got local key $key");
                   7662: 			$clientok     = 1;
                   7663: 			my $cipherkey = pack("H32", $key);
                   7664: 			$cipher       = new IDEA($cipherkey);
                   7665: 			print $client "ok:local\n";
1.442     www      7666: 			&logthis('<font color="green">'
1.212     foxr     7667: 				 . "Successful local authentication </font>");
                   7668: 			$keymode = "local"
1.178     foxr     7669: 		    } else {
1.212     foxr     7670: 			Debug("Failed to get local key");
                   7671: 			$clientok = 0;
                   7672: 			shutdown($client, 3);
                   7673: 			close $client;
1.178     foxr     7674: 		    }
1.212     foxr     7675: 		} elsif ($inittype eq "ssl") {
1.532     raeburn  7676: 		    my $key = SSLConnection($client,$clientname);
1.212     foxr     7677: 		    if ($key) {
                   7678: 			$clientok = 1;
                   7679: 			my $cipherkey = pack("H32", $key);
                   7680: 			$cipher       = new IDEA($cipherkey);
                   7681: 			&logthis('<font color="green">'
                   7682: 				 ."Successfull ssl authentication with $clientname </font>");
                   7683: 			$keymode = "ssl";
                   7684: 	     
1.178     foxr     7685: 		    } else {
1.212     foxr     7686: 			$clientok = 0;
                   7687: 			close $client;
1.178     foxr     7688: 		    }
1.212     foxr     7689: 	   
                   7690: 		} else {
                   7691: 		    my $ok = InsecureConnection($client);
                   7692: 		    if($ok) {
                   7693: 			$clientok = 1;
                   7694: 			&logthis('<font color="green">'
                   7695: 				 ."Successful insecure authentication with $clientname </font>");
                   7696: 			print $client "ok\n";
                   7697: 			$keymode = "insecure";
1.178     foxr     7698: 		    } else {
1.212     foxr     7699: 			&logthis('<font color="yellow">'
                   7700: 				  ."Attempted insecure connection disallowed </font>");
                   7701: 			close $client;
                   7702: 			$clientok = 0;
1.178     foxr     7703: 		    }
                   7704: 		}
1.212     foxr     7705: 	    } else {
                   7706: 		&logthis(
                   7707: 			 "<font color='blue'>WARNING: "
                   7708: 			 ."$clientip failed to initialize: >$remotereq< </font>");
                   7709: 		&status('No init '.$clientip);
                   7710: 	    }
                   7711: 	} else {
                   7712: 	    &logthis(
                   7713: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
                   7714: 	    &status('Hung up on '.$clientip);
                   7715: 	}
                   7716:  
                   7717: 	if ($clientok) {
                   7718: # ---------------- New known client connecting, could mean machine online again
1.368     albertel 7719: 	    if (&Apache::lonnet::get_host_ip($currenthostid) ne $clientip 
1.367     albertel 7720: 		&& $clientip ne '127.0.0.1') {
1.375     albertel 7721: 		&Apache::lonnet::reconlonc($clientname);
1.212     foxr     7722: 	    }
                   7723: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
                   7724: 	    &status('Will listen to '.$clientname);
                   7725: # ------------------------------------------------------------ Process requests
                   7726: 	    my $keep_going = 1;
                   7727: 	    my $user_input;
1.556     raeburn  7728: 
1.212     foxr     7729: 	    while(($user_input = get_request) && $keep_going) {
                   7730: 		alarm(120);
                   7731: 		Debug("Main: Got $user_input\n");
                   7732: 		$keep_going = &process_request($user_input);
1.178     foxr     7733: 		alarm(0);
1.212     foxr     7734: 		&status('Listening to '.$clientname." ($keymode)");	   
1.161     foxr     7735: 	    }
1.212     foxr     7736: 
1.59      www      7737: # --------------------------------------------- client unknown or fishy, refuse
1.212     foxr     7738: 	}  else {
1.161     foxr     7739: 	    print $client "refused\n";
                   7740: 	    $client->close();
1.190     albertel 7741: 	    &logthis("<font color='blue'>WARNING: "
1.161     foxr     7742: 		     ."Rejected client $clientip, closing connection</font>");
                   7743: 	}
1.525     raeburn  7744:     }
1.161     foxr     7745:     
1.1       albertel 7746: # =============================================================================
1.161     foxr     7747:     
1.190     albertel 7748:     &logthis("<font color='red'>CRITICAL: "
1.161     foxr     7749: 	     ."Disconnect from $clientip ($clientname)</font>");    
                   7750:     
                   7751:     
                   7752:     # this exit is VERY important, otherwise the child will become
                   7753:     # a producer of more and more children, forking yourself into
                   7754:     # process death.
                   7755:     exit;
1.106     foxr     7756:     
1.78      foxr     7757: }
1.532     raeburn  7758: 
                   7759: #
                   7760: #  Used to determine if a particular client is from the same domain
1.556     raeburn  7761: #  as the current server, or from the same internet domain, and
                   7762: #  also if the client can host sessions for the domain's users.
                   7763: #  A hash is populated with keys set to commands sent by the client
                   7764: #  which may not be executed for this domain.
1.532     raeburn  7765: #
                   7766: #  Optional input -- the client to check for domain and internet domain.
                   7767: #  If not specified, defaults to the package variable: $clientname
                   7768: #
                   7769: #  If called in array context will not set package variables, but will
                   7770: #  instead return an array of two values - (a) true if client is in the
1.556     raeburn  7771: #  same domain as the server, and (b) true if client is in the same 
                   7772: #  internet domain.
1.532     raeburn  7773: #
                   7774: #  If called in scalar context, sets package variables for current client:
                   7775: #
1.556     raeburn  7776: #  $clienthomedom    - LonCAPA domain of homeID for client.
                   7777: #  $clientsamedom    - LonCAPA domain same for this host and client.
                   7778: #  $clientintdom     - LonCAPA "internet domain" for client.
                   7779: #  $clientsameinst   - LonCAPA "internet domain" same for this host & client.
                   7780: #  $clientremoteok   - If current domain permits hosting on this client: 1
                   7781: #  %clientprohibited - Commands prohibited for domain's users for this client.
                   7782: #
                   7783: #  if the host and client have the same "internet domain", then the value
                   7784: #  of $clientremoteok is not used, and no commands are prohibited.
1.532     raeburn  7785: #
                   7786: #  returns 1 to indicate package variables have been set for current client.
                   7787: #
                   7788: 
                   7789: sub set_client_info {
                   7790:     my ($lonhost) = @_;
                   7791:     $lonhost ||= $clientname;
                   7792:     my $clienthost = &Apache::lonnet::hostname($lonhost);
                   7793:     my $clientserverhomeID = &Apache::lonnet::get_server_homeID($clienthost);
                   7794:     my $homedom = &Apache::lonnet::host_domain($clientserverhomeID);
                   7795:     my $samedom = 0;
1.557     raeburn  7796:     if ($perlvar{'lonDefDomain'} eq $homedom) {
1.532     raeburn  7797:         $samedom = 1;
                   7798:     }
                   7799:     my $intdom = &Apache::lonnet::internet_dom($clientserverhomeID);
                   7800:     my $sameinst = 0;
                   7801:     if ($intdom ne '') {
                   7802:         my $internet_names = &Apache::lonnet::get_internet_names($currenthostid);
                   7803:         if (ref($internet_names) eq 'ARRAY') {
                   7804:             if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   7805:                 $sameinst = 1;
                   7806:             }
                   7807:         }
                   7808:     }
                   7809:     if (wantarray) {
                   7810:         return ($samedom,$sameinst);
                   7811:     } else {
                   7812:         $clienthomedom = $homedom;
                   7813:         $clientsamedom = $samedom;
                   7814:         $clientintdom = $intdom;
                   7815:         $clientsameinst = $sameinst;
1.556     raeburn  7816:         if ($clientsameinst) {
                   7817:             undef($clientremoteok);
                   7818:             undef(%clientprohibited);
                   7819:         } else {
                   7820:             $clientremoteok = &get_remote_hostable($currentdomainid);
                   7821:             %clientprohibited = &get_prohibited($currentdomainid);
                   7822:         }
1.532     raeburn  7823:         return 1;
                   7824:     }
                   7825: }
                   7826: 
1.261     foxr     7827: #
                   7828: #   Determine if a user is an author for the indicated domain.
                   7829: #
                   7830: # Parameters:
                   7831: #    domain          - domain to check in .
                   7832: #    user            - Name of user to check.
                   7833: #
                   7834: # Return:
                   7835: #     1             - User is an author for domain.
                   7836: #     0             - User is not an author for domain.
                   7837: sub is_author {
                   7838:     my ($domain, $user) = @_;
                   7839: 
                   7840:     &Debug("is_author: $user @ $domain");
                   7841: 
                   7842:     my $hashref = &tie_user_hash($domain, $user, "roles",
                   7843: 				 &GDBM_READER());
                   7844: 
                   7845:     #  Author role should show up as a key /domain/_au
1.78      foxr     7846: 
1.321     albertel 7847:     my $value;
1.487     foxr     7848:     if ($hashref) {
1.78      foxr     7849: 
1.487     foxr     7850: 	my $key    = "/$domain/_au";
                   7851: 	if (defined($hashref)) {
                   7852: 	    $value = $hashref->{$key};
                   7853: 	    if(!untie_user_hash($hashref)) {
                   7854: 		return 'error: ' .  ($!+0)." untie (GDBM) Failed";
                   7855: 	    }
                   7856: 	}
                   7857: 	
                   7858: 	if(defined($value)) {
                   7859: 	    &Debug("$user @ $domain is an author");
                   7860: 	}
                   7861:     } else {
                   7862: 	return 'error: '.($!+0)." tie (GDBM) Failed";
1.261     foxr     7863:     }
                   7864: 
                   7865:     return defined($value);
                   7866: }
1.78      foxr     7867: #
                   7868: #   Checks to see if the input roleput request was to set
1.482     www      7869: # an author role.  If so, creates construction space 
1.78      foxr     7870: # Parameters:
                   7871: #    request   - The request sent to the rolesput subchunk.
                   7872: #                We're looking for  /domain/_au
                   7873: #    domain    - The domain in which the user is having roles doctored.
                   7874: #    user      - Name of the user for which the role is being put.
                   7875: #    authtype  - The authentication type associated with the user.
                   7876: #
1.289     albertel 7877: sub manage_permissions {
1.192     foxr     7878:     my ($request, $domain, $user, $authtype) = @_;
1.78      foxr     7879:     # See if the request is of the form /$domain/_au
1.289     albertel 7880:     if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
1.484     raeburn  7881:         my $path=$perlvar{'lonDocRoot'}."/priv/$domain";
1.482     www      7882:         unless (-e $path) {        
                   7883:            mkdir($path);
                   7884:         }
                   7885:         unless (-e $path.'/'.$user) {
                   7886:            mkdir($path.'/'.$user);
                   7887:         }
1.78      foxr     7888:     }
                   7889: }
1.222     foxr     7890: 
                   7891: 
                   7892: #
                   7893: #  Return the full path of a user password file, whether it exists or not.
                   7894: # Parameters:
                   7895: #   domain     - Domain in which the password file lives.
                   7896: #   user       - name of the user.
                   7897: # Returns:
                   7898: #    Full passwd path:
                   7899: #
                   7900: sub password_path {
                   7901:     my ($domain, $user) = @_;
1.264     albertel 7902:     return &propath($domain, $user).'/passwd';
1.222     foxr     7903: }
                   7904: 
                   7905: #   Password Filename
                   7906: #   Returns the path to a passwd file given domain and user... only if
                   7907: #  it exists.
                   7908: # Parameters:
                   7909: #   domain    - Domain in which to search.
                   7910: #   user      - username.
                   7911: # Returns:
                   7912: #   - If the password file exists returns its path.
                   7913: #   - If the password file does not exist, returns undefined.
                   7914: #
                   7915: sub password_filename {
                   7916:     my ($domain, $user) = @_;
                   7917: 
                   7918:     Debug ("PasswordFilename called: dom = $domain user = $user");
                   7919: 
                   7920:     my $path  = &password_path($domain, $user);
                   7921:     Debug("PasswordFilename got path: $path");
                   7922:     if(-e $path) {
                   7923: 	return $path;
                   7924:     } else {
                   7925: 	return undef;
                   7926:     }
                   7927: }
                   7928: 
                   7929: #
                   7930: #   Rewrite the contents of the user's passwd file.
                   7931: #  Parameters:
                   7932: #    domain    - domain of the user.
                   7933: #    name      - User's name.
                   7934: #    contents  - New contents of the file.
1.533     raeburn  7935: #    saveold   - (optional). If true save old file in a passwd.bak file.
1.222     foxr     7936: # Returns:
                   7937: #   0    - Failed.
                   7938: #   1    - Success.
                   7939: #
                   7940: sub rewrite_password_file {
1.533     raeburn  7941:     my ($domain, $user, $contents, $saveold) = @_;
1.222     foxr     7942: 
                   7943:     my $file = &password_filename($domain, $user);
                   7944:     if (defined $file) {
1.533     raeburn  7945:         if ($saveold) {
                   7946:             my $bakfile = $file.'.bak';
                   7947:             if (CopyFile($file,$bakfile)) {
                   7948:                 chmod(0400,$bakfile);
                   7949:                 &logthis("Old password saved in passwd.bak for internally authenticated user: $user:$domain");
                   7950:             } else {
                   7951:                 &logthis("Failed to save old password in passwd.bak for internally authenticated user: $user:$domain");
                   7952:             }
                   7953:         }
1.222     foxr     7954: 	my $pf = IO::File->new(">$file");
                   7955: 	if($pf) {
                   7956: 	    print $pf "$contents\n";
                   7957: 	    return 1;
                   7958: 	} else {
                   7959: 	    return 0;
                   7960: 	}
                   7961:     } else {
                   7962: 	return 0;
                   7963:     }
                   7964: 
                   7965: }
                   7966: 
1.78      foxr     7967: #
1.222     foxr     7968: #   get_auth_type - Determines the authorization type of a user in a domain.
1.78      foxr     7969: 
                   7970: #     Returns the authorization type or nouser if there is no such user.
                   7971: #
1.436     raeburn  7972: sub get_auth_type {
1.192     foxr     7973:     my ($domain, $user)  = @_;
1.78      foxr     7974: 
1.222     foxr     7975:     Debug("get_auth_type( $domain, $user ) \n");
1.78      foxr     7976:     my $proname    = &propath($domain, $user); 
                   7977:     my $passwdfile = "$proname/passwd";
                   7978:     if( -e $passwdfile ) {
                   7979: 	my $pf = IO::File->new($passwdfile);
                   7980: 	my $realpassword = <$pf>;
                   7981: 	chomp($realpassword);
1.79      foxr     7982: 	Debug("Password info = $realpassword\n");
1.78      foxr     7983: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79      foxr     7984: 	Debug("Authtype = $authtype, content = $contentpwd\n");
1.259     raeburn  7985: 	return "$authtype:$contentpwd";     
1.224     foxr     7986:     } else {
1.79      foxr     7987: 	Debug("Returning nouser");
1.78      foxr     7988: 	return "nouser";
                   7989:     }
1.1       albertel 7990: }
                   7991: 
1.220     foxr     7992: #
                   7993: #  Validate a user given their domain, name and password.  This utility
                   7994: #  function is used by both  AuthenticateHandler and ChangePasswordHandler
                   7995: #  to validate the login credentials of a user.
                   7996: # Parameters:
                   7997: #    $domain    - The domain being logged into (this is required due to
                   7998: #                 the capability for multihomed systems.
                   7999: #    $user      - The name of the user being validated.
                   8000: #    $password  - The user's propoposed password.
                   8001: #
                   8002: # Returns:
                   8003: #     1        - The domain,user,pasword triplet corresponds to a valid
                   8004: #                user.
                   8005: #     0        - The domain,user,password triplet is not a valid user.
                   8006: #
                   8007: sub validate_user {
1.396     raeburn  8008:     my ($domain, $user, $password, $checkdefauth) = @_;
1.220     foxr     8009: 
                   8010:     # Why negative ~pi you may well ask?  Well this function is about
                   8011:     # authentication, and therefore very important to get right.
                   8012:     # I've initialized the flag that determines whether or not I've 
                   8013:     # validated correctly to a value it's not supposed to get.
                   8014:     # At the end of this function. I'll ensure that it's not still that
                   8015:     # value so we don't just wind up returning some accidental value
                   8016:     # as a result of executing an unforseen code path that
1.249     foxr     8017:     # did not set $validated.  At the end of valid execution paths,
                   8018:     # validated shoule be 1 for success or 0 for failuer.
1.220     foxr     8019: 
                   8020:     my $validated = -3.14159;
                   8021: 
                   8022:     #  How we authenticate is determined by the type of authentication
                   8023:     #  the user has been assigned.  If the authentication type is
                   8024:     #  "nouser", the user does not exist so we will return 0.
                   8025: 
1.222     foxr     8026:     my $contents = &get_auth_type($domain, $user);
1.220     foxr     8027:     my ($howpwd, $contentpwd) = split(/:/, $contents);
                   8028: 
                   8029:     my $null = pack("C",0);	# Used by kerberos auth types.
                   8030: 
1.395     raeburn  8031:     if ($howpwd eq 'nouser') {
1.396     raeburn  8032:         if ($checkdefauth) {
                   8033:             my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   8034:             if ($domdefaults{'auth_def'} eq 'localauth') {
                   8035:                 $howpwd = $domdefaults{'auth_def'};
                   8036:                 $contentpwd = $domdefaults{'auth_arg_def'};
                   8037:             } elsif ((($domdefaults{'auth_def'} eq 'krb4') || 
                   8038:                       ($domdefaults{'auth_def'} eq 'krb5')) &&
                   8039:                      ($domdefaults{'auth_arg_def'} ne '')) {
                   8040:                 $howpwd = $domdefaults{'auth_def'};
                   8041:                 $contentpwd = $domdefaults{'auth_arg_def'}; 
                   8042:             }
1.395     raeburn  8043:         }
1.533     raeburn  8044:     }
1.220     foxr     8045:     if ($howpwd ne 'nouser') {
                   8046: 	if($howpwd eq "internal") { # Encrypted is in local password file.
1.518     raeburn  8047:             if (length($contentpwd) == 13) {
                   8048:                 $validated = (crypt($password,$contentpwd) eq $contentpwd);
                   8049:                 if ($validated) {
1.533     raeburn  8050:                     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   8051:                     if ($domdefaults{'intauth_switch'}) {
                   8052:                         my $ncpass = &hash_passwd($domain,$password);
                   8053:                         my $saveold;
                   8054:                         if ($domdefaults{'intauth_switch'} == 2) {
                   8055:                             $saveold = 1;
                   8056:                         }
                   8057:                         if (&rewrite_password_file($domain,$user,"$howpwd:$ncpass",$saveold)) {
                   8058:                             &update_passwd_history($user,$domain,$howpwd,'conversion');
                   8059:                             &logthis("Validated password hashed with bcrypt for $user:$domain");
                   8060:                         }
1.518     raeburn  8061:                     }
                   8062:                 }
                   8063:             } else {
1.533     raeburn  8064:                 $validated = &check_internal_passwd($password,$contentpwd,$domain,$user);
1.518     raeburn  8065:             }
1.220     foxr     8066: 	}
                   8067: 	elsif ($howpwd eq "unix") { # User is a normal unix user.
                   8068: 	    $contentpwd = (getpwnam($user))[1];
                   8069: 	    if($contentpwd) {
                   8070: 		if($contentpwd eq 'x') { # Shadow password file...
                   8071: 		    my $pwauth_path = "/usr/local/sbin/pwauth";
                   8072: 		    open PWAUTH,  "|$pwauth_path" or
                   8073: 			die "Cannot invoke authentication";
                   8074: 		    print PWAUTH "$user\n$password\n";
                   8075: 		    close PWAUTH;
                   8076: 		    $validated = ! $?;
                   8077: 
                   8078: 		} else { 	         # Passwords in /etc/passwd. 
                   8079: 		    $validated = (crypt($password,
                   8080: 					$contentpwd) eq $contentpwd);
                   8081: 		}
                   8082: 	    } else {
                   8083: 		$validated = 0;
                   8084: 	    }
1.439     raeburn  8085: 	} elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
                   8086:             my $checkwithkrb5 = 0;
                   8087:             if ($dist =~/^fedora(\d+)$/) {
                   8088:                 if ($1 > 11) {
                   8089:                     $checkwithkrb5 = 1;
                   8090:                 }
                   8091:             } elsif ($dist =~ /^suse([\d.]+)$/) {
                   8092:                 if ($1 > 11.1) {
                   8093:                     $checkwithkrb5 = 1; 
                   8094:                 }
                   8095:             }
                   8096:             if ($checkwithkrb5) {
                   8097:                 $validated = &krb5_authen($password,$null,$user,$contentpwd);
                   8098:             } else {
                   8099:                 $validated = &krb4_authen($password,$null,$user,$contentpwd);
                   8100:             }
1.224     foxr     8101: 	} elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
1.439     raeburn  8102:             $validated = &krb5_authen($password,$null,$user,$contentpwd);
1.224     foxr     8103: 	} elsif ($howpwd eq "localauth") { 
1.220     foxr     8104: 	    #  Authenticate via installation specific authentcation method:
                   8105: 	    $validated = &localauth::localauth($user, 
                   8106: 					       $password, 
1.353     albertel 8107: 					       $contentpwd,
                   8108: 					       $domain);
1.358     albertel 8109: 	    if ($validated < 0) {
1.357     albertel 8110: 		&logthis("localauth for $contentpwd $user:$domain returned a $validated");
                   8111: 		$validated = 0;
                   8112: 	    }
1.224     foxr     8113: 	} else {			# Unrecognized auth is also bad.
1.220     foxr     8114: 	    $validated = 0;
                   8115: 	}
                   8116:     } else {
                   8117: 	$validated = 0;
                   8118:     }
                   8119:     #
                   8120:     #  $validated has the correct stat of the authentication:
                   8121:     #
                   8122: 
                   8123:     unless ($validated != -3.14159) {
1.249     foxr     8124: 	#  I >really really< want to know if this happens.
                   8125: 	#  since it indicates that user authentication is badly
                   8126: 	#  broken in some code path.
                   8127:         #
                   8128: 	die "ValidateUser - failed to set the value of validated $domain, $user $password";
1.220     foxr     8129:     }
                   8130:     return $validated;
                   8131: }
                   8132: 
1.518     raeburn  8133: sub check_internal_passwd {
1.533     raeburn  8134:     my ($plainpass,$stored,$domain,$user) = @_;
1.518     raeburn  8135:     my (undef,$method,@rest) = split(/!/,$stored);
1.533     raeburn  8136:     if ($method eq 'bcrypt') {
1.518     raeburn  8137:         my $result = &hash_passwd($domain,$plainpass,@rest);
                   8138:         if ($result ne $stored) {
                   8139:             return 0;
                   8140:         }
1.533     raeburn  8141:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   8142:         if ($domdefaults{'intauth_check'}) {
                   8143:             # Upgrade to a larger number of rounds if necessary
                   8144:             my $defaultcost = $domdefaults{'intauth_cost'};
                   8145:             if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
                   8146:                 $defaultcost = 10;
                   8147:             }
                   8148:             if (int($rest[0])<int($defaultcost)) {
                   8149:                 if ($domdefaults{'intauth_check'} == 1) { 
                   8150:                     my $ncpass = &hash_passwd($domain,$plainpass);
                   8151:                     if (&rewrite_password_file($domain,$user,"internal:$ncpass")) {
                   8152:                         &update_passwd_history($user,$domain,'internal','update cost');
                   8153:                         &logthis("Validated password hashed with bcrypt for $user:$domain");
                   8154:                     }
                   8155:                     return 1;
                   8156:                 } elsif ($domdefaults{'intauth_check'} == 2) {
                   8157:                     return 0;
                   8158:                 }
                   8159:             }
                   8160:         } else {
                   8161:             return 1;
1.518     raeburn  8162:         }
                   8163:     }
                   8164:     return 0;
                   8165: }
                   8166: 
                   8167: sub get_last_authchg {
                   8168:     my ($domain,$user) = @_;
                   8169:     my $lastmod;
                   8170:     my $logname = &propath($domain,$user).'/passwd.log';
                   8171:     if (-e "$logname") {
                   8172:         $lastmod = (stat("$logname"))[9];
                   8173:     }
                   8174:     return $lastmod;
                   8175: }
                   8176: 
1.439     raeburn  8177: sub krb4_authen {
                   8178:     my ($password,$null,$user,$contentpwd) = @_;
                   8179:     my $validated = 0;
                   8180:     if (!($password =~ /$null/) ) {  # Null password not allowed.
                   8181:         eval {
                   8182:             require Authen::Krb4;
                   8183:         };
                   8184:         if (!$@) {
                   8185:             my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
                   8186:                                                        "",
                   8187:                                                        $contentpwd,,
                   8188:                                                        'krbtgt',
                   8189:                                                        $contentpwd,
                   8190:                                                        1,
                   8191:                                                        $password);
                   8192:             if(!$k4error) {
                   8193:                 $validated = 1;
                   8194:             } else {
                   8195:                 $validated = 0;
                   8196:                 &logthis('krb4: '.$user.', '.$contentpwd.', '.
                   8197:                           &Authen::Krb4::get_err_txt($Authen::Krb4::error));
                   8198:             }
                   8199:         } else {
                   8200:             $validated = krb5_authen($password,$null,$user,$contentpwd);
                   8201:         }
                   8202:     }
                   8203:     return $validated;
                   8204: }
                   8205: 
                   8206: sub krb5_authen {
                   8207:     my ($password,$null,$user,$contentpwd) = @_;
                   8208:     my $validated = 0;
                   8209:     if(!($password =~ /$null/)) { # Null password not allowed.
                   8210:         my $krbclient = &Authen::Krb5::parse_name($user.'@'
                   8211:                                                   .$contentpwd);
                   8212:         my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
                   8213:         my $krbserver  = &Authen::Krb5::parse_name($krbservice);
                   8214:         my $credentials= &Authen::Krb5::cc_default();
                   8215:         $credentials->initialize(&Authen::Krb5::parse_name($user.'@'
                   8216:                                                             .$contentpwd));
                   8217:         my $krbreturn;
                   8218:         if (exists(&Authen::Krb5::get_init_creds_password)) {
                   8219:             $krbreturn =
                   8220:                 &Authen::Krb5::get_init_creds_password($krbclient,$password,
                   8221:                                                           $krbservice);
                   8222:             $validated = (ref($krbreturn) eq 'Authen::Krb5::Creds');
                   8223:         } else {
                   8224:             $krbreturn  =
                   8225:                 &Authen::Krb5::get_in_tkt_with_password($krbclient,$krbserver,
                   8226:                                                          $password,$credentials);
                   8227:             $validated = ($krbreturn == 1);
                   8228:         }
                   8229:         if (!$validated) {
                   8230:             &logthis('krb5: '.$user.', '.$contentpwd.', '.
                   8231:                      &Authen::Krb5::error());
                   8232:         }
                   8233:     }
                   8234:     return $validated;
                   8235: }
1.220     foxr     8236: 
1.84      albertel 8237: sub addline {
                   8238:     my ($fname,$hostid,$ip,$newline)=@_;
                   8239:     my $contents;
                   8240:     my $found=0;
1.355     albertel 8241:     my $expr='^'.quotemeta($hostid).':'.quotemeta($ip).':';
1.134     albertel 8242:     my $sh;
1.84      albertel 8243:     if ($sh=IO::File->new("$fname.subscription")) {
                   8244: 	while (my $subline=<$sh>) {
                   8245: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
                   8246: 	}
                   8247: 	$sh->close();
                   8248:     }
                   8249:     $sh=IO::File->new(">$fname.subscription");
                   8250:     if ($contents) { print $sh $contents; }
                   8251:     if ($newline) { print $sh $newline; }
                   8252:     $sh->close();
                   8253:     return $found;
1.86      www      8254: }
                   8255: 
1.234     foxr     8256: sub get_chat {
1.324     raeburn  8257:     my ($cdom,$cname,$udom,$uname,$group)=@_;
1.310     albertel 8258: 
1.87      www      8259:     my @entries=();
1.324     raeburn  8260:     my $namespace = 'nohist_chatroom';
                   8261:     my $namespace_inroom = 'nohist_inchatroom';
1.335     albertel 8262:     if ($group ne '') {
1.324     raeburn  8263:         $namespace .= '_'.$group;
                   8264:         $namespace_inroom .= '_'.$group;
                   8265:     }
                   8266:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 8267: 				 &GDBM_READER());
                   8268:     if ($hashref) {
                   8269: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.311     albertel 8270: 	&untie_user_hash($hashref);
1.123     www      8271:     }
1.124     www      8272:     my @participants=();
1.134     albertel 8273:     my $cutoff=time-60;
1.324     raeburn  8274:     $hashref = &tie_user_hash($cdom, $cname, $namespace_inroom,
1.310     albertel 8275: 			      &GDBM_WRCREAT());
                   8276:     if ($hashref) {
                   8277:         $hashref->{$uname.':'.$udom}=time;
                   8278:         foreach my $user (sort(keys(%$hashref))) {
                   8279: 	    if ($hashref->{$user}>$cutoff) {
                   8280: 		push(@participants, 'active_participant:'.$user);
1.123     www      8281:             }
                   8282:         }
1.311     albertel 8283:         &untie_user_hash($hashref);
1.86      www      8284:     }
1.124     www      8285:     return (@participants,@entries);
1.86      www      8286: }
                   8287: 
1.234     foxr     8288: sub chat_add {
1.324     raeburn  8289:     my ($cdom,$cname,$newchat,$group)=@_;
1.88      albertel 8290:     my @entries=();
1.142     www      8291:     my $time=time;
1.324     raeburn  8292:     my $namespace = 'nohist_chatroom';
                   8293:     my $logfile = 'chatroom.log';
1.335     albertel 8294:     if ($group ne '') {
1.324     raeburn  8295:         $namespace .= '_'.$group;
                   8296:         $logfile = 'chatroom_'.$group.'.log';
                   8297:     }
                   8298:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 8299: 				 &GDBM_WRCREAT());
                   8300:     if ($hashref) {
                   8301: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.88      albertel 8302: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
                   8303: 	my ($thentime,$idnum)=split(/\_/,$lastid);
                   8304: 	my $newid=$time.'_000000';
                   8305: 	if ($thentime==$time) {
                   8306: 	    $idnum=~s/^0+//;
                   8307: 	    $idnum++;
                   8308: 	    $idnum=substr('000000'.$idnum,-6,6);
                   8309: 	    $newid=$time.'_'.$idnum;
                   8310: 	}
1.310     albertel 8311: 	$hashref->{$newid}=$newchat;
1.88      albertel 8312: 	my $expired=$time-3600;
1.310     albertel 8313: 	foreach my $comment (keys(%$hashref)) {
                   8314: 	    my ($thistime) = ($comment=~/(\d+)\_/);
1.88      albertel 8315: 	    if ($thistime<$expired) {
1.310     albertel 8316: 		delete $hashref->{$comment};
1.88      albertel 8317: 	    }
                   8318: 	}
1.310     albertel 8319: 	{
                   8320: 	    my $proname=&propath($cdom,$cname);
1.324     raeburn  8321: 	    if (open(CHATLOG,">>$proname/$logfile")) { 
1.310     albertel 8322: 		print CHATLOG ("$time:".&unescape($newchat)."\n");
                   8323: 	    }
                   8324: 	    close(CHATLOG);
1.142     www      8325: 	}
1.311     albertel 8326: 	&untie_user_hash($hashref);
1.86      www      8327:     }
1.84      albertel 8328: }
                   8329: 
                   8330: sub unsub {
                   8331:     my ($fname,$clientip)=@_;
                   8332:     my $result;
1.188     foxr     8333:     my $unsubs = 0;		# Number of successful unsubscribes:
                   8334: 
                   8335: 
                   8336:     # An old way subscriptions were handled was to have a 
                   8337:     # subscription marker file:
                   8338: 
                   8339:     Debug("Attempting unlink of $fname.$clientname");
1.161     foxr     8340:     if (unlink("$fname.$clientname")) {
1.188     foxr     8341: 	$unsubs++;		# Successful unsub via marker file.
                   8342:     } 
                   8343: 
                   8344:     # The more modern way to do it is to have a subscription list
                   8345:     # file:
                   8346: 
1.84      albertel 8347:     if (-e "$fname.subscription") {
1.161     foxr     8348: 	my $found=&addline($fname,$clientname,$clientip,'');
1.188     foxr     8349: 	if ($found) { 
                   8350: 	    $unsubs++;
                   8351: 	}
                   8352:     } 
                   8353: 
                   8354:     #  If either or both of these mechanisms succeeded in unsubscribing a 
                   8355:     #  resource we can return ok:
                   8356: 
                   8357:     if($unsubs) {
                   8358: 	$result = "ok\n";
1.84      albertel 8359:     } else {
1.188     foxr     8360: 	$result = "not_subscribed\n";
1.84      albertel 8361:     }
1.188     foxr     8362: 
1.84      albertel 8363:     return $result;
                   8364: }
                   8365: 
1.101     www      8366: sub currentversion {
                   8367:     my $fname=shift;
                   8368:     my $version=-1;
                   8369:     my $ulsdir='';
                   8370:     if ($fname=~/^(.+)\/[^\/]+$/) {
                   8371:        $ulsdir=$1;
                   8372:     }
1.114     albertel 8373:     my ($fnamere1,$fnamere2);
                   8374:     # remove version if already specified
1.101     www      8375:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114     albertel 8376:     # get the bits that go before and after the version number
                   8377:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
                   8378: 	$fnamere1=$1;
                   8379: 	$fnamere2='.'.$2;
                   8380:     }
1.101     www      8381:     if (-e $fname) { $version=1; }
                   8382:     if (-e $ulsdir) {
1.134     albertel 8383: 	if(-d $ulsdir) {
                   8384: 	    if (opendir(LSDIR,$ulsdir)) {
                   8385: 		my $ulsfn;
                   8386: 		while ($ulsfn=readdir(LSDIR)) {
1.101     www      8387: # see if this is a regular file (ignore links produced earlier)
1.134     albertel 8388: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
                   8389: 		    unless (-l $thisfile) {
1.160     www      8390: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134     albertel 8391: 			    if ($1>$version) { $version=$1; }
                   8392: 			}
                   8393: 		    }
                   8394: 		}
                   8395: 		closedir(LSDIR);
                   8396: 		$version++;
                   8397: 	    }
                   8398: 	}
                   8399:     }
                   8400:     return $version;
1.101     www      8401: }
                   8402: 
                   8403: sub thisversion {
                   8404:     my $fname=shift;
                   8405:     my $version=-1;
                   8406:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
                   8407: 	$version=$1;
                   8408:     }
                   8409:     return $version;
                   8410: }
                   8411: 
1.84      albertel 8412: sub subscribe {
                   8413:     my ($userinput,$clientip)=@_;
                   8414:     my $result;
1.293     albertel 8415:     my ($cmd,$fname)=split(/:/,$userinput,2);
1.84      albertel 8416:     my $ownership=&ishome($fname);
                   8417:     if ($ownership eq 'owner') {
1.101     www      8418: # explitly asking for the current version?
                   8419:         unless (-e $fname) {
                   8420:             my $currentversion=&currentversion($fname);
                   8421: 	    if (&thisversion($fname)==$currentversion) {
                   8422:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
                   8423: 		    my $root=$1;
                   8424:                     my $extension=$2;
                   8425:                     symlink($root.'.'.$extension,
                   8426:                             $root.'.'.$currentversion.'.'.$extension);
1.102     www      8427:                     unless ($extension=~/\.meta$/) {
                   8428:                        symlink($root.'.'.$extension.'.meta',
                   8429:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
                   8430: 		    }
1.101     www      8431:                 }
                   8432:             }
                   8433:         }
1.84      albertel 8434: 	if (-e $fname) {
                   8435: 	    if (-d $fname) {
                   8436: 		$result="directory\n";
                   8437: 	    } else {
1.161     foxr     8438: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134     albertel 8439: 		my $now=time;
1.161     foxr     8440: 		my $found=&addline($fname,$clientname,$clientip,
                   8441: 				   "$clientname:$clientip:$now\n");
1.84      albertel 8442: 		if ($found) { $result="$fname\n"; }
                   8443: 		# if they were subscribed to only meta data, delete that
                   8444:                 # subscription, when you subscribe to a file you also get
                   8445:                 # the metadata
                   8446: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
                   8447: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
1.476     raeburn  8448:                 my $protocol = $Apache::lonnet::protocol{$perlvar{'lonHostID'}};
                   8449:                 $protocol = 'http' if ($protocol ne 'https');
                   8450: 		$fname=$protocol.'://'.&Apache::lonnet::hostname($perlvar{'lonHostID'})."/".$fname;
1.84      albertel 8451: 		$result="$fname\n";
                   8452: 	    }
                   8453: 	} else {
                   8454: 	    $result="not_found\n";
                   8455: 	}
                   8456:     } else {
                   8457: 	$result="rejected\n";
                   8458:     }
                   8459:     return $result;
                   8460: }
1.287     foxr     8461: #  Change the passwd of a unix user.  The caller must have
                   8462: #  first verified that the user is a loncapa user.
                   8463: #
                   8464: # Parameters:
                   8465: #    user      - Unix user name to change.
                   8466: #    pass      - New password for the user.
                   8467: # Returns:
                   8468: #    ok    - if success
                   8469: #    other - Some meaningfule error message string.
                   8470: # NOTE:
                   8471: #    invokes a setuid script to change the passwd.
                   8472: sub change_unix_password {
                   8473:     my ($user, $pass) = @_;
                   8474: 
                   8475:     &Debug("change_unix_password");
                   8476:     my $execdir=$perlvar{'lonDaemons'};
                   8477:     &Debug("Opening lcpasswd pipeline");
                   8478:     my $pf = IO::File->new("|$execdir/lcpasswd > "
                   8479: 			   ."$perlvar{'lonDaemons'}"
                   8480: 			   ."/logs/lcpasswd.log");
                   8481:     print $pf "$user\n$pass\n$pass\n";
                   8482:     close $pf;
                   8483:     my $err = $?;
                   8484:     return ($err < @passwderrors) ? $passwderrors[$err] : 
                   8485: 	"pwchange_falure - unknown error";
                   8486: 
                   8487:     
                   8488: }
                   8489: 
1.91      albertel 8490: 
                   8491: sub make_passwd_file {
1.518     raeburn  8492:     my ($uname,$udom,$umode,$npass,$passfilename,$action)=@_;
1.390     raeburn  8493:     my $result="ok";
1.91      albertel 8494:     if ($umode eq 'krb4' or $umode eq 'krb5') {
                   8495: 	{
                   8496: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8497: 	    if ($pf) {
                   8498: 		print $pf "$umode:$npass\n";
1.518     raeburn  8499:                 &update_passwd_history($uname,$udom,$umode,$action);
1.261     foxr     8500: 	    } else {
                   8501: 		$result = "pass_file_failed_error";
                   8502: 	    }
1.91      albertel 8503: 	}
                   8504:     } elsif ($umode eq 'internal') {
1.518     raeburn  8505:         my $ncpass = &hash_passwd($udom,$npass);
1.91      albertel 8506: 	{
                   8507: 	    &Debug("Creating internal auth");
                   8508: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8509: 	    if($pf) {
1.518     raeburn  8510: 		print $pf "internal:$ncpass\n";
                   8511:                 &update_passwd_history($uname,$udom,$umode,$action); 
1.261     foxr     8512: 	    } else {
                   8513: 		$result = "pass_file_failed_error";
                   8514: 	    }
1.91      albertel 8515: 	}
                   8516:     } elsif ($umode eq 'localauth') {
                   8517: 	{
                   8518: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8519: 	    if($pf) {
                   8520: 		print $pf "localauth:$npass\n";
1.524     raeburn  8521:                 &update_passwd_history($uname,$udom,$umode,$action);
1.261     foxr     8522: 	    } else {
                   8523: 		$result = "pass_file_failed_error";
                   8524: 	    }
1.91      albertel 8525: 	}
                   8526:     } elsif ($umode eq 'unix') {
1.502     raeburn  8527: 	&logthis(">>>Attempt to create unix account blocked -- unix auth not available for new users.");
                   8528: 	$result="no_new_unix_accounts";
1.91      albertel 8529:     } elsif ($umode eq 'none') {
                   8530: 	{
1.223     foxr     8531: 	    my $pf = IO::File->new("> $passfilename");
1.261     foxr     8532: 	    if($pf) {
                   8533: 		print $pf "none:\n";
                   8534: 	    } else {
                   8535: 		$result = "pass_file_failed_error";
                   8536: 	    }
1.91      albertel 8537: 	}
1.543     raeburn  8538:     } elsif ($umode eq 'lti') {
                   8539:         my $pf = IO::File->new(">$passfilename");
                   8540:         if($pf) {
                   8541:             print $pf "lti:\n";
                   8542:             &update_passwd_history($uname,$udom,$umode,$action);
                   8543:         } else {
                   8544:             $result = "pass_file_failed_error";
                   8545:         }
1.91      albertel 8546:     } else {
1.390     raeburn  8547: 	$result="auth_mode_error";
1.91      albertel 8548:     }
                   8549:     return $result;
1.121     albertel 8550: }
                   8551: 
1.265     albertel 8552: sub convert_photo {
                   8553:     my ($start,$dest)=@_;
                   8554:     system("convert $start $dest");
                   8555: }
                   8556: 
1.121     albertel 8557: sub sethost {
                   8558:     my ($remotereq) = @_;
                   8559:     my (undef,$hostid)=split(/:/,$remotereq);
1.322     albertel 8560:     # ignore sethost if we are already correct
                   8561:     if ($hostid eq $currenthostid) {
                   8562: 	return 'ok';
                   8563:     }
                   8564: 
1.121     albertel 8565:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
1.368     albertel 8566:     if (&Apache::lonnet::get_host_ip($perlvar{'lonHostID'}) 
                   8567: 	eq &Apache::lonnet::get_host_ip($hostid)) {
1.200     matthew  8568: 	$currenthostid  =$hostid;
1.369     albertel 8569: 	$currentdomainid=&Apache::lonnet::host_domain($hostid);
1.556     raeburn  8570:         &set_client_info();
1.443     www      8571: #	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
1.121     albertel 8572:     } else {
                   8573: 	&logthis("Requested host id $hostid not an alias of ".
                   8574: 		 $perlvar{'lonHostID'}." refusing connection");
                   8575: 	return 'unable_to_set';
                   8576:     }
                   8577:     return 'ok';
                   8578: }
                   8579: 
                   8580: sub version {
                   8581:     my ($userinput)=@_;
                   8582:     $remoteVERSION=(split(/:/,$userinput))[1];
                   8583:     return "version:$VERSION";
1.127     albertel 8584: }
1.178     foxr     8585: 
1.447     raeburn  8586: sub get_usersession_config {
                   8587:     my ($dom,$name) = @_;
                   8588:     my ($usersessionconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8589:     if (defined($cached)) {
                   8590:         return $usersessionconf;
                   8591:     } else {
                   8592:         my %domconfig = &Apache::lonnet::get_dom('configuration',['usersessions'],$dom);
1.525     raeburn  8593:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'usersessions'},3600);
                   8594:         return $domconfig{'usersessions'};
1.447     raeburn  8595:     }
                   8596:     return;
                   8597: }
1.200     matthew  8598: 
1.534     raeburn  8599: sub get_usersearch_config {
                   8600:     my ($dom,$name) = @_;
                   8601:     my ($usersearchconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8602:     if (defined($cached)) {
                   8603:         return $usersearchconf;
                   8604:     } else {
                   8605:         my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$dom);
                   8606:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'directorysrch'},600);
                   8607:         return $domconfig{'directorysrch'};
                   8608:     }
                   8609:     return;
                   8610: }
                   8611: 
1.525     raeburn  8612: sub get_prohibited {
                   8613:     my ($dom) = @_;
                   8614:     my $name = 'trust';
                   8615:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8616:     unless (defined($cached)) {
                   8617:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$dom);
                   8618:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'trust'},3600);
                   8619:         $trustconfig = $domconfig{'trust'};
                   8620:     }
                   8621:     my %prohibited;
                   8622:     if (ref($trustconfig)) {
                   8623:         foreach my $prefix (keys(%{$trustconfig})) {
                   8624:             if (ref($trustconfig->{$prefix}) eq 'HASH') {
                   8625:                 my $reject;
                   8626:                 if (ref($trustconfig->{$prefix}->{'exc'}) eq 'ARRAY') {
                   8627:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'exc'}})) {
                   8628:                         $reject = 1;
                   8629:                     }
                   8630:                 }
                   8631:                 if (ref($trustconfig->{$prefix}->{'inc'}) eq 'ARRAY') {
                   8632:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'inc'}})) {
                   8633:                         $reject = 0;
                   8634:                     } else {
                   8635:                         $reject = 1;
                   8636:                     }
                   8637:                 }
                   8638:                 if ($reject) {
                   8639:                     $prohibited{$prefix} = 1;
                   8640:                 }
                   8641:             }
                   8642:         }
                   8643:     }
                   8644:     return %prohibited;
                   8645: }
1.450     raeburn  8646: 
1.556     raeburn  8647: sub get_remote_hostable {
                   8648:     my ($dom) = @_;
                   8649:     my $result;
                   8650:     if ($clientintdom) {
                   8651:         $result = 1;
                   8652:         my $remsessconf = &get_usersession_config($dom,'remotesession');
                   8653:         if (ref($remsessconf) eq 'HASH') {
                   8654:             if (ref($remsessconf->{'remote'}) eq 'HASH') {
                   8655:                 if (ref($remsessconf->{'remote'}->{'excludedomain'}) eq 'ARRAY') {
                   8656:                     if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'excludedomain'}})) {
                   8657:                         $result = 0;
                   8658:                     }
                   8659:                 }
                   8660:                 if (ref($remsessconf->{'remote'}->{'includedomain'}) eq 'ARRAY') {
                   8661:                     if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'includedomain'}})) {
                   8662:                         $result = 1;
                   8663:                     } else {
                   8664:                         $result = 0;
                   8665:                     }
                   8666:                 }
                   8667:             }
                   8668:         }
                   8669:     }
                   8670:     return $result;
                   8671: }
                   8672: 
1.471     raeburn  8673: sub distro_and_arch {
                   8674:     return $dist.':'.$arch;
                   8675: }
                   8676: 
1.61      harris41 8677: # ----------------------------------- POD (plain old documentation, CPAN style)
                   8678: 
                   8679: =head1 NAME
                   8680: 
                   8681: lond - "LON Daemon" Server (port "LOND" 5663)
                   8682: 
                   8683: =head1 SYNOPSIS
                   8684: 
1.74      harris41 8685: Usage: B<lond>
                   8686: 
                   8687: Should only be run as user=www.  This is a command-line script which
                   8688: is invoked by B<loncron>.  There is no expectation that a typical user
                   8689: will manually start B<lond> from the command-line.  (In other words,
                   8690: DO NOT START B<lond> YOURSELF.)
1.61      harris41 8691: 
                   8692: =head1 DESCRIPTION
                   8693: 
1.74      harris41 8694: There are two characteristics associated with the running of B<lond>,
                   8695: PROCESS MANAGEMENT (starting, stopping, handling child processes)
                   8696: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
                   8697: subscriptions, etc).  These are described in two large
                   8698: sections below.
                   8699: 
                   8700: B<PROCESS MANAGEMENT>
                   8701: 
1.61      harris41 8702: Preforker - server who forks first. Runs as a daemon. HUPs.
                   8703: Uses IDEA encryption
                   8704: 
1.74      harris41 8705: B<lond> forks off children processes that correspond to the other servers
                   8706: in the network.  Management of these processes can be done at the
                   8707: parent process level or the child process level.
                   8708: 
                   8709: B<logs/lond.log> is the location of log messages.
                   8710: 
                   8711: The process management is now explained in terms of linux shell commands,
                   8712: subroutines internal to this code, and signal assignments:
                   8713: 
                   8714: =over 4
                   8715: 
                   8716: =item *
                   8717: 
                   8718: PID is stored in B<logs/lond.pid>
                   8719: 
                   8720: This is the process id number of the parent B<lond> process.
                   8721: 
                   8722: =item *
                   8723: 
                   8724: SIGTERM and SIGINT
                   8725: 
                   8726: Parent signal assignment:
                   8727:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   8728: 
                   8729: Child signal assignment:
                   8730:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
                   8731: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
                   8732:  to restart a new child.)
                   8733: 
                   8734: Command-line invocations:
                   8735:  B<kill> B<-s> SIGTERM I<PID>
                   8736:  B<kill> B<-s> SIGINT I<PID>
                   8737: 
                   8738: Subroutine B<HUNTSMAN>:
                   8739:  This is only invoked for the B<lond> parent I<PID>.
                   8740: This kills all the children, and then the parent.
                   8741: The B<lonc.pid> file is cleared.
                   8742: 
                   8743: =item *
                   8744: 
                   8745: SIGHUP
                   8746: 
                   8747: Current bug:
                   8748:  This signal can only be processed the first time
                   8749: on the parent process.  Subsequent SIGHUP signals
                   8750: have no effect.
                   8751: 
                   8752: Parent signal assignment:
                   8753:  $SIG{HUP}  = \&HUPSMAN;
                   8754: 
                   8755: Child signal assignment:
                   8756:  none (nothing happens)
                   8757: 
                   8758: Command-line invocations:
                   8759:  B<kill> B<-s> SIGHUP I<PID>
                   8760: 
                   8761: Subroutine B<HUPSMAN>:
                   8762:  This is only invoked for the B<lond> parent I<PID>,
                   8763: This kills all the children, and then the parent.
                   8764: The B<lond.pid> file is cleared.
                   8765: 
                   8766: =item *
                   8767: 
                   8768: SIGUSR1
                   8769: 
                   8770: Parent signal assignment:
                   8771:  $SIG{USR1} = \&USRMAN;
                   8772: 
                   8773: Child signal assignment:
                   8774:  $SIG{USR1}= \&logstatus;
                   8775: 
                   8776: Command-line invocations:
                   8777:  B<kill> B<-s> SIGUSR1 I<PID>
                   8778: 
                   8779: Subroutine B<USRMAN>:
                   8780:  When invoked for the B<lond> parent I<PID>,
                   8781: SIGUSR1 is sent to all the children, and the status of
                   8782: each connection is logged.
1.144     foxr     8783: 
                   8784: =item *
                   8785: 
                   8786: SIGUSR2
                   8787: 
                   8788: Parent Signal assignment:
                   8789:     $SIG{USR2} = \&UpdateHosts
                   8790: 
                   8791: Child signal assignment:
                   8792:     NONE
                   8793: 
1.74      harris41 8794: 
                   8795: =item *
                   8796: 
                   8797: SIGCHLD
                   8798: 
                   8799: Parent signal assignment:
                   8800:  $SIG{CHLD} = \&REAPER;
                   8801: 
                   8802: Child signal assignment:
                   8803:  none
                   8804: 
                   8805: Command-line invocations:
                   8806:  B<kill> B<-s> SIGCHLD I<PID>
                   8807: 
                   8808: Subroutine B<REAPER>:
                   8809:  This is only invoked for the B<lond> parent I<PID>.
                   8810: Information pertaining to the child is removed.
                   8811: The socket port is cleaned up.
                   8812: 
                   8813: =back
                   8814: 
                   8815: B<SERVER-SIDE ACTIVITIES>
                   8816: 
                   8817: Server-side information can be accepted in an encrypted or non-encrypted
                   8818: method.
                   8819: 
                   8820: =over 4
                   8821: 
                   8822: =item ping
                   8823: 
                   8824: Query a client in the hosts.tab table; "Are you there?"
                   8825: 
                   8826: =item pong
                   8827: 
                   8828: Respond to a ping query.
                   8829: 
                   8830: =item ekey
                   8831: 
                   8832: Read in encrypted key, make cipher.  Respond with a buildkey.
                   8833: 
                   8834: =item load
                   8835: 
                   8836: Respond with CPU load based on a computation upon /proc/loadavg.
                   8837: 
                   8838: =item currentauth
                   8839: 
                   8840: Reply with current authentication information (only over an
                   8841: encrypted channel).
                   8842: 
                   8843: =item auth
                   8844: 
                   8845: Only over an encrypted channel, reply as to whether a user's
                   8846: authentication information can be validated.
                   8847: 
                   8848: =item passwd
                   8849: 
                   8850: Allow for a password to be set.
                   8851: 
                   8852: =item makeuser
                   8853: 
                   8854: Make a user.
                   8855: 
1.517     raeburn  8856: =item changeuserauth
1.74      harris41 8857: 
                   8858: Allow for authentication mechanism and password to be changed.
                   8859: 
                   8860: =item home
1.61      harris41 8861: 
1.74      harris41 8862: Respond to a question "are you the home for a given user?"
                   8863: 
                   8864: =item update
                   8865: 
                   8866: Update contents of a subscribed resource.
                   8867: 
                   8868: =item unsubscribe
                   8869: 
                   8870: The server is unsubscribing from a resource.
                   8871: 
                   8872: =item subscribe
                   8873: 
                   8874: The server is subscribing to a resource.
                   8875: 
                   8876: =item log
                   8877: 
                   8878: Place in B<logs/lond.log>
                   8879: 
                   8880: =item put
                   8881: 
                   8882: stores hash in namespace
                   8883: 
1.496     raeburn  8884: =item rolesput
1.74      harris41 8885: 
                   8886: put a role into a user's environment
                   8887: 
                   8888: =item get
                   8889: 
                   8890: returns hash with keys from array
                   8891: reference filled in from namespace
                   8892: 
                   8893: =item eget
                   8894: 
                   8895: returns hash with keys from array
                   8896: reference filled in from namesp (encrypts the return communication)
                   8897: 
                   8898: =item rolesget
                   8899: 
                   8900: get a role from a user's environment
                   8901: 
                   8902: =item del
                   8903: 
                   8904: deletes keys out of array from namespace
                   8905: 
                   8906: =item keys
                   8907: 
                   8908: returns namespace keys
                   8909: 
                   8910: =item dump
                   8911: 
                   8912: dumps the complete (or key matching regexp) namespace into a hash
                   8913: 
                   8914: =item store
                   8915: 
                   8916: stores hash permanently
                   8917: for this url; hashref needs to be given and should be a \%hashname; the
                   8918: remaining args aren't required and if they aren't passed or are '' they will
                   8919: be derived from the ENV
                   8920: 
                   8921: =item restore
                   8922: 
                   8923: returns a hash for a given url
                   8924: 
                   8925: =item querysend
                   8926: 
                   8927: Tells client about the lonsql process that has been launched in response
                   8928: to a sent query.
                   8929: 
                   8930: =item queryreply
                   8931: 
                   8932: Accept information from lonsql and make appropriate storage in temporary
                   8933: file space.
                   8934: 
                   8935: =item idput
                   8936: 
                   8937: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
                   8938: for each student, defined perhaps by the institutional Registrar.)
                   8939: 
                   8940: =item idget
                   8941: 
                   8942: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
                   8943: for each student, defined perhaps by the institutional Registrar.)
                   8944: 
1.517     raeburn  8945: =item iddel
                   8946: 
                   8947: Deletes one or more ids in a domain's id database.
                   8948: 
1.74      harris41 8949: =item tmpput
                   8950: 
                   8951: Accept and store information in temporary space.
                   8952: 
                   8953: =item tmpget
                   8954: 
                   8955: Send along temporarily stored information.
                   8956: 
                   8957: =item ls
                   8958: 
                   8959: List part of a user's directory.
                   8960: 
1.135     foxr     8961: =item pushtable
                   8962: 
                   8963: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
                   8964: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
                   8965: must be restored manually in case of a problem with the new table file.
                   8966: pushtable requires that the request be encrypted and validated via
                   8967: ValidateManager.  The form of the command is:
                   8968: enc:pushtable tablename <tablecontents> \n
                   8969: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
                   8970: cleartext newline.
                   8971: 
1.74      harris41 8972: =item Hanging up (exit or init)
                   8973: 
                   8974: What to do when a client tells the server that they (the client)
                   8975: are leaving the network.
                   8976: 
                   8977: =item unknown command
                   8978: 
                   8979: If B<lond> is sent an unknown command (not in the list above),
                   8980: it replys to the client "unknown_cmd".
1.135     foxr     8981: 
1.74      harris41 8982: 
                   8983: =item UNKNOWN CLIENT
                   8984: 
                   8985: If the anti-spoofing algorithm cannot verify the client,
                   8986: the client is rejected (with a "refused" message sent
                   8987: to the client, and the connection is closed.
                   8988: 
                   8989: =back
1.61      harris41 8990: 
                   8991: =head1 PREREQUISITES
                   8992: 
                   8993: IO::Socket
                   8994: IO::File
                   8995: Apache::File
                   8996: POSIX
                   8997: Crypt::IDEA
                   8998: GDBM_File
                   8999: Authen::Krb4
1.91      albertel 9000: Authen::Krb5
1.61      harris41 9001: 
                   9002: =head1 COREQUISITES
                   9003: 
1.490     droeschl 9004: none
                   9005: 
1.61      harris41 9006: =head1 OSNAMES
                   9007: 
                   9008: linux
                   9009: 
                   9010: =head1 SCRIPT CATEGORIES
                   9011: 
                   9012: Server/Process
                   9013: 
                   9014: =cut
1.409     foxr     9015: 
                   9016: 
                   9017: =pod
                   9018: 
                   9019: =head1 LOG MESSAGES
                   9020: 
                   9021: The messages below can be emitted in the lond log.  This log is located
                   9022: in ~httpd/perl/logs/lond.log  Many log messages have HTML encapsulation
                   9023: to provide coloring if examined from inside a web page. Some do not.
                   9024: Where color is used, the colors are; Red for sometihhng to get excited
                   9025: about and to follow up on. Yellow for something to keep an eye on to
                   9026: be sure it does not get worse, Green,and Blue for informational items.
                   9027: 
                   9028: In the discussions below, sometimes reference is made to ~httpd
                   9029: when describing file locations.  There isn't really an httpd 
                   9030: user, however there is an httpd directory that gets installed in the
                   9031: place that user home directories go.  On linux, this is usually
                   9032: (always?) /home/httpd.
                   9033: 
                   9034: 
                   9035: Some messages are colorless.  These are usually (not always)
                   9036: Green/Blue color level messages.
                   9037: 
                   9038: =over 2
                   9039: 
                   9040: =item (Red)  LocalConnection rejecting non local: <ip> ne 127.0.0.1
                   9041: 
                   9042: A local connection negotiation was attempted by
                   9043: a host whose IP address was not 127.0.0.1.
                   9044: The socket is closed and the child will exit.
                   9045: lond has three ways to establish an encyrption
                   9046: key with a client:
                   9047: 
                   9048: =over 2
                   9049: 
                   9050: =item local 
                   9051: 
                   9052: The key is written and read from a file.
                   9053: This is only valid for connections from localhost.
                   9054: 
                   9055: =item insecure 
                   9056: 
                   9057: The key is generated by the server and
                   9058: transmitted to the client.
                   9059: 
                   9060: =item  ssl (secure)
                   9061: 
                   9062: An ssl connection is negotiated with the client,
                   9063: the key is generated by the server and sent to the 
                   9064: client across this ssl connection before the
                   9065: ssl connectionis terminated and clear text
                   9066: transmission resumes.
                   9067: 
                   9068: =back
                   9069: 
                   9070: =item (Red) LocalConnection: caller is insane! init = <init> and type = <type>
                   9071: 
                   9072: The client is local but has not sent an initialization
                   9073: string that is the literal "init:local"  The connection
                   9074: is closed and the child exits.
                   9075: 
                   9076: =item Red CRITICAL Can't get key file <error>        
                   9077: 
                   9078: SSL key negotiation is being attempted but the call to
1.549     raeburn  9079: lonssl::KeyFile failed.  This usually means that the
1.409     foxr     9080: configuration file is not correctly defining or protecting
                   9081: the directories/files lonCertificateDirectory or
                   9082: lonnetPrivateKey
                   9083: <error> is a string that describes the reason that
                   9084: the key file could not be located.
                   9085: 
                   9086: =item (Red) CRITICAL  Can't get certificates <error>  
                   9087: 
                   9088: SSL key negotiation failed because we were not able to retrives our certificate
                   9089: or the CA's certificate in the call to lonssl::CertificateFile
                   9090: <error> is the textual reason this failed.  Usual reasons:
                   9091: 
                   9092: =over 2
1.490     droeschl 9093: 
1.409     foxr     9094: =item Apache config file for loncapa  incorrect:
1.490     droeschl 9095: 
1.409     foxr     9096: one of the variables 
                   9097: lonCertificateDirectory, lonnetCertificateAuthority, or lonnetCertificate
                   9098: undefined or incorrect
                   9099: 
                   9100: =item Permission error:
                   9101: 
                   9102: The directory pointed to by lonCertificateDirectory is not readable by lond
                   9103: 
                   9104: =item Permission error:
                   9105: 
                   9106: Files in the directory pointed to by lonCertificateDirectory are not readable by lond.
                   9107: 
                   9108: =item Installation error:                         
                   9109: 
                   9110: Either the certificate authority file or the certificate have not
                   9111: been installed in lonCertificateDirectory.
                   9112: 
                   9113: =item (Red) CRITICAL SSL Socket promotion failed:  <err> 
                   9114: 
                   9115: The promotion of the connection from plaintext to SSL failed
                   9116: <err> is the reason for the failure.  There are two
                   9117: system calls involved in the promotion (one of which failed), 
                   9118: a dup to produce
                   9119: a second fd on the raw socket over which the encrypted data
                   9120: will flow and IO::SOcket::SSL->new_from_fd which creates
                   9121: the SSL connection on the duped fd.
                   9122: 
                   9123: =item (Blue)   WARNING client did not respond to challenge 
                   9124: 
                   9125: This occurs on an insecure (non SSL) connection negotiation request.
                   9126: lond generates some number from the time, the PID and sends it to
                   9127: the client.  The client must respond by echoing this information back.
                   9128: If the client does not do so, that's a violation of the challenge
                   9129: protocols and the connection will be failed.
                   9130: 
                   9131: =item (Red) No manager table. Nobody can manage!!    
                   9132: 
                   9133: lond has the concept of privileged hosts that
                   9134: can perform remote management function such
                   9135: as update the hosts.tab.   The manager hosts
                   9136: are described in the 
                   9137: ~httpd/lonTabs/managers.tab file.
                   9138: this message is logged if this file is missing.
                   9139: 
                   9140: 
                   9141: =item (Green) Registering manager <dnsname> as <cluster_name> with <ipaddress>
                   9142: 
                   9143: Reports the successful parse and registration
                   9144: of a specific manager. 
                   9145: 
                   9146: =item Green existing host <clustername:dnsname>  
                   9147: 
                   9148: The manager host is already defined in the hosts.tab
                   9149: the information in that table, rather than the info in the
                   9150: manager table will be used to determine the manager's ip.
                   9151: 
                   9152: =item (Red) Unable to craete <filename>                 
                   9153: 
                   9154: lond has been asked to create new versions of an administrative
                   9155: file (by a manager).  When this is done, the new file is created
                   9156: in a temp file and then renamed into place so that there are always
                   9157: usable administrative files, even if the update fails.  This failure
                   9158: message means that the temp file could not be created.
                   9159: The update is abandoned, and the old file is available for use.
                   9160: 
                   9161: =item (Green) CopyFile from <oldname> to <newname> failed
                   9162: 
                   9163: In an update of administrative files, the copy of the existing file to a
                   9164: backup file failed.  The installation of the new file may still succeed,
                   9165: but there will not be a back up file to rever to (this should probably
                   9166: be yellow).
                   9167: 
                   9168: =item (Green) Pushfile: backed up <oldname> to <newname>
                   9169: 
                   9170: See above, the backup of the old administrative file succeeded.
                   9171: 
                   9172: =item (Red)  Pushfile: Unable to install <filename> <reason>
                   9173: 
                   9174: The new administrative file could not be installed.  In this case,
                   9175: the old administrative file is still in use.
                   9176: 
                   9177: =item (Green) Installed new < filename>.                      
                   9178: 
                   9179: The new administrative file was successfullly installed.                                               
                   9180: 
                   9181: =item (Red) Reinitializing lond pid=<pid>                    
                   9182: 
                   9183: The lonc child process <pid> will be sent a USR2 
                   9184: signal.
                   9185: 
                   9186: =item (Red) Reinitializing self                                    
                   9187: 
                   9188: We've been asked to re-read our administrative files,and
                   9189: are doing so.
                   9190: 
                   9191: =item (Yellow) error:Invalid process identifier <ident>  
                   9192: 
                   9193: A reinit command was received, but the target part of the 
                   9194: command was not valid.  It must be either
                   9195: 'lond' or 'lonc' but was <ident>
                   9196: 
                   9197: =item (Green) isValideditCommand checking: Command = <command> Key = <key> newline = <newline>
                   9198: 
                   9199: Checking to see if lond has been handed a valid edit
                   9200: command.  It is possible the edit command is not valid
                   9201: in that case there are no log messages to indicate that.
                   9202: 
                   9203: =item Result of password change for  <username> pwchange_success
                   9204: 
                   9205: The password for <username> was
                   9206: successfully changed.
                   9207: 
                   9208: =item Unable to open <user> passwd to change password
                   9209: 
                   9210: Could not rewrite the 
                   9211: internal password file for a user
                   9212: 
                   9213: =item Result of password change for <user> : <result>
1.490     droeschl 9214: 
1.409     foxr     9215: A unix password change for <user> was attempted 
                   9216: and the pipe returned <result>  
                   9217: 
                   9218: =item LWP GET: <message> for <fname> (<remoteurl>)
                   9219: 
                   9220: The lightweight process fetch for a resource failed
                   9221: with <message> the local filename that should
                   9222: have existed/been created was  <fname> the
                   9223: corresponding URI: <remoteurl>  This is emitted in several
                   9224: places.
                   9225: 
                   9226: =item Unable to move <transname> to <destname>     
                   9227: 
                   9228: From fetch_user_file_handler - the user file was replicated but could not
                   9229: be mv'd to its final location.
                   9230: 
                   9231: =item Looking for <domain> <username>              
                   9232: 
                   9233: From user_has_session_handler - This should be a Debug call instead
                   9234: it indicates lond is about to check whether the specified user has a 
                   9235: session active on the specified domain on the local host.
                   9236: 
                   9237: =item Client <ip> (<name>) hanging up: <input>     
                   9238: 
                   9239: lond has been asked to exit by its client.  The <ip> and <name> identify the
                   9240: client systemand <input> is the full exit command sent to the server.
                   9241: 
                   9242: =item Red CRITICAL: ABNORMAL EXIT. child <pid> for server <hostname> died through a crass with this error->[<message>].
1.490     droeschl 9243: 
1.409     foxr     9244: A lond child terminated.  NOte that this termination can also occur when the
                   9245: child receives the QUIT or DIE signals.  <pid> is the process id of the child,
                   9246: <hostname> the host lond is working for, and <message> the reason the child died
                   9247: to the best of our ability to get it (I would guess that any numeric value
                   9248: represents and errno value).  This is immediately followed by
                   9249: 
                   9250: =item  Famous last words: Catching exception - <log> 
                   9251: 
                   9252: Where log is some recent information about the state of the child.
                   9253: 
                   9254: =item Red CRITICAL: TIME OUT <pid>                     
                   9255: 
                   9256: Some timeout occured for server <pid>.  THis is normally a timeout on an LWP
                   9257: doing an HTTP::GET.
                   9258: 
                   9259: =item child <pid> died                              
                   9260: 
                   9261: The reaper caught a SIGCHILD for the lond child process <pid>
                   9262: This should be modified to also display the IP of the dying child
                   9263: $children{$pid}
                   9264: 
                   9265: =item Unknown child 0 died                           
                   9266: A child died but the wait for it returned a pid of zero which really should not
                   9267: ever happen. 
                   9268: 
                   9269: =item Child <which> - <pid> looks like we missed it's death 
                   9270: 
                   9271: When a sigchild is received, the reaper process checks all children to see if they are
                   9272: alive.  If children are dying quite quickly, the lack of signal queuing can mean
                   9273: that a signal hearalds the death of more than one child.  If so this message indicates
                   9274: which other one died. <which> is the ip of a dead child
                   9275: 
                   9276: =item Free socket: <shutdownretval>                
                   9277: 
                   9278: The HUNTSMAN sub was called due to a SIGINT in a child process.  The socket is being shutdown.
                   9279: for whatever reason, <shutdownretval> is printed but in fact shutdown() is not documented
                   9280: to return anything. This is followed by: 
                   9281: 
                   9282: =item Red CRITICAL: Shutting down                       
                   9283: 
                   9284: Just prior to exit.
                   9285: 
                   9286: =item Free socket: <shutdownretval>                 
                   9287: 
                   9288: The HUPSMAN sub was called due to a SIGHUP.  all children get killsed, and lond execs itself.
                   9289: This is followed by:
                   9290: 
                   9291: =item (Red) CRITICAL: Restarting                         
                   9292: 
                   9293: lond is about to exec itself to restart.
                   9294: 
                   9295: =item (Blue) Updating connections                        
                   9296: 
                   9297: (In response to a USR2).  All the children (except the one for localhost)
                   9298: are about to be killed, the hosts tab reread, and Apache reloaded via apachereload.
                   9299: 
                   9300: =item (Blue) UpdateHosts killing child <pid> for ip <ip>   
                   9301: 
                   9302: Due to USR2 as above.
                   9303: 
                   9304: =item (Green) keeping child for ip <ip> (pid = <pid>)    
                   9305: 
                   9306: In response to USR2 as above, the child indicated is not being restarted because
                   9307: it's assumed that we'll always need a child for the localhost.
                   9308: 
                   9309: 
                   9310: =item Going to check on the children                
                   9311: 
                   9312: Parent is about to check on the health of the child processes.
                   9313: Note that this is in response to a USR1 sent to the parent lond.
                   9314: there may be one or more of the next two messages:
                   9315: 
                   9316: =item <pid> is dead                                 
                   9317: 
                   9318: A child that we have in our child hash as alive has evidently died.
                   9319: 
                   9320: =item  Child <pid> did not respond                   
                   9321: 
                   9322: In the health check the child <pid> did not update/produce a pid_.txt
                   9323: file when sent it's USR1 signal.  That process is killed with a 9 signal, as it's
                   9324: assumed to be hung in some un-fixable way.
                   9325: 
                   9326: =item Finished checking children                   
1.490     droeschl 9327: 
1.409     foxr     9328: Master processs's USR1 processing is cojmplete.
                   9329: 
                   9330: =item (Red) CRITICAL: ------- Starting ------            
                   9331: 
                   9332: (There are more '-'s on either side).  Lond has forked itself off to 
                   9333: form a new session and is about to start actual initialization.
                   9334: 
                   9335: =item (Green) Attempting to start child (<client>)       
                   9336: 
                   9337: Started a new child process for <client>.  Client is IO::Socket object
                   9338: connected to the child.  This was as a result of a TCP/IP connection from a client.
                   9339: 
                   9340: =item Unable to determine who caller was, getpeername returned nothing
1.490     droeschl 9341: 
1.409     foxr     9342: In child process initialization.  either getpeername returned undef or
                   9343: a zero sized object was returned.  Processing continues, but in my opinion,
                   9344: this should be cause for the child to exit.
                   9345: 
                   9346: =item Unable to determine clientip                  
                   9347: 
                   9348: In child process initialization.  The peer address from getpeername was not defined.
                   9349: The client address is stored as "Unavailable" and processing continues.
                   9350: 
                   9351: =item (Yellow) INFO: Connection <ip> <name> connection type = <type>
1.490     droeschl 9352: 
1.409     foxr     9353: In child initialization.  A good connectionw as received from <ip>.
                   9354: 
                   9355: =over 2
                   9356: 
                   9357: =item <name> 
                   9358: 
                   9359: is the name of the client from hosts.tab.
                   9360: 
                   9361: =item <type> 
                   9362: 
                   9363: Is the connection type which is either 
                   9364: 
                   9365: =over 2
                   9366: 
                   9367: =item manager 
                   9368: 
                   9369: The connection is from a manager node, not in hosts.tab
                   9370: 
                   9371: =item client  
                   9372: 
                   9373: the connection is from a non-manager in the hosts.tab
                   9374: 
                   9375: =item both
                   9376: 
                   9377: The connection is from a manager in the hosts.tab.
                   9378: 
                   9379: =back
                   9380: 
                   9381: =back
                   9382: 
                   9383: =item (Blue) Certificates not installed -- trying insecure auth
                   9384: 
                   9385: One of the certificate file, key file or
                   9386: certificate authority file could not be found for a client attempting
                   9387: SSL connection intiation.  COnnection will be attemptied in in-secure mode.
                   9388: (this would be a system with an up to date lond that has not gotten a 
                   9389: certificate from us).
                   9390: 
                   9391: =item (Green)  Successful local authentication            
                   9392: 
                   9393: A local connection successfully negotiated the encryption key. 
                   9394: In this case the IDEA key is in a file (that is hopefully well protected).
                   9395: 
                   9396: =item (Green) Successful ssl authentication with <client>  
                   9397: 
                   9398: The client (<client> is the peer's name in hosts.tab), has successfully
                   9399: negotiated an SSL connection with this child process.
                   9400: 
                   9401: =item (Green) Successful insecure authentication with <client>
1.490     droeschl 9402: 
1.409     foxr     9403: 
                   9404: The client has successfully negotiated an  insecure connection withthe child process.
                   9405: 
                   9406: =item (Yellow) Attempted insecure connection disallowed    
                   9407: 
                   9408: The client attempted and failed to successfully negotiate a successful insecure
                   9409: connection.  This can happen either because the variable londAllowInsecure is false
                   9410: or undefined, or becuse the child did not successfully echo back the challenge
                   9411: string.
                   9412: 
                   9413: 
                   9414: =back
                   9415: 
1.441     raeburn  9416: =back
                   9417: 
1.409     foxr     9418: 
                   9419: =cut

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