Annotation of loncom/lond, revision 1.563

1.1       albertel    1: #!/usr/bin/perl
                      2: # The LearningOnline Network
                      3: # lond "LON Daemon" Server (port "LOND" 5663)
1.60      www         4: #
1.563   ! raeburn     5: # $Id: lond,v 1.562 2020/05/04 17:05: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.563   ! raeburn    68: my $VERSION='$Revision: 1.562 $'; #' 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},
1.561     raeburn   223:                coursesessions => {institutiononly => 1},
1.525     raeburn   224:                currentauth => {remote => 1, domroles => 1, enroll => 1},
                    225:                currentdump => {remote => 1, enroll => 1},
                    226:                currentversion => {remote=> 1, content => 1},
                    227:                dcmaildump => {remote => 1, domroles => 1},
                    228:                dcmailput => {remote => 1, domroles => 1},
                    229:                del => {remote => 1, domroles => 1, enroll => 1, content => 1},
1.551     raeburn   230:                delbalcookie => {institutiononly => 1},
1.560     raeburn   231:                delusersession => {institutiononly => 1},
1.525     raeburn   232:                deldom => {remote => 1, domroles => 1}, # not currently used
                    233:                devalidatecache => {institutiononly => 1},
                    234:                domroleput => {remote => 1, enroll => 1},
                    235:                domrolesdump => {remote => 1, catalog => 1},
                    236:                du => {remote => 1, enroll => 1},
                    237:                du2 => {remote => 1, enroll => 1},
                    238:                dump => {remote => 1, enroll => 1, domroles => 1},
                    239:                edit => {institutiononly => 1},  #not used currently
                    240:                eget => {remote => 1, domroles => 1, enroll => 1}, #not used currently
1.536     raeburn   241:                egetdom => {remote => 1, domroles => 1, enroll => 1, },
1.553     raeburn   242:                ekey => {anywhere => 1},
1.525     raeburn   243:                exit => {anywhere => 1},
                    244:                fetchuserfile => {remote => 1, enroll => 1},
                    245:                get => {remote => 1, domroles => 1, enroll => 1},
                    246:                getdom => {anywhere => 1},
                    247:                home => {anywhere => 1},
                    248:                iddel => {remote => 1, enroll => 1},
                    249:                idget => {remote => 1, enroll => 1},
                    250:                idput => {remote => 1, domroles => 1, enroll => 1},
                    251:                inc => {remote => 1, enroll => 1},
                    252:                init => {anywhere => 1},
                    253:                inst_usertypes => {remote => 1, domroles => 1, enroll => 1},
                    254:                instemailrules => {remote => 1, domroles => 1},
                    255:                instidrulecheck => {remote => 1, domroles => 1,},
                    256:                instidrules => {remote => 1, domroles => 1,},
                    257:                instrulecheck => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1},
                    258:                instselfcreatecheck => {institutiononly => 1},
                    259:                instuserrules => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1},
                    260:                keys => {remote => 1,},
                    261:                load => {anywhere => 1},
                    262:                log => {anywhere => 1},
                    263:                ls => {remote => 1, enroll => 1, content => 1,},
                    264:                ls2 => {remote => 1, enroll => 1, content => 1,},
                    265:                ls3 => {remote => 1, enroll => 1, content => 1,},
                    266:                makeuser => {remote => 1, enroll => 1, domroles => 1,},
                    267:                mkdiruserfile => {remote => 1, enroll => 1,},
                    268:                newput => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1,},
                    269:                passwd => {remote => 1},
                    270:                ping => {anywhere => 1},
                    271:                pong => {anywhere => 1},
                    272:                pushfile => {manageronly => 1},
                    273:                put => {remote => 1, enroll => 1, domroles => 1, msg => 1, content => 1, shared => 1},
                    274:                putdom => {remote => 1, domroles => 1,},
                    275:                putstore => {remote => 1, enroll => 1},
                    276:                queryreply => {anywhere => 1},
                    277:                querysend => {anywhere => 1},
1.535     raeburn   278:                querysend_activitylog => {remote => 1},
                    279:                querysend_allusers => {remote => 1, domroles => 1},
                    280:                querysend_courselog => {remote => 1},
                    281:                querysend_fetchenrollment => {remote => 1},
                    282:                querysend_getinstuser => {remote => 1},
                    283:                querysend_getmultinstusers => {remote => 1},
                    284:                querysend_instdirsearch => {remote => 1, domroles => 1, coaurem => 1},
                    285:                querysend_institutionalphotos => {remote => 1},
                    286:                querysend_portfolio_metadata => {remote => 1, content => 1},
                    287:                querysend_userlog => {remote => 1, domroles => 1},
                    288:                querysend_usersearch => {remote => 1, enroll => 1, coaurem => 1},
1.525     raeburn   289:                quit => {anywhere => 1},
                    290:                readlonnetglobal => {institutiononly => 1},
                    291:                reinit => {manageronly => 1}, #not used currently
                    292:                removeuserfile => {remote => 1, enroll => 1},
                    293:                renameuserfile => {remote => 1,},
                    294:                restore => {remote => 1, enroll => 1, reqcrs => 1,},
                    295:                rolesdel => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
                    296:                rolesput => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
1.527     raeburn   297:                servercerts => {institutiononly => 1},
1.528     raeburn   298:                serverdistarch => {anywhere => 1},
1.525     raeburn   299:                serverhomeID => {anywhere => 1},
                    300:                serverloncaparev => {anywhere => 1},
                    301:                servertimezone => {remote => 1, enroll => 1},
                    302:                setannounce => {remote => 1, domroles => 1},
                    303:                sethost => {anywhere => 1},
                    304:                store => {remote => 1, enroll => 1, reqcrs => 1,},
                    305:                studentphoto => {remote => 1, enroll => 1},
                    306:                sub => {content => 1,},
1.552     raeburn   307:                tmpdel => {institutiononly => 1},
                    308:                tmpget => {institutiononly => 1},
                    309:                tmpput => {remote => 1, othcoau => 1},
1.525     raeburn   310:                tokenauthuserfile => {anywhere => 1},
                    311:                unsub => {content => 1,},
                    312:                update => {shared => 1},
                    313:                updateclickers => {remote => 1},
                    314:                userhassession => {anywhere => 1},
                    315:                userload => {anywhere => 1},
                    316:                version => {anywhere => 1}, #not used
                    317:             );
                    318: 
                    319: #
1.207     foxr      320: #   Statistics that are maintained and dislayed in the status line.
                    321: #
1.212     foxr      322: my $Transactions = 0;		# Number of attempted transactions.
                    323: my $Failures     = 0;		# Number of transcations failed.
1.207     foxr      324: 
                    325: #   ResetStatistics: 
                    326: #      Resets the statistics counters:
                    327: #
                    328: sub ResetStatistics {
                    329:     $Transactions = 0;
                    330:     $Failures     = 0;
                    331: }
                    332: 
1.200     matthew   333: #------------------------------------------------------------------------
                    334: #
                    335: #   LocalConnection
                    336: #     Completes the formation of a locally authenticated connection.
                    337: #     This function will ensure that the 'remote' client is really the
                    338: #     local host.  If not, the connection is closed, and the function fails.
                    339: #     If so, initcmd is parsed for the name of a file containing the
                    340: #     IDEA session key.  The fie is opened, read, deleted and the session
                    341: #     key returned to the caller.
                    342: #
                    343: # Parameters:
                    344: #   $Socket      - Socket open on client.
                    345: #   $initcmd     - The full text of the init command.
                    346: #
                    347: # Returns:
                    348: #     IDEA session key on success.
                    349: #     undef on failure.
                    350: #
                    351: sub LocalConnection {
                    352:     my ($Socket, $initcmd) = @_;
1.373     albertel  353:     Debug("Attempting local connection: $initcmd client: $clientip");
1.277     albertel  354:     if($clientip ne "127.0.0.1") {
1.200     matthew   355: 	&logthis('<font color="red"> LocalConnection rejecting non local: '
1.373     albertel  356: 		 ."$clientip ne 127.0.0.1 </font>");
1.200     matthew   357: 	close $Socket;
                    358: 	return undef;
1.224     foxr      359:     }  else {
1.200     matthew   360: 	chomp($initcmd);	# Get rid of \n in filename.
                    361: 	my ($init, $type, $name) = split(/:/, $initcmd);
                    362: 	Debug(" Init command: $init $type $name ");
                    363: 
                    364: 	# Require that $init = init, and $type = local:  Otherwise
                    365: 	# the caller is insane:
                    366: 
                    367: 	if(($init ne "init") && ($type ne "local")) {
                    368: 	    &logthis('<font color = "red"> LocalConnection: caller is insane! '
                    369: 		     ."init = $init, and type = $type </font>");
                    370: 	    close($Socket);;
                    371: 	    return undef;
                    372: 		
                    373: 	}
                    374: 	#  Now get the key filename:
                    375: 
                    376: 	my $IDEAKey = lonlocal::ReadKeyFile($name);
                    377: 	return $IDEAKey;
                    378:     }
                    379: }
                    380: #------------------------------------------------------------------------------
                    381: #
                    382: #  SSLConnection
                    383: #   Completes the formation of an ssh authenticated connection. The
                    384: #   socket is promoted to an ssl socket.  If this promotion and the associated
                    385: #   certificate exchange are successful, the IDEA key is generated and sent
                    386: #   to the remote peer via the SSL tunnel. The IDEA key is also returned to
                    387: #   the caller after the SSL tunnel is torn down.
                    388: #
                    389: # Parameters:
                    390: #   Name              Type             Purpose
                    391: #   $Socket          IO::Socket::INET  Plaintext socket.
                    392: #
                    393: # Returns:
                    394: #    IDEA key on success.
                    395: #    undef on failure.
                    396: #
                    397: sub SSLConnection {
                    398:     my $Socket   = shift;
                    399: 
                    400:     Debug("SSLConnection: ");
                    401:     my $KeyFile         = lonssl::KeyFile();
                    402:     if(!$KeyFile) {
                    403: 	my $err = lonssl::LastError();
                    404: 	&logthis("<font color=\"red\"> CRITICAL"
                    405: 		 ."Can't get key file $err </font>");
                    406: 	return undef;
                    407:     }
                    408:     my ($CACertificate,
                    409: 	$Certificate) = lonssl::CertificateFile();
                    410: 
                    411: 
                    412:     # If any of the key, certificate or certificate authority 
                    413:     # certificate filenames are not defined, this can't work.
                    414: 
                    415:     if((!$Certificate) || (!$CACertificate)) {
                    416: 	my $err = lonssl::LastError();
                    417: 	&logthis("<font color=\"red\"> CRITICAL"
                    418: 		 ."Can't get certificates: $err </font>");
                    419: 
                    420: 	return undef;
                    421:     }
                    422:     Debug("Key: $KeyFile CA: $CACertificate Cert: $Certificate");
                    423: 
                    424:     # Indicate to our peer that we can procede with
                    425:     # a transition to ssl authentication:
                    426: 
                    427:     print $Socket "ok:ssl\n";
                    428: 
                    429:     Debug("Approving promotion -> ssl");
                    430:     #  And do so:
                    431: 
1.545     raeburn   432:     my $CRLFile;
                    433:     unless ($crlchecked{$clientname}) {
                    434:         $CRLFile = lonssl::CRLFile();
                    435:         $crlchecked{$clientname} = 1;
                    436:     }
                    437: 
1.200     matthew   438:     my $SSLSocket = lonssl::PromoteServerSocket($Socket,
                    439: 						$CACertificate,
                    440: 						$Certificate,
1.544     raeburn   441: 						$KeyFile,
1.545     raeburn   442: 						$clientname,
1.546     raeburn   443:                                                 $CRLFile,
                    444:                                                 $clientversion);
1.200     matthew   445:     if(! ($SSLSocket) ) {	# SSL socket promotion failed.
                    446: 	my $err = lonssl::LastError();
                    447: 	&logthis("<font color=\"red\"> CRITICAL "
                    448: 		 ."SSL Socket promotion failed: $err </font>");
                    449: 	return undef;
                    450:     }
                    451:     Debug("SSL Promotion successful");
                    452: 
                    453:     # 
                    454:     #  The only thing we'll use the socket for is to send the IDEA key
                    455:     #  to the peer:
                    456: 
                    457:     my $Key = lonlocal::CreateCipherKey();
                    458:     print $SSLSocket "$Key\n";
                    459: 
                    460:     lonssl::Close($SSLSocket); 
                    461: 
                    462:     Debug("Key exchange complete: $Key");
                    463: 
                    464:     return $Key;
                    465: }
                    466: #
                    467: #     InsecureConnection: 
                    468: #        If insecure connections are allowd,
                    469: #        exchange a challenge with the client to 'validate' the
                    470: #        client (not really, but that's the protocol):
                    471: #        We produce a challenge string that's sent to the client.
                    472: #        The client must then echo the challenge verbatim to us.
                    473: #
                    474: #  Parameter:
                    475: #      Socket      - Socket open on the client.
                    476: #  Returns:
                    477: #      1           - success.
                    478: #      0           - failure (e.g.mismatch or insecure not allowed).
                    479: #
                    480: sub InsecureConnection {
                    481:     my $Socket  =  shift;
                    482: 
                    483:     #   Don't even start if insecure connections are not allowed.
1.532     raeburn   484:     #   return 0 if Insecure connections not allowed.
                    485:     #
                    486:     if (ref($secureconf{'connfrom'}) eq 'HASH') {
                    487:         if ($clientsamedom) {
                    488:             if ($secureconf{'connfrom'}{'dom'} eq 'req') {
                    489:                 return 0;
                    490:             } 
                    491:         } elsif ($clientsameinst) {
                    492:             if ($secureconf{'connfrom'}{'intdom'} eq 'req') {
                    493:                 return 0;
                    494:             }
                    495:         } else {
                    496:             if ($secureconf{'connfrom'}{'other'} eq 'req') {
                    497:                 return 0;
                    498:             }
                    499:         }
                    500:     } elsif (!$perlvar{londAllowInsecure}) {
1.200     matthew   501: 	return 0;
                    502:     }
                    503: 
                    504:     #   Fabricate a challenge string and send it..
                    505: 
                    506:     my $challenge = "$$".time;	# pid + time.
                    507:     print $Socket "$challenge\n";
                    508:     &status("Waiting for challenge reply");
                    509: 
                    510:     my $answer = <$Socket>;
                    511:     $answer    =~s/\W//g;
                    512:     if($challenge eq $answer) {
                    513: 	return 1;
1.224     foxr      514:     } else {
1.200     matthew   515: 	logthis("<font color='blue'>WARNING client did not respond to challenge</font>");
                    516: 	&status("No challenge reqply");
                    517: 	return 0;
                    518:     }
                    519:     
                    520: 
                    521: }
1.251     foxr      522: #
                    523: #   Safely execute a command (as long as it's not a shel command and doesn
                    524: #   not require/rely on shell escapes.   The function operates by doing a
                    525: #   a pipe based fork and capturing stdout and stderr  from the pipe.
                    526: #
                    527: # Formal Parameters:
                    528: #     $line                    - A line of text to be executed as a command.
                    529: # Returns:
                    530: #     The output from that command.  If the output is multiline the caller
                    531: #     must know how to split up the output.
                    532: #
                    533: #
                    534: sub execute_command {
                    535:     my ($line)    = @_;
                    536:     my @words     = split(/\s/, $line);	# Bust the command up into words.
                    537:     my $output    = "";
                    538: 
                    539:     my $pid = open(CHILD, "-|");
                    540:     
                    541:     if($pid) {			# Parent process
                    542: 	Debug("In parent process for execute_command");
                    543: 	my @data = <CHILD>;	# Read the child's outupt...
                    544: 	close CHILD;
                    545: 	foreach my $output_line (@data) {
                    546: 	    Debug("Adding $output_line");
                    547: 	    $output .= $output_line; # Presumably has a \n on it.
                    548: 	}
                    549: 
                    550:     } else {			# Child process
                    551: 	close (STDERR);
                    552: 	open  (STDERR, ">&STDOUT");# Combine stderr, and stdout...
                    553: 	exec(@words);		# won't return.
                    554:     }
                    555:     return $output;
                    556: }
                    557: 
1.200     matthew   558: 
1.140     foxr      559: #   GetCertificate: Given a transaction that requires a certificate,
                    560: #   this function will extract the certificate from the transaction
                    561: #   request.  Note that at this point, the only concept of a certificate
                    562: #   is the hostname to which we are connected.
                    563: #
                    564: #   Parameter:
                    565: #      request   - The request sent by our client (this parameterization may
                    566: #                  need to change when we really use a certificate granting
                    567: #                  authority.
                    568: #
                    569: sub GetCertificate {
                    570:     my $request = shift;
                    571: 
                    572:     return $clientip;
                    573: }
1.161     foxr      574: 
1.178     foxr      575: #
                    576: #   Return true if client is a manager.
                    577: #
                    578: sub isManager {
                    579:     return (($ConnectionType eq "manager") || ($ConnectionType eq "both"));
                    580: }
                    581: #
                    582: #   Return tru if client can do client functions
                    583: #
                    584: sub isClient {
                    585:     return (($ConnectionType eq "client") || ($ConnectionType eq "both"));
                    586: }
1.161     foxr      587: 
                    588: 
1.156     foxr      589: #
                    590: #   ReadManagerTable: Reads in the current manager table. For now this is
                    591: #                     done on each manager authentication because:
                    592: #                     - These authentications are not frequent
                    593: #                     - This allows dynamic changes to the manager table
                    594: #                       without the need to signal to the lond.
                    595: #
                    596: sub ReadManagerTable {
                    597: 
1.412     foxr      598:     &Debug("Reading manager table");
1.156     foxr      599:     #   Clean out the old table first..
                    600: 
1.166     foxr      601:    foreach my $key (keys %managers) {
                    602:       delete $managers{$key};
                    603:    }
                    604: 
                    605:    my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
                    606:    if (!open (MANAGERS, $tablename)) {
1.473     raeburn   607:        my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
                    608:        if (&Apache::lonnet::is_LC_dns($hostname)) {
1.472     raeburn   609:            &logthis('<font color="red">No manager table.  Nobody can manage!!</font>');
                    610:        }
                    611:        return;
1.166     foxr      612:    }
                    613:    while(my $host = <MANAGERS>) {
                    614:       chomp($host);
                    615:       if ($host =~ "^#") {                  # Comment line.
                    616:          next;
                    617:       }
1.368     albertel  618:       if (!defined &Apache::lonnet::get_host_ip($host)) { # This is a non cluster member
1.161     foxr      619: 	    #  The entry is of the form:
                    620: 	    #    cluname:hostname
                    621: 	    #  cluname - A 'cluster hostname' is needed in order to negotiate
                    622: 	    #            the host key.
                    623: 	    #  hostname- The dns name of the host.
                    624: 	    #
1.166     foxr      625:           my($cluname, $dnsname) = split(/:/, $host);
                    626:           
                    627:           my $ip = gethostbyname($dnsname);
                    628:           if(defined($ip)) {                 # bad names don't deserve entry.
                    629:             my $hostip = inet_ntoa($ip);
                    630:             $managers{$hostip} = $cluname;
                    631:             logthis('<font color="green"> registering manager '.
                    632:                     "$dnsname as $cluname with $hostip </font>\n");
                    633:          }
                    634:       } else {
                    635:          logthis('<font color="green"> existing host'." $host</font>\n");
1.472     raeburn   636:          $managers{&Apache::lonnet::get_host_ip($host)} = $host;  # Use info from cluster tab if cluster memeber
1.166     foxr      637:       }
                    638:    }
1.156     foxr      639: }
1.140     foxr      640: 
                    641: #
                    642: #  ValidManager: Determines if a given certificate represents a valid manager.
                    643: #                in this primitive implementation, the 'certificate' is
                    644: #                just the connecting loncapa client name.  This is checked
                    645: #                against a valid client list in the configuration.
                    646: #
                    647: #                  
                    648: sub ValidManager {
                    649:     my $certificate = shift; 
                    650: 
1.163     foxr      651:     return isManager;
1.140     foxr      652: }
                    653: #
1.143     foxr      654: #  CopyFile:  Called as part of the process of installing a 
                    655: #             new configuration file.  This function copies an existing
                    656: #             file to a backup file.
                    657: # Parameters:
                    658: #     oldfile  - Name of the file to backup.
                    659: #     newfile  - Name of the backup file.
                    660: # Return:
                    661: #     0   - Failure (errno has failure reason).
                    662: #     1   - Success.
                    663: #
                    664: sub CopyFile {
1.192     foxr      665: 
                    666:     my ($oldfile, $newfile) = @_;
1.143     foxr      667: 
1.281     matthew   668:     if (! copy($oldfile,$newfile)) {
                    669:         return 0;
1.143     foxr      670:     }
1.281     matthew   671:     chmod(0660, $newfile);
                    672:     return 1;
1.143     foxr      673: }
1.157     foxr      674: #
                    675: #  Host files are passed out with externally visible host IPs.
                    676: #  If, for example, we are behind a fire-wall or NAT host, our 
                    677: #  internally visible IP may be different than the externally
                    678: #  visible IP.  Therefore, we always adjust the contents of the
                    679: #  host file so that the entry for ME is the IP that we believe
                    680: #  we have.  At present, this is defined as the entry that
                    681: #  DNS has for us.  If by some chance we are not able to get a
                    682: #  DNS translation for us, then we assume that the host.tab file
                    683: #  is correct.  
                    684: #    BUGBUGBUG - in the future, we really should see if we can
                    685: #       easily query the interface(s) instead.
                    686: # Parameter(s):
                    687: #     contents    - The contents of the host.tab to check.
                    688: # Returns:
                    689: #     newcontents - The adjusted contents.
                    690: #
                    691: #
                    692: sub AdjustHostContents {
                    693:     my $contents  = shift;
                    694:     my $adjusted;
                    695:     my $me        = $perlvar{'lonHostID'};
                    696: 
1.354     albertel  697:     foreach my $line (split(/\n/,$contents)) {
1.472     raeburn   698: 	if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/) ||
                    699:              ($line =~ /^\s*\^/))) {
1.157     foxr      700: 	    chomp($line);
                    701: 	    my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
                    702: 	    if ($id eq $me) {
1.354     albertel  703: 		my $ip = gethostbyname($name);
                    704: 		my $ipnew = inet_ntoa($ip);
                    705: 		$ip = $ipnew;
1.157     foxr      706: 		#  Reconstruct the host line and append to adjusted:
                    707: 		
1.354     albertel  708: 		my $newline = "$id:$domain:$role:$name:$ip";
                    709: 		if($maxcon ne "") { # Not all hosts have loncnew tuning params
                    710: 		    $newline .= ":$maxcon:$idleto:$mincon";
                    711: 		}
                    712: 		$adjusted .= $newline."\n";
1.157     foxr      713: 		
1.354     albertel  714: 	    } else {		# Not me, pass unmodified.
                    715: 		$adjusted .= $line."\n";
                    716: 	    }
1.157     foxr      717: 	} else {                  # Blank or comment never re-written.
                    718: 	    $adjusted .= $line."\n";	# Pass blanks and comments as is.
                    719: 	}
1.354     albertel  720:     }
                    721:     return $adjusted;
1.157     foxr      722: }
1.143     foxr      723: #
                    724: #   InstallFile: Called to install an administrative file:
1.412     foxr      725: #       - The file is created int a temp directory called <name>.tmp
                    726: #       - lcinstall file is called to install the file.
                    727: #         since the web app has no direct write access to the table directory
1.143     foxr      728: #
                    729: #  Parameters:
                    730: #       Name of the file
                    731: #       File Contents.
                    732: #  Return:
                    733: #      nonzero - success.
                    734: #      0       - failure and $! has an errno.
1.412     foxr      735: # Assumptions:
                    736: #    File installtion is a relatively infrequent
1.143     foxr      737: #
                    738: sub InstallFile {
1.192     foxr      739: 
                    740:     my ($Filename, $Contents) = @_;
1.412     foxr      741: #     my $TempFile = $Filename.".tmp";
                    742:     my $exedir = $perlvar{'lonDaemons'};
                    743:     my $tmpdir = $exedir.'/tmp/';
                    744:     my $TempFile = $tmpdir."TempTableFile.tmp";
1.143     foxr      745: 
                    746:     #  Open the file for write:
                    747: 
                    748:     my $fh = IO::File->new("> $TempFile"); # Write to temp.
                    749:     if(!(defined $fh)) {
                    750: 	&logthis('<font color="red"> Unable to create '.$TempFile."</font>");
                    751: 	return 0;
                    752:     }
                    753:     #  write the contents of the file:
                    754: 
                    755:     print $fh ($Contents); 
                    756:     $fh->close;			# In case we ever have a filesystem w. locking
                    757: 
1.412     foxr      758:     chmod(0664, $TempFile);	# Everyone can write it.
                    759: 
                    760:     # Use lcinstall file to put the file in the table directory...
                    761: 
                    762:     &Debug("Opening pipe to $exedir/lcinstallfile $TempFile $Filename");
                    763:     my $pf = IO::File->new("| $exedir/lcinstallfile   $TempFile $Filename > $exedir/logs/lcinstallfile.log");
                    764:     close $pf;
                    765:     my $err = $?;
                    766:     &Debug("Status is $err");
                    767:     if ($err != 0) {
                    768: 	my $msg = $err;
                    769: 	if ($err < @installerrors) {
                    770: 	    $msg = $installerrors[$err];
                    771: 	}
                    772: 	&logthis("Install failed for table file $Filename : $msg");
                    773: 	return 0;
                    774:     }
                    775: 
                    776:     # Remove the temp file:
1.143     foxr      777: 
1.412     foxr      778:     unlink($TempFile);
1.143     foxr      779: 
                    780:     return 1;
                    781: }
1.200     matthew   782: 
                    783: 
1.169     foxr      784: #
                    785: #   ConfigFileFromSelector: converts a configuration file selector
1.411     foxr      786: #                 into a configuration file pathname.
1.472     raeburn   787: #                 Supports the following file selectors: 
                    788: #                 hosts, domain, dns_hosts, dns_domain  
1.411     foxr      789: #
1.169     foxr      790: #
                    791: #  Parameters:
                    792: #      selector  - Configuration file selector.
                    793: #  Returns:
                    794: #      Full path to the file or undef if the selector is invalid.
                    795: #
                    796: sub ConfigFileFromSelector {
                    797:     my $selector   = shift;
                    798:     my $tablefile;
                    799: 
1.549     raeburn   800:     if ($selector eq 'loncapaCAcrl') {
                    801:         my $tabledir = $perlvar{'lonCertificateDirectory'};
                    802:         if (-d $tabledir) {
                    803:             $tablefile =  $tabledir.'/'.$selector.'.pem';
                    804:         }
                    805:     } else {
                    806:         my $tabledir = $perlvar{'lonTabDir'}.'/';
                    807:         if (($selector eq "hosts") || ($selector eq "domain") || 
                    808:             ($selector eq "dns_hosts") || ($selector eq "dns_domain")) {
                    809: 	    $tablefile =  $tabledir.$selector.'.tab';
                    810:         }
1.169     foxr      811:     }
                    812:     return $tablefile;
                    813: }
1.143     foxr      814: #
1.141     foxr      815: #   PushFile:  Called to do an administrative push of a file.
                    816: #              - Ensure the file being pushed is one we support.
                    817: #              - Backup the old file to <filename.saved>
                    818: #              - Separate the contents of the new file out from the
                    819: #                rest of the request.
                    820: #              - Write the new file.
                    821: #  Parameter:
                    822: #     Request - The entire user request.  This consists of a : separated
                    823: #               string pushfile:tablename:contents.
                    824: #     NOTE:  The contents may have :'s in it as well making things a bit
                    825: #            more interesting... but not much.
                    826: #  Returns:
                    827: #     String to send to client ("ok" or "refused" if bad file).
                    828: #
                    829: sub PushFile {
1.510     raeburn   830:     my $request = shift;
1.141     foxr      831:     my ($command, $filename, $contents) = split(":", $request, 3);
1.412     foxr      832:     &Debug("PushFile");
1.141     foxr      833:     
1.549     raeburn   834:     #  At this point in time, pushes for only the following tables and
                    835:     #  CRL file are supported:
1.141     foxr      836:     #   hosts.tab  ($filename eq host).
                    837:     #   domain.tab ($filename eq domain).
1.472     raeburn   838:     #   dns_hosts.tab ($filename eq dns_host).
1.554     raeburn   839:     #   dns_domain.tab ($filename eq dns_domain).
                    840:     #   loncapaCAcrl.pem ($filename eq loncapaCAcrl).
1.141     foxr      841:     # Construct the destination filename or reject the request.
                    842:     #
                    843:     # lonManage is supposed to ensure this, however this session could be
                    844:     # part of some elaborate spoof that managed somehow to authenticate.
                    845:     #
                    846: 
1.169     foxr      847: 
                    848:     my $tablefile = ConfigFileFromSelector($filename);
                    849:     if(! (defined $tablefile)) {
1.141     foxr      850: 	return "refused";
                    851:     }
1.412     foxr      852: 
1.157     foxr      853:     #  If the file being pushed is the host file, we adjust the entry for ourself so that the
                    854:     #  IP will be our current IP as looked up in dns.  Note this is only 99% good as it's possible
                    855:     #  to conceive of conditions where we don't have a DNS entry locally.  This is possible in a 
                    856:     #  network sense but it doesn't make much sense in a LonCAPA sense so we ignore (for now)
                    857:     #  that possibilty.
                    858: 
                    859:     if($filename eq "host") {
                    860: 	$contents = AdjustHostContents($contents);
1.549     raeburn   861:     } elsif (($filename eq 'dns_host') || ($filename eq 'dns_domain') ||
                    862:              ($filename eq 'loncapaCAcrl')) {
1.510     raeburn   863:         if ($contents eq '') {
                    864:             &logthis('<font color="red"> Pushfile: unable to install '
                    865:                     .$tablefile." - no data received from push. </font>");
                    866:             return 'error: push had no data';
                    867:         }
                    868:         if (&Apache::lonnet::get_host_ip($clientname)) {
                    869:             my $clienthost = &Apache::lonnet::hostname($clientname);
                    870:             if ($managers{$clientip} eq $clientname) {
                    871:                 my $clientprotocol = $Apache::lonnet::protocol{$clientname};
                    872:                 $clientprotocol = 'http' if ($clientprotocol ne 'https');
1.549     raeburn   873:                 my $url;
                    874:                 if ($filename eq 'loncapaCAcrl') {
                    875:                     $url = '/adm/dns/loncapaCRL';
                    876:                 } else {
                    877:                     $url = '/adm/'.$filename;
                    878:                     $url =~ s{_}{/};
                    879:                 }
1.510     raeburn   880:                 my $request=new HTTP::Request('GET',"$clientprotocol://$clienthost$url");
1.523     raeburn   881:                 my $response = LONCAPA::LWPReq::makerequest($clientname,$request,'',\%perlvar,60,0);
1.510     raeburn   882:                 if ($response->is_error()) {
                    883:                     &logthis('<font color="red"> Pushfile: unable to install '
                    884:                             .$tablefile." - error attempting to pull data. </font>");
                    885:                     return 'error: pull failed';
                    886:                 } else {
                    887:                     my $result = $response->content;
                    888:                     chomp($result);
                    889:                     unless ($result eq $contents) {
                    890:                         &logthis('<font color="red"> Pushfile: unable to install '
                    891:                                 .$tablefile." - pushed data and pulled data differ. </font>");
                    892:                         my $pushleng = length($contents);
                    893:                         my $pullleng = length($result);
                    894:                         if ($pushleng != $pullleng) {
                    895:                             return "error: $pushleng vs $pullleng bytes";
                    896:                         } else {
                    897:                             return "error: mismatch push and pull";
                    898:                         }
                    899:                     }
                    900:                 }
                    901:             }
                    902:         }
1.157     foxr      903:     }
                    904: 
1.141     foxr      905:     #  Install the new file:
                    906: 
1.412     foxr      907:     &logthis("Installing new $tablefile contents:\n$contents");
1.143     foxr      908:     if(!InstallFile($tablefile, $contents)) {
                    909: 	&logthis('<font color="red"> Pushfile: unable to install '
1.145     foxr      910: 	 .$tablefile." $! </font>");
1.143     foxr      911: 	return "error:$!";
1.224     foxr      912:     } else {
1.143     foxr      913: 	&logthis('<font color="green"> Installed new '.$tablefile
1.473     raeburn   914: 		 ." - transaction by: $clientname ($clientip)</font>");
1.472     raeburn   915:         my $adminmail = $perlvar{'lonAdmEMail'};
                    916:         my $admindom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                    917:         if ($admindom ne '') {
                    918:             my %domconfig =
                    919:                 &Apache::lonnet::get_dom('configuration',['contacts'],$admindom);
                    920:             if (ref($domconfig{'contacts'}) eq 'HASH') {
                    921:                 if ($domconfig{'contacts'}{'adminemail'} ne '') {
                    922:                     $adminmail = $domconfig{'contacts'}{'adminemail'};
                    923:                 }
                    924:             }
                    925:         }
                    926:         if ($adminmail =~ /^[^\@]+\@[^\@]+$/) {
                    927:             my $msg = new Mail::Send;
                    928:             $msg->to($adminmail);
                    929:             $msg->subject('LON-CAPA DNS update on '.$perlvar{'lonHostID'});
                    930:             $msg->add('Content-type','text/plain; charset=UTF-8');
                    931:             if (my $fh = $msg->open()) {
                    932:                 print $fh 'Update to '.$tablefile.' from Cluster Manager '.
1.473     raeburn   933:                           "$clientname ($clientip)\n";
1.472     raeburn   934:                 $fh->close;
                    935:             }
                    936:         }
1.143     foxr      937:     }
                    938: 
1.141     foxr      939:     #  Indicate success:
                    940:  
                    941:     return "ok";
                    942: 
                    943: }
1.145     foxr      944: 
                    945: #
                    946: #  Called to re-init either lonc or lond.
                    947: #
                    948: #  Parameters:
                    949: #    request   - The full request by the client.  This is of the form
                    950: #                reinit:<process>  
                    951: #                where <process> is allowed to be either of 
                    952: #                lonc or lond
                    953: #
                    954: #  Returns:
                    955: #     The string to be sent back to the client either:
                    956: #   ok         - Everything worked just fine.
                    957: #   error:why  - There was a failure and why describes the reason.
                    958: #
                    959: #
                    960: sub ReinitProcess {
                    961:     my $request = shift;
                    962: 
1.146     foxr      963: 
                    964:     # separate the request (reinit) from the process identifier and
                    965:     # validate it producing the name of the .pid file for the process.
                    966:     #
                    967:     #
                    968:     my ($junk, $process) = split(":", $request);
1.147     foxr      969:     my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
1.146     foxr      970:     if($process eq 'lonc') {
                    971: 	$processpidfile = $processpidfile."lonc.pid";
1.147     foxr      972: 	if (!open(PIDFILE, "< $processpidfile")) {
                    973: 	    return "error:Open failed for $processpidfile";
                    974: 	}
                    975: 	my $loncpid = <PIDFILE>;
                    976: 	close(PIDFILE);
                    977: 	logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
                    978: 		."</font>");
                    979: 	kill("USR2", $loncpid);
1.146     foxr      980:     } elsif ($process eq 'lond') {
1.147     foxr      981: 	logthis('<font color="red"> Reinitializing self (lond) </font>');
                    982: 	&UpdateHosts;			# Lond is us!!
1.146     foxr      983:     } else {
                    984: 	&logthis('<font color="yellow" Invalid reinit request for '.$process
                    985: 		 ."</font>");
                    986: 	return "error:Invalid process identifier $process";
                    987:     }
1.145     foxr      988:     return 'ok';
                    989: }
1.168     foxr      990: #   Validate a line in a configuration file edit script:
                    991: #   Validation includes:
                    992: #     - Ensuring the command is valid.
                    993: #     - Ensuring the command has sufficient parameters
                    994: #   Parameters:
                    995: #     scriptline - A line to validate (\n has been stripped for what it's worth).
1.167     foxr      996: #
1.168     foxr      997: #   Return:
                    998: #      0     - Invalid scriptline.
                    999: #      1     - Valid scriptline
                   1000: #  NOTE:
                   1001: #     Only the command syntax is checked, not the executability of the
                   1002: #     command.
                   1003: #
                   1004: sub isValidEditCommand {
                   1005:     my $scriptline = shift;
                   1006: 
                   1007:     #   Line elements are pipe separated:
                   1008: 
                   1009:     my ($command, $key, $newline)  = split(/\|/, $scriptline);
                   1010:     &logthis('<font color="green"> isValideditCommand checking: '.
                   1011: 	     "Command = '$command', Key = '$key', Newline = '$newline' </font>\n");
                   1012:     
                   1013:     if ($command eq "delete") {
                   1014: 	#
                   1015: 	#   key with no newline.
                   1016: 	#
                   1017: 	if( ($key eq "") || ($newline ne "")) {
                   1018: 	    return 0;		# Must have key but no newline.
                   1019: 	} else {
                   1020: 	    return 1;		# Valid syntax.
                   1021: 	}
1.169     foxr     1022:     } elsif ($command eq "replace") {
1.168     foxr     1023: 	#
                   1024: 	#   key and newline:
                   1025: 	#
                   1026: 	if (($key eq "") || ($newline eq "")) {
                   1027: 	    return 0;
                   1028: 	} else {
                   1029: 	    return 1;
                   1030: 	}
1.169     foxr     1031:     } elsif ($command eq "append") {
                   1032: 	if (($key ne "") && ($newline eq "")) {
                   1033: 	    return 1;
                   1034: 	} else {
                   1035: 	    return 0;
                   1036: 	}
1.168     foxr     1037:     } else {
                   1038: 	return 0;		# Invalid command.
                   1039:     }
                   1040:     return 0;			# Should not get here!!!
                   1041: }
1.169     foxr     1042: #
                   1043: #   ApplyEdit - Applies an edit command to a line in a configuration 
                   1044: #               file.  It is the caller's responsiblity to validate the
                   1045: #               edit line.
                   1046: #   Parameters:
                   1047: #      $directive - A single edit directive to apply.  
                   1048: #                   Edit directives are of the form:
                   1049: #                  append|newline      - Appends a new line to the file.
                   1050: #                  replace|key|newline - Replaces the line with key value 'key'
                   1051: #                  delete|key          - Deletes the line with key value 'key'.
                   1052: #      $editor   - A config file editor object that contains the
                   1053: #                  file being edited.
                   1054: #
                   1055: sub ApplyEdit {
1.192     foxr     1056: 
                   1057:     my ($directive, $editor) = @_;
1.169     foxr     1058: 
                   1059:     # Break the directive down into its command and its parameters
                   1060:     # (at most two at this point.  The meaning of the parameters, if in fact
                   1061:     #  they exist depends on the command).
                   1062: 
                   1063:     my ($command, $p1, $p2) = split(/\|/, $directive);
                   1064: 
                   1065:     if($command eq "append") {
                   1066: 	$editor->Append($p1);	          # p1 - key p2 null.
                   1067:     } elsif ($command eq "replace") {
                   1068: 	$editor->ReplaceLine($p1, $p2);   # p1 - key p2 = newline.
                   1069:     } elsif ($command eq "delete") {
                   1070: 	$editor->DeleteLine($p1);         # p1 - key p2 null.
                   1071:     } else {			          # Should not get here!!!
                   1072: 	die "Invalid command given to ApplyEdit $command"
                   1073:     }
                   1074: }
                   1075: #
                   1076: # AdjustOurHost:
                   1077: #           Adjusts a host file stored in a configuration file editor object
                   1078: #           for the true IP address of this host. This is necessary for hosts
                   1079: #           that live behind a firewall.
                   1080: #           Those hosts have a publicly distributed IP of the firewall, but
                   1081: #           internally must use their actual IP.  We assume that a given
                   1082: #           host only has a single IP interface for now.
                   1083: # Formal Parameters:
                   1084: #     editor   - The configuration file editor to adjust.  This
                   1085: #                editor is assumed to contain a hosts.tab file.
                   1086: # Strategy:
                   1087: #    - Figure out our hostname.
                   1088: #    - Lookup the entry for this host.
                   1089: #    - Modify the line to contain our IP
                   1090: #    - Do a replace for this host.
                   1091: sub AdjustOurHost {
                   1092:     my $editor        = shift;
                   1093: 
                   1094:     # figure out who I am.
                   1095: 
                   1096:     my $myHostName    = $perlvar{'lonHostID'}; # LonCAPA hostname.
                   1097: 
                   1098:     #  Get my host file entry.
                   1099: 
                   1100:     my $ConfigLine    = $editor->Find($myHostName);
                   1101:     if(! (defined $ConfigLine)) {
                   1102: 	die "AdjustOurHost - no entry for me in hosts file $myHostName";
                   1103:     }
                   1104:     # figure out my IP:
                   1105:     #   Use the config line to get my hostname.
                   1106:     #   Use gethostbyname to translate that into an IP address.
                   1107:     #
1.338     albertel 1108:     my ($id,$domain,$role,$name,$maxcon,$idleto,$mincon) = split(/:/,$ConfigLine);
1.169     foxr     1109:     #
                   1110:     #  Reassemble the config line from the elements in the list.
                   1111:     #  Note that if the loncnew items were not present before, they will
                   1112:     #  be now even if they would be empty
                   1113:     #
                   1114:     my $newConfigLine = $id;
1.338     albertel 1115:     foreach my $item ($domain, $role, $name, $maxcon, $idleto, $mincon) {
1.169     foxr     1116: 	$newConfigLine .= ":".$item;
                   1117:     }
                   1118:     #  Replace the line:
                   1119: 
                   1120:     $editor->ReplaceLine($id, $newConfigLine);
                   1121:     
                   1122: }
                   1123: #
                   1124: #   ReplaceConfigFile:
                   1125: #              Replaces a configuration file with the contents of a
                   1126: #              configuration file editor object.
                   1127: #              This is done by:
                   1128: #              - Copying the target file to <filename>.old
                   1129: #              - Writing the new file to <filename>.tmp
                   1130: #              - Moving <filename.tmp>  -> <filename>
                   1131: #              This laborious process ensures that the system is never without
                   1132: #              a configuration file that's at least valid (even if the contents
                   1133: #              may be dated).
                   1134: #   Parameters:
                   1135: #        filename   - Name of the file to modify... this is a full path.
                   1136: #        editor     - Editor containing the file.
                   1137: #
                   1138: sub ReplaceConfigFile {
1.192     foxr     1139:     
                   1140:     my ($filename, $editor) = @_;
1.168     foxr     1141: 
1.169     foxr     1142:     CopyFile ($filename, $filename.".old");
                   1143: 
                   1144:     my $contents  = $editor->Get(); # Get the contents of the file.
                   1145: 
                   1146:     InstallFile($filename, $contents);
                   1147: }
1.168     foxr     1148: #   
                   1149: #
                   1150: #   Called to edit a configuration table  file
1.167     foxr     1151: #   Parameters:
                   1152: #      request           - The entire command/request sent by lonc or lonManage
                   1153: #   Return:
                   1154: #      The reply to send to the client.
1.168     foxr     1155: #
1.167     foxr     1156: sub EditFile {
                   1157:     my $request = shift;
                   1158: 
                   1159:     #  Split the command into it's pieces:  edit:filetype:script
                   1160: 
1.339     albertel 1161:     my ($cmd, $filetype, $script) = split(/:/, $request,3);	# : in script
1.167     foxr     1162: 
                   1163:     #  Check the pre-coditions for success:
                   1164: 
1.339     albertel 1165:     if($cmd != "edit") {	# Something is amiss afoot alack.
1.167     foxr     1166: 	return "error:edit request detected, but request != 'edit'\n";
                   1167:     }
                   1168:     if( ($filetype ne "hosts")  &&
                   1169: 	($filetype ne "domain")) {
                   1170: 	return "error:edit requested with invalid file specifier: $filetype \n";
                   1171:     }
                   1172: 
                   1173:     #   Split the edit script and check it's validity.
1.168     foxr     1174: 
                   1175:     my @scriptlines = split(/\n/, $script);  # one line per element.
                   1176:     my $linecount   = scalar(@scriptlines);
                   1177:     for(my $i = 0; $i < $linecount; $i++) {
                   1178: 	chomp($scriptlines[$i]);
                   1179: 	if(!isValidEditCommand($scriptlines[$i])) {
                   1180: 	    return "error:edit with bad script line: '$scriptlines[$i]' \n";
                   1181: 	}
                   1182:     }
1.145     foxr     1183: 
1.167     foxr     1184:     #   Execute the edit operation.
1.169     foxr     1185:     #   - Create a config file editor for the appropriate file and 
                   1186:     #   - execute each command in the script:
                   1187:     #
                   1188:     my $configfile = ConfigFileFromSelector($filetype);
                   1189:     if (!(defined $configfile)) {
                   1190: 	return "refused\n";
                   1191:     }
                   1192:     my $editor = ConfigFileEdit->new($configfile);
1.167     foxr     1193: 
1.169     foxr     1194:     for (my $i = 0; $i < $linecount; $i++) {
                   1195: 	ApplyEdit($scriptlines[$i], $editor);
                   1196:     }
                   1197:     # If the file is the host file, ensure that our host is
                   1198:     # adjusted to have our ip:
                   1199:     #
                   1200:     if($filetype eq "host") {
                   1201: 	AdjustOurHost($editor);
                   1202:     }
                   1203:     #  Finally replace the current file with our file.
                   1204:     #
                   1205:     ReplaceConfigFile($configfile, $editor);
1.167     foxr     1206: 
                   1207:     return "ok\n";
                   1208: }
1.207     foxr     1209: 
1.255     foxr     1210: #   read_profile
                   1211: #
                   1212: #   Returns a set of specific entries from a user's profile file.
                   1213: #   this is a utility function that is used by both get_profile_entry and
                   1214: #   get_profile_entry_encrypted.
                   1215: #
                   1216: # Parameters:
                   1217: #    udom       - Domain in which the user exists.
                   1218: #    uname      - User's account name (loncapa account)
                   1219: #    namespace  - The profile namespace to open.
                   1220: #    what       - A set of & separated queries.
                   1221: # Returns:
                   1222: #    If all ok: - The string that needs to be shipped back to the user.
                   1223: #    If failure - A string that starts with error: followed by the failure
                   1224: #                 reason.. note that this probabyl gets shipped back to the
                   1225: #                 user as well.
                   1226: #
                   1227: sub read_profile {
                   1228:     my ($udom, $uname, $namespace, $what) = @_;
                   1229:     
                   1230:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   1231: 				 &GDBM_READER());
                   1232:     if ($hashref) {
                   1233:         my @queries=split(/\&/,$what);
1.440     raeburn  1234:         if ($namespace eq 'roles') {
                   1235:             @queries = map { &unescape($_); } @queries; 
                   1236:         }
1.255     foxr     1237:         my $qresult='';
                   1238: 	
                   1239: 	for (my $i=0;$i<=$#queries;$i++) {
                   1240: 	    $qresult.="$hashref->{$queries[$i]}&";    # Presumably failure gives empty string.
                   1241: 	}
                   1242: 	$qresult=~s/\&$//;              # Remove trailing & from last lookup.
1.311     albertel 1243: 	if (&untie_user_hash($hashref)) {
1.255     foxr     1244: 	    return $qresult;
                   1245: 	} else {
                   1246: 	    return "error: ".($!+0)." untie (GDBM) Failed";
                   1247: 	}
                   1248:     } else {
                   1249: 	if ($!+0 == 2) {
                   1250: 	    return "error:No such file or GDBM reported bad block error";
                   1251: 	} else {
                   1252: 	    return "error: ".($!+0)." tie (GDBM) Failed";
                   1253: 	}
                   1254:     }
                   1255: 
                   1256: }
1.214     foxr     1257: #--------------------- Request Handlers --------------------------------------------
                   1258: #
1.215     foxr     1259: #   By convention each request handler registers itself prior to the sub 
                   1260: #   declaration:
1.214     foxr     1261: #
                   1262: 
1.216     foxr     1263: #++
                   1264: #
1.214     foxr     1265: #  Handles ping requests.
                   1266: #  Parameters:
                   1267: #      $cmd    - the actual keyword that invoked us.
                   1268: #      $tail   - the tail of the request that invoked us.
                   1269: #      $replyfd- File descriptor connected to the client
                   1270: #  Implicit Inputs:
                   1271: #      $currenthostid - Global variable that carries the name of the host we are
                   1272: #                       known as.
                   1273: #  Returns:
                   1274: #      1       - Ok to continue processing.
                   1275: #      0       - Program should exit.
                   1276: #  Side effects:
                   1277: #      Reply information is sent to the client.
                   1278: sub ping_handler {
                   1279:     my ($cmd, $tail, $client) = @_;
                   1280:     Debug("$cmd $tail $client .. $currenthostid:");
                   1281:    
1.387     albertel 1282:     Reply( $client,\$currenthostid,"$cmd:$tail");
1.214     foxr     1283:    
                   1284:     return 1;
                   1285: }
                   1286: &register_handler("ping", \&ping_handler, 0, 1, 1);       # Ping unencoded, client or manager.
                   1287: 
1.216     foxr     1288: #++
1.215     foxr     1289: #
                   1290: # Handles pong requests.  Pong replies with our current host id, and
                   1291: #                         the results of a ping sent to us via our lonc.
                   1292: #
                   1293: # Parameters:
                   1294: #      $cmd    - the actual keyword that invoked us.
                   1295: #      $tail   - the tail of the request that invoked us.
                   1296: #      $replyfd- File descriptor connected to the client
                   1297: #  Implicit Inputs:
                   1298: #      $currenthostid - Global variable that carries the name of the host we are
                   1299: #                       connected to.
                   1300: #  Returns:
                   1301: #      1       - Ok to continue processing.
                   1302: #      0       - Program should exit.
                   1303: #  Side effects:
                   1304: #      Reply information is sent to the client.
                   1305: sub pong_handler {
                   1306:     my ($cmd, $tail, $replyfd) = @_;
                   1307: 
1.365     albertel 1308:     my $reply=&Apache::lonnet::reply("ping",$clientname);
1.215     foxr     1309:     &Reply( $replyfd, "$currenthostid:$reply\n", "$cmd:$tail"); 
                   1310:     return 1;
                   1311: }
                   1312: &register_handler("pong", \&pong_handler, 0, 1, 1);       # Pong unencoded, client or manager
                   1313: 
1.216     foxr     1314: #++
                   1315: #      Called to establish an encrypted session key with the remote client.
                   1316: #      Note that with secure lond, in most cases this function is never
                   1317: #      invoked.  Instead, the secure session key is established either
                   1318: #      via a local file that's locked down tight and only lives for a short
                   1319: #      time, or via an ssl tunnel...and is generated from a bunch-o-random
                   1320: #      bits from /dev/urandom, rather than the predictable pattern used by
                   1321: #      by this sub.  This sub is only used in the old-style insecure
                   1322: #      key negotiation.
                   1323: # Parameters:
                   1324: #      $cmd    - the actual keyword that invoked us.
                   1325: #      $tail   - the tail of the request that invoked us.
                   1326: #      $replyfd- File descriptor connected to the client
                   1327: #  Implicit Inputs:
                   1328: #      $currenthostid - Global variable that carries the name of the host
                   1329: #                       known as.
1.448     raeburn  1330: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.216     foxr     1331: #  Returns:
                   1332: #      1       - Ok to continue processing.
                   1333: #      0       - Program should exit.
                   1334: #  Implicit Outputs:
                   1335: #      Reply information is sent to the client.
                   1336: #      $cipher is set with a reference to a new IDEA encryption object.
                   1337: #
                   1338: sub establish_key_handler {
                   1339:     my ($cmd, $tail, $replyfd) = @_;
                   1340: 
                   1341:     my $buildkey=time.$$.int(rand 100000);
                   1342:     $buildkey=~tr/1-6/A-F/;
                   1343:     $buildkey=int(rand 100000).$buildkey.int(rand 100000);
                   1344:     my $key=$currenthostid.$clientname;
                   1345:     $key=~tr/a-z/A-Z/;
                   1346:     $key=~tr/G-P/0-9/;
                   1347:     $key=~tr/Q-Z/0-9/;
                   1348:     $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
                   1349:     $key=substr($key,0,32);
                   1350:     my $cipherkey=pack("H32",$key);
                   1351:     $cipher=new IDEA $cipherkey;
1.387     albertel 1352:     &Reply($replyfd, \$buildkey, "$cmd:$tail"); 
1.216     foxr     1353:    
                   1354:     return 1;
                   1355: 
                   1356: }
                   1357: &register_handler("ekey", \&establish_key_handler, 0, 1,1);
                   1358: 
1.217     foxr     1359: #     Handler for the load command.  Returns the current system load average
                   1360: #     to the requestor.
                   1361: #
                   1362: # Parameters:
                   1363: #      $cmd    - the actual keyword that invoked us.
                   1364: #      $tail   - the tail of the request that invoked us.
                   1365: #      $replyfd- File descriptor connected to the client
                   1366: #  Implicit Inputs:
                   1367: #      $currenthostid - Global variable that carries the name of the host
                   1368: #                       known as.
1.448     raeburn  1369: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.217     foxr     1370: #  Returns:
                   1371: #      1       - Ok to continue processing.
                   1372: #      0       - Program should exit.
                   1373: #  Side effects:
                   1374: #      Reply information is sent to the client.
                   1375: sub load_handler {
                   1376:     my ($cmd, $tail, $replyfd) = @_;
                   1377: 
1.463     foxr     1378: 
                   1379: 
1.217     foxr     1380:    # Get the load average from /proc/loadavg and calculate it as a percentage of
                   1381:    # the allowed load limit as set by the perl global variable lonLoadLim
                   1382: 
                   1383:     my $loadavg;
                   1384:     my $loadfile=IO::File->new('/proc/loadavg');
                   1385:    
                   1386:     $loadavg=<$loadfile>;
                   1387:     $loadavg =~ s/\s.*//g;                      # Extract the first field only.
                   1388:    
                   1389:     my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
                   1390: 
1.387     albertel 1391:     &Reply( $replyfd, \$loadpercent, "$cmd:$tail");
1.217     foxr     1392:    
                   1393:     return 1;
                   1394: }
1.263     albertel 1395: &register_handler("load", \&load_handler, 0, 1, 0);
1.217     foxr     1396: 
                   1397: #
                   1398: #   Process the userload request.  This sub returns to the client the current
                   1399: #  user load average.  It can be invoked either by clients or managers.
                   1400: #
                   1401: # Parameters:
                   1402: #      $cmd    - the actual keyword that invoked us.
                   1403: #      $tail   - the tail of the request that invoked us.
                   1404: #      $replyfd- File descriptor connected to the client
                   1405: #  Implicit Inputs:
                   1406: #      $currenthostid - Global variable that carries the name of the host
                   1407: #                       known as.
1.448     raeburn  1408: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.217     foxr     1409: #  Returns:
                   1410: #      1       - Ok to continue processing.
                   1411: #      0       - Program should exit
                   1412: # Implicit inputs:
                   1413: #     whatever the userload() function requires.
                   1414: #  Implicit outputs:
                   1415: #     the reply is written to the client.
                   1416: #
                   1417: sub user_load_handler {
                   1418:     my ($cmd, $tail, $replyfd) = @_;
                   1419: 
1.365     albertel 1420:     my $userloadpercent=&Apache::lonnet::userload();
1.387     albertel 1421:     &Reply($replyfd, \$userloadpercent, "$cmd:$tail");
1.217     foxr     1422:     
                   1423:     return 1;
                   1424: }
1.263     albertel 1425: &register_handler("userload", \&user_load_handler, 0, 1, 0);
1.217     foxr     1426: 
1.218     foxr     1427: #   Process a request for the authorization type of a user:
                   1428: #   (userauth).
                   1429: #
                   1430: # Parameters:
                   1431: #      $cmd    - the actual keyword that invoked us.
                   1432: #      $tail   - the tail of the request that invoked us.
                   1433: #      $replyfd- File descriptor connected to the client
                   1434: #  Returns:
                   1435: #      1       - Ok to continue processing.
                   1436: #      0       - Program should exit
                   1437: # Implicit outputs:
                   1438: #    The user authorization type is written to the client.
                   1439: #
                   1440: sub user_authorization_type {
                   1441:     my ($cmd, $tail, $replyfd) = @_;
                   1442:    
                   1443:     my $userinput = "$cmd:$tail";
                   1444:    
                   1445:     #  Pull the domain and username out of the command tail.
1.222     foxr     1446:     # and call get_auth_type to determine the authentication type.
1.218     foxr     1447:    
                   1448:     my ($udom,$uname)=split(/:/,$tail);
1.222     foxr     1449:     my $result = &get_auth_type($udom, $uname);
1.218     foxr     1450:     if($result eq "nouser") {
                   1451: 	&Failure( $replyfd, "unknown_user\n", $userinput);
                   1452:     } else {
                   1453: 	#
1.222     foxr     1454: 	# We only want to pass the second field from get_auth_type
1.218     foxr     1455: 	# for ^krb.. otherwise we'll be handing out the encrypted
                   1456: 	# password for internals e.g.
                   1457: 	#
                   1458: 	my ($type,$otherinfo) = split(/:/,$result);
                   1459: 	if($type =~ /^krb/) {
                   1460: 	    $type = $result;
1.269     raeburn  1461: 	} else {
                   1462:             $type .= ':';
                   1463:         }
1.387     albertel 1464: 	&Reply( $replyfd, \$type, $userinput);
1.218     foxr     1465:     }
                   1466:   
                   1467:     return 1;
                   1468: }
                   1469: &register_handler("currentauth", \&user_authorization_type, 1, 1, 0);
                   1470: 
                   1471: #   Process a request by a manager to push a hosts or domain table 
                   1472: #   to us.  We pick apart the command and pass it on to the subs
                   1473: #   that already exist to do this.
                   1474: #
                   1475: # Parameters:
                   1476: #      $cmd    - the actual keyword that invoked us.
                   1477: #      $tail   - the tail of the request that invoked us.
                   1478: #      $client - File descriptor connected to the client
                   1479: #  Returns:
                   1480: #      1       - Ok to continue processing.
                   1481: #      0       - Program should exit
                   1482: # Implicit Output:
                   1483: #    a reply is written to the client.
                   1484: sub push_file_handler {
                   1485:     my ($cmd, $tail, $client) = @_;
1.412     foxr     1486:     &Debug("In push file handler");
1.218     foxr     1487:     my $userinput = "$cmd:$tail";
                   1488: 
                   1489:     # At this time we only know that the IP of our partner is a valid manager
                   1490:     # the code below is a hook to do further authentication (e.g. to resolve
                   1491:     # spoofing).
                   1492: 
                   1493:     my $cert = &GetCertificate($userinput);
1.412     foxr     1494:     if(&ValidManager($cert)) {
                   1495: 	&Debug("Valid manager: $client");
1.218     foxr     1496: 
                   1497: 	# Now presumably we have the bona fides of both the peer host and the
                   1498: 	# process making the request.
                   1499:       
                   1500: 	my $reply = &PushFile($userinput);
1.387     albertel 1501: 	&Reply($client, \$reply, $userinput);
1.218     foxr     1502: 
                   1503:     } else {
1.412     foxr     1504: 	&logthis("push_file_handler $client is not valid");
1.218     foxr     1505: 	&Failure( $client, "refused\n", $userinput);
                   1506:     } 
1.219     foxr     1507:     return 1;
1.218     foxr     1508: }
                   1509: &register_handler("pushfile", \&push_file_handler, 1, 0, 1);
                   1510: 
1.399     raeburn  1511: # The du_handler routine should be considered obsolete and is retained
                   1512: # for communication with legacy servers.  Please see the du2_handler.
1.243     banghart 1513: #
1.399     raeburn  1514: #   du  - list the disk usage of a directory recursively. 
1.243     banghart 1515: #    
                   1516: #   note: stolen code from the ls file handler
                   1517: #   under construction by Rick Banghart 
                   1518: #    .
                   1519: # Parameters:
                   1520: #    $cmd        - The command that dispatched us (du).
                   1521: #    $ududir     - The directory path to list... I'm not sure what this
                   1522: #                  is relative as things like ls:. return e.g.
                   1523: #                  no_such_dir.
                   1524: #    $client     - Socket open on the client.
                   1525: # Returns:
                   1526: #     1 - indicating that the daemon should not disconnect.
                   1527: # Side Effects:
                   1528: #   The reply is written to  $client.
                   1529: #
                   1530: sub du_handler {
                   1531:     my ($cmd, $ududir, $client) = @_;
1.339     albertel 1532:     ($ududir) = split(/:/,$ududir); # Make 'telnet' testing easier.
1.251     foxr     1533:     my $userinput = "$cmd:$ududir";
                   1534: 
1.245     albertel 1535:     if ($ududir=~/\.\./ || $ududir!~m|^/home/httpd/|) {
                   1536: 	&Failure($client,"refused\n","$cmd:$ududir");
                   1537: 	return 1;
                   1538:     }
1.249     foxr     1539:     #  Since $ududir could have some nasties in it,
                   1540:     #  we will require that ududir is a valid
                   1541:     #  directory.  Just in case someone tries to
                   1542:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
                   1543:     #  etc.
                   1544:     #
                   1545:     if (-d $ududir) {
1.292     albertel 1546: 	my $total_size=0;
                   1547: 	my $code=sub { 
                   1548: 	    if ($_=~/\.\d+\./) { return;} 
                   1549: 	    if ($_=~/\.meta$/) { return;}
1.362     albertel 1550: 	    if (-d $_)         { return;}
1.292     albertel 1551: 	    $total_size+=(stat($_))[7];
                   1552: 	};
1.295     raeburn  1553: 	chdir($ududir);
1.292     albertel 1554: 	find($code,$ududir);
                   1555: 	$total_size=int($total_size/1024);
1.387     albertel 1556: 	&Reply($client,\$total_size,"$cmd:$ududir");
1.249     foxr     1557:     } else {
1.251     foxr     1558: 	&Failure($client, "bad_directory:$ududir\n","$cmd:$ududir"); 
1.249     foxr     1559:     }
1.243     banghart 1560:     return 1;
                   1561: }
                   1562: &register_handler("du", \&du_handler, 0, 1, 0);
1.218     foxr     1563: 
1.399     raeburn  1564: # Please also see the du_handler, which is obsoleted by du2. 
                   1565: # du2_handler differs from du_handler in that required path to directory
                   1566: # provided by &propath() is prepended in the handler instead of on the 
                   1567: # client side.
1.239     foxr     1568: #
1.399     raeburn  1569: #   du2  - list the disk usage of a directory recursively.
                   1570: #
                   1571: # Parameters:
                   1572: #    $cmd        - The command that dispatched us (du).
                   1573: #    $tail       - The tail of the request that invoked us.
                   1574: #                  $tail is a : separated list of the following:
                   1575: #                   - $ududir - directory path to list (before prepending)
                   1576: #                   - $getpropath = 1 if &propath() should prepend
                   1577: #                   - $uname - username to use for &propath or user dir
                   1578: #                   - $udom - domain to use for &propath or user dir
                   1579: #                   All are escaped.
                   1580: #    $client     - Socket open on the client.
                   1581: # Returns:
                   1582: #     1 - indicating that the daemon should not disconnect.
                   1583: # Side Effects:
                   1584: #   The reply is written to $client.
                   1585: #
                   1586: 
                   1587: sub du2_handler {
                   1588:     my ($cmd, $tail, $client) = @_;
                   1589:     my ($ududir,$getpropath,$uname,$udom) = map { &unescape($_) } (split(/:/, $tail));
                   1590:     my $userinput = "$cmd:$tail";
                   1591:     if (($ududir=~/\.\./) || (($ududir!~m|^/home/httpd/|) && (!$getpropath))) {
                   1592:         &Failure($client,"refused\n","$cmd:$tail");
                   1593:         return 1;
                   1594:     }
                   1595:     if ($getpropath) {
                   1596:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
                   1597:             $ududir = &propath($udom,$uname).'/'.$ududir;
                   1598:         } else {
                   1599:             &Failure($client,"refused\n","$cmd:$tail");
                   1600:             return 1;
                   1601:         }
                   1602:     }
                   1603:     #  Since $ududir could have some nasties in it,
                   1604:     #  we will require that ududir is a valid
                   1605:     #  directory.  Just in case someone tries to
                   1606:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
                   1607:     #  etc.
                   1608:     #
                   1609:     if (-d $ududir) {
                   1610:         my $total_size=0;
                   1611:         my $code=sub {
                   1612:             if ($_=~/\.\d+\./) { return;}
                   1613:             if ($_=~/\.meta$/) { return;}
                   1614:             if (-d $_)         { return;}
                   1615:             $total_size+=(stat($_))[7];
                   1616:         };
                   1617:         chdir($ududir);
                   1618:         find($code,$ududir);
                   1619:         $total_size=int($total_size/1024);
                   1620:         &Reply($client,\$total_size,"$cmd:$ududir");
                   1621:     } else {
                   1622:         &Failure($client, "bad_directory:$ududir\n","$cmd:$tail");
                   1623:     }
                   1624:     return 1;
                   1625: }
                   1626: &register_handler("du2", \&du2_handler, 0, 1, 0);
                   1627: 
                   1628: #
                   1629: # The ls_handler routine should be considered obsolete and is retained
                   1630: # for communication with legacy servers.  Please see the ls3_handler.
1.280     matthew  1631: #
1.239     foxr     1632: #   ls  - list the contents of a directory.  For each file in the
                   1633: #    selected directory the filename followed by the full output of
                   1634: #    the stat function is returned.  The returned info for each
                   1635: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1636: #
                   1637: #    If the requested path contains /../ or is:
                   1638: #
                   1639: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1640: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1641: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1642: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
                   1643: #    or is:
                   1644: #
1.538     raeburn  1645: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1646: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1647: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1648: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
1.529     raeburn  1649: #
                   1650: #    the response will be "refused".
                   1651: #
1.239     foxr     1652: # Parameters:
                   1653: #    $cmd        - The command that dispatched us (ls).
                   1654: #    $ulsdir     - The directory path to list... I'm not sure what this
                   1655: #                  is relative as things like ls:. return e.g.
                   1656: #                  no_such_dir.
                   1657: #    $client     - Socket open on the client.
                   1658: # Returns:
                   1659: #     1 - indicating that the daemon should not disconnect.
                   1660: # Side Effects:
                   1661: #   The reply is written to  $client.
                   1662: #
                   1663: sub ls_handler {
1.280     matthew  1664:     # obsoleted by ls2_handler
1.239     foxr     1665:     my ($cmd, $ulsdir, $client) = @_;
                   1666: 
                   1667:     my $userinput = "$cmd:$ulsdir";
                   1668: 
                   1669:     my $obs;
                   1670:     my $rights;
                   1671:     my $ulsout='';
                   1672:     my $ulsfn;
1.529     raeburn  1673:     if ($ulsdir =~m{/\.\./}) {
                   1674:         &Failure($client,"refused\n",$userinput);
                   1675:         return 1;
                   1676:     }
1.239     foxr     1677:     if (-e $ulsdir) {
                   1678: 	if(-d $ulsdir) {
1.539     raeburn  1679:             unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1680:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
1.529     raeburn  1681:                 &Failure($client,"refused\n",$userinput);
                   1682:                 return 1;
                   1683:             }
1.239     foxr     1684: 	    if (opendir(LSDIR,$ulsdir)) {
                   1685: 		while ($ulsfn=readdir(LSDIR)) {
1.291     albertel 1686: 		    undef($obs);
                   1687: 		    undef($rights); 
1.239     foxr     1688: 		    my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1689: 		    #We do some obsolete checking here
                   1690: 		    if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   1691: 			open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1692: 			my @obsolete=<FILE>;
                   1693: 			foreach my $obsolete (@obsolete) {
1.301     www      1694: 			    if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
1.239     foxr     1695: 			    if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
                   1696: 			}
                   1697: 		    }
                   1698: 		    $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
                   1699: 		    if($obs eq '1') { $ulsout.="&1"; }
                   1700: 		    else { $ulsout.="&0"; }
                   1701: 		    if($rights eq '1') { $ulsout.="&1:"; }
                   1702: 		    else { $ulsout.="&0:"; }
                   1703: 		}
                   1704: 		closedir(LSDIR);
                   1705: 	    }
                   1706: 	} else {
1.539     raeburn  1707:             unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1708:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
1.529     raeburn  1709:                 &Failure($client,"refused\n",$userinput);
                   1710:                 return 1;
                   1711:             }
1.239     foxr     1712: 	    my @ulsstats=stat($ulsdir);
                   1713: 	    $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1714: 	}
                   1715:     } else {
                   1716: 	$ulsout='no_such_dir';
                   1717:     }
                   1718:     if ($ulsout eq '') { $ulsout='empty'; }
1.387     albertel 1719:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1.239     foxr     1720:     
                   1721:     return 1;
                   1722: 
                   1723: }
                   1724: &register_handler("ls", \&ls_handler, 0, 1, 0);
                   1725: 
1.399     raeburn  1726: # The ls2_handler routine should be considered obsolete and is retained
                   1727: # for communication with legacy servers.  Please see the ls3_handler.
                   1728: # Please also see the ls_handler, which was itself obsoleted by ls2.
1.280     matthew  1729: # ls2_handler differs from ls_handler in that it escapes its return 
                   1730: # values before concatenating them together with ':'s.
                   1731: #
                   1732: #   ls2  - list the contents of a directory.  For each file in the
                   1733: #    selected directory the filename followed by the full output of
                   1734: #    the stat function is returned.  The returned info for each
                   1735: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1736: #
                   1737: #    If the requested path contains /../ or is:
                   1738: #
                   1739: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1740: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1741: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1742: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
                   1743: #    or is:
                   1744: #
1.538     raeburn  1745: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1746: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1747: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1748: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
1.529     raeburn  1749: #
                   1750: #    the response will be "refused".
                   1751: #
1.280     matthew  1752: # Parameters:
                   1753: #    $cmd        - The command that dispatched us (ls).
                   1754: #    $ulsdir     - The directory path to list... I'm not sure what this
                   1755: #                  is relative as things like ls:. return e.g.
                   1756: #                  no_such_dir.
                   1757: #    $client     - Socket open on the client.
                   1758: # Returns:
                   1759: #     1 - indicating that the daemon should not disconnect.
                   1760: # Side Effects:
                   1761: #   The reply is written to  $client.
                   1762: #
                   1763: sub ls2_handler {
                   1764:     my ($cmd, $ulsdir, $client) = @_;
                   1765: 
                   1766:     my $userinput = "$cmd:$ulsdir";
                   1767: 
                   1768:     my $obs;
                   1769:     my $rights;
                   1770:     my $ulsout='';
                   1771:     my $ulsfn;
1.529     raeburn  1772:     if ($ulsdir =~m{/\.\./}) {
                   1773:         &Failure($client,"refused\n",$userinput);
                   1774:         return 1;
                   1775:     }
1.280     matthew  1776:     if (-e $ulsdir) {
                   1777:         if(-d $ulsdir) {
1.539     raeburn  1778:             unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1779:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
1.529     raeburn  1780:                 &Failure($client,"refused\n","$userinput");
                   1781:                 return 1;
                   1782:             }
1.280     matthew  1783:             if (opendir(LSDIR,$ulsdir)) {
                   1784:                 while ($ulsfn=readdir(LSDIR)) {
1.291     albertel 1785:                     undef($obs);
                   1786: 		    undef($rights); 
1.280     matthew  1787:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1788:                     #We do some obsolete checking here
                   1789:                     if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   1790:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1791:                         my @obsolete=<FILE>;
                   1792:                         foreach my $obsolete (@obsolete) {
1.301     www      1793:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
1.280     matthew  1794:                             if($obsolete =~ m|(<copyright>)(default)|) {
                   1795:                                 $rights = 1;
                   1796:                             }
                   1797:                         }
                   1798:                     }
                   1799:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
                   1800:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1801:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1802:                     $ulsout.= &escape($tmp).':';
                   1803:                 }
                   1804:                 closedir(LSDIR);
                   1805:             }
                   1806:         } else {
1.539     raeburn  1807:             unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1808:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
1.529     raeburn  1809:                 &Failure($client,"refused\n",$userinput);
                   1810:                 return 1;
                   1811:             }
1.280     matthew  1812:             my @ulsstats=stat($ulsdir);
                   1813:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1814:         }
                   1815:     } else {
                   1816:         $ulsout='no_such_dir';
                   1817:    }
                   1818:    if ($ulsout eq '') { $ulsout='empty'; }
1.387     albertel 1819:    &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1.280     matthew  1820:    return 1;
                   1821: }
                   1822: &register_handler("ls2", \&ls2_handler, 0, 1, 0);
1.399     raeburn  1823: #
                   1824: #   ls3  - list the contents of a directory.  For each file in the
                   1825: #    selected directory the filename followed by the full output of
                   1826: #    the stat function is returned.  The returned info for each
                   1827: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1828: #
                   1829: #    If the requested path (after prepending) contains /../ or is:
                   1830: #
                   1831: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1832: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1833: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1834: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
1.539     raeburn  1835: #        (d) /home/httpd/html/priv/<domain> and client is the homeserver
1.529     raeburn  1836: #
1.530     raeburn  1837: #    or is:
1.529     raeburn  1838: #
1.538     raeburn  1839: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1840: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1841: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1842: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
                   1843: #        (d) /home/httpd/html/priv/<domain>/<username>/ and client is the homeserver
1.529     raeburn  1844: #
                   1845: #    the response will be "refused".
                   1846: #
1.399     raeburn  1847: # Parameters:
                   1848: #    $cmd        - The command that dispatched us (ls).
                   1849: #    $tail       - The tail of the request that invoked us.
                   1850: #                  $tail is a : separated list of the following:
                   1851: #                   - $ulsdir - directory path to list (before prepending)
                   1852: #                   - $getpropath = 1 if &propath() should prepend
                   1853: #                   - $getuserdir = 1 if path to user dir in lonUsers should
                   1854: #                                     prepend
                   1855: #                   - $alternate_root - path to prepend
                   1856: #                   - $uname - username to use for &propath or user dir
                   1857: #                   - $udom - domain to use for &propath or user dir
                   1858: #            All of these except $getpropath and &getuserdir are escaped.    
                   1859: #                  no_such_dir.
                   1860: #    $client     - Socket open on the client.
                   1861: # Returns:
                   1862: #     1 - indicating that the daemon should not disconnect.
                   1863: # Side Effects:
                   1864: #   The reply is written to $client.
                   1865: #
                   1866: 
                   1867: sub ls3_handler {
                   1868:     my ($cmd, $tail, $client) = @_;
                   1869:     my $userinput = "$cmd:$tail";
                   1870:     my ($ulsdir,$getpropath,$getuserdir,$alternate_root,$uname,$udom) =
                   1871:         split(/:/,$tail);
                   1872:     if (defined($ulsdir)) {
                   1873:         $ulsdir = &unescape($ulsdir);
                   1874:     }
                   1875:     if (defined($alternate_root)) {
                   1876:         $alternate_root = &unescape($alternate_root);
                   1877:     }
                   1878:     if (defined($uname)) {
                   1879:         $uname = &unescape($uname);
                   1880:     }
                   1881:     if (defined($udom)) {
                   1882:         $udom = &unescape($udom);
                   1883:     }
                   1884: 
                   1885:     my $dir_root = $perlvar{'lonDocRoot'};
1.529     raeburn  1886:     if (($getpropath) || ($getuserdir)) {
1.399     raeburn  1887:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
                   1888:             $dir_root = &propath($udom,$uname);
                   1889:             $dir_root =~ s/\/$//;
                   1890:         } else {
1.529     raeburn  1891:             &Failure($client,"refused\n",$userinput);
1.399     raeburn  1892:             return 1;
                   1893:         }
1.400     raeburn  1894:     } elsif ($alternate_root ne '') {
1.399     raeburn  1895:         $dir_root = $alternate_root;
                   1896:     }
1.408     raeburn  1897:     if (($dir_root ne '') && ($dir_root ne '/')) {
1.400     raeburn  1898:         if ($ulsdir =~ /^\//) {
                   1899:             $ulsdir = $dir_root.$ulsdir;
                   1900:         } else {
                   1901:             $ulsdir = $dir_root.'/'.$ulsdir;
                   1902:         }
1.399     raeburn  1903:     }
1.529     raeburn  1904:     if ($ulsdir =~m{/\.\./}) {
                   1905:         &Failure($client,"refused\n",$userinput);
                   1906:         return 1;
                   1907:     }
                   1908:     my $islocal;
                   1909:     my @machine_ids = &Apache::lonnet::current_machine_ids();
                   1910:     if (grep(/^\Q$clientname\E$/,@machine_ids)) {
                   1911:         $islocal = 1;
                   1912:     }
1.399     raeburn  1913:     my $obs;
                   1914:     my $rights;
                   1915:     my $ulsout='';
                   1916:     my $ulsfn;
1.547     raeburn  1917: 
                   1918:     my ($crscheck,$toplevel,$currdom,$currnum,$skip);
                   1919:     unless ($islocal) {
                   1920:         my ($major,$minor) = split(/\./,$clientversion);
                   1921:         if (($major < 2) || ($major == 2 && $minor < 12)) {
                   1922:             $crscheck = 1;
                   1923:         }
                   1924:     }
1.399     raeburn  1925:     if (-e $ulsdir) {
                   1926:         if(-d $ulsdir) {
1.529     raeburn  1927:             unless (($getpropath) || ($getuserdir) ||
1.539     raeburn  1928:                     ($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1929:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles}) ||
                   1930:                     (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain}) && ($islocal))) {
1.529     raeburn  1931:                 &Failure($client,"refused\n",$userinput);
                   1932:                 return 1;
                   1933:             }
1.547     raeburn  1934:             if (($crscheck) &&
                   1935:                 ($ulsdir =~ m{^/home/httpd/html/res/($LONCAPA::match_domain)(/?$|/$LONCAPA::match_courseid)})) {
                   1936:                 ($currdom,my $posscnum) = ($1,$2);
                   1937:                 if (($posscnum eq '') || ($posscnum eq '/')) {
                   1938:                     $toplevel = 1;
                   1939:                 } else {
                   1940:                     $posscnum =~ s{^/+}{};
                   1941:                     if (&LONCAPA::Lond::is_course($currdom,$posscnum)) {
                   1942:                         $skip = 1;
                   1943:                     }
                   1944:                 }
                   1945:             }
                   1946:             if ((!$skip) && (opendir(LSDIR,$ulsdir))) {
1.399     raeburn  1947:                 while ($ulsfn=readdir(LSDIR)) {
1.547     raeburn  1948:                     if (($crscheck) && ($toplevel) && ($currdom ne '') &&
                   1949:                         ($ulsfn =~ /^$LONCAPA::match_courseid$/) && (-d "$ulsdir/$ulsfn")) {
                   1950:                         if (&LONCAPA::Lond::is_course($currdom,$ulsfn)) {
                   1951:                             next;
                   1952:                         }
                   1953:                     }
1.399     raeburn  1954:                     undef($obs);
                   1955:                     undef($rights);
                   1956:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1957:                     #We do some obsolete checking here
                   1958:                     if(-e $ulsdir.'/'.$ulsfn.".meta") {
                   1959:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1960:                         my @obsolete=<FILE>;
                   1961:                         foreach my $obsolete (@obsolete) {
                   1962:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; }
                   1963:                             if($obsolete =~ m|(<copyright>)(default)|) {
                   1964:                                 $rights = 1;
                   1965:                             }
                   1966:                         }
                   1967:                     }
                   1968:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
                   1969:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1970:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1971:                     $ulsout.= &escape($tmp).':';
                   1972:                 }
                   1973:                 closedir(LSDIR);
                   1974:             }
                   1975:         } else {
1.529     raeburn  1976:             unless (($getpropath) || ($getuserdir) ||
1.539     raeburn  1977:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1978:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/}) ||
                   1979:                     (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain/$LONCAPA::match_name/}) && ($islocal))) {
1.529     raeburn  1980:                 &Failure($client,"refused\n",$userinput);
                   1981:                 return 1;
                   1982:             }
1.399     raeburn  1983:             my @ulsstats=stat($ulsdir);
                   1984:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1985:         }
                   1986:     } else {
                   1987:         $ulsout='no_such_dir';
1.400     raeburn  1988:     }
                   1989:     if ($ulsout eq '') { $ulsout='empty'; }
                   1990:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
                   1991:     return 1;
1.399     raeburn  1992: }
                   1993: &register_handler("ls3", \&ls3_handler, 0, 1, 0);
1.280     matthew  1994: 
1.477     raeburn  1995: sub read_lonnet_global {
                   1996:     my ($cmd,$tail,$client) = @_;
                   1997:     my $userinput = "$cmd:$tail";
                   1998:     my $requested = &Apache::lonnet::thaw_unescape($tail);
                   1999:     my $result;
1.480     raeburn  2000:     my %packagevars = (
                   2001:                         spareid => \%Apache::lonnet::spareid,
                   2002:                         perlvar => \%Apache::lonnet::perlvar,
                   2003:                       );
                   2004:     my %limit_to = (
                   2005:                     perlvar => {
1.531     raeburn  2006:                                  lonOtherAuthen  => 1,
                   2007:                                  lonBalancer     => 1,
                   2008:                                  lonVersion      => 1,
                   2009:                                  lonAdmEMail     => 1,
                   2010:                                  lonSupportEMail => 1,  
                   2011:                                  lonSysEMail     => 1,
                   2012:                                  lonHostID       => 1,
                   2013:                                  lonRole         => 1,
                   2014:                                  lonDefDomain    => 1,
                   2015:                                  lonLoadLim      => 1,
                   2016:                                  lonUserLoadLim  => 1,
1.480     raeburn  2017:                                }
                   2018:                   );
1.477     raeburn  2019:     if (ref($requested) eq 'HASH') {
                   2020:         foreach my $what (keys(%{$requested})) {
                   2021:             my $response;
1.480     raeburn  2022:             my $items = {};
                   2023:             if (exists($packagevars{$what})) {
                   2024:                 if (ref($limit_to{$what}) eq 'HASH') {
                   2025:                     foreach my $varname (keys(%{$packagevars{$what}})) {
                   2026:                         if ($limit_to{$what}{$varname}) {
                   2027:                             $items->{$varname} = $packagevars{$what}{$varname};
                   2028:                         }
                   2029:                     }
                   2030:                 } else {
                   2031:                     $items = $packagevars{$what};
1.477     raeburn  2032:                 }
1.480     raeburn  2033:                 if ($what eq 'perlvar') {
                   2034:                     if (!exists($packagevars{$what}{'lonBalancer'})) {
1.559     raeburn  2035:                         if ($dist =~ /^(centos|rhes|fedora|scientific|oracle)/) {
1.480     raeburn  2036:                             my $othervarref=LONCAPA::Configuration::read_conf('httpd.conf');
                   2037:                             if (ref($othervarref) eq 'HASH') {
                   2038:                                 $items->{'lonBalancer'} = $othervarref->{'lonBalancer'};
                   2039:                             }
                   2040:                         }
                   2041:                     }
1.477     raeburn  2042:                 }
1.480     raeburn  2043:                 $response = &Apache::lonnet::freeze_escape($items);
1.477     raeburn  2044:             }
1.478     raeburn  2045:             $result .= &escape($what).'='.$response.'&';
1.477     raeburn  2046:         }
                   2047:     }
                   2048:     $result =~ s/\&$//;
                   2049:     &Reply($client,\$result,$userinput);
                   2050:     return 1;
                   2051: }
                   2052: &register_handler("readlonnetglobal", \&read_lonnet_global, 0, 1, 0);
                   2053: 
1.479     raeburn  2054: sub server_devalidatecache_handler {
                   2055:     my ($cmd,$tail,$client) = @_;
                   2056:     my $userinput = "$cmd:$tail";
1.503     raeburn  2057:     my $items = &unescape($tail);
                   2058:     my @cached = split(/\&/,$items);
                   2059:     foreach my $key (@cached) {
                   2060:         if ($key =~ /:/) {
                   2061:             my ($name,$id) = map { &unescape($_); } split(/:/,$key);
                   2062:             &Apache::lonnet::devalidate_cache_new($name,$id);
                   2063:         }
                   2064:     }
1.479     raeburn  2065:     my $result = 'ok';
                   2066:     &Reply($client,\$result,$userinput);
                   2067:     return 1;
                   2068: }
1.481     raeburn  2069: &register_handler("devalidatecache", \&server_devalidatecache_handler, 0, 1, 0);
1.479     raeburn  2070: 
1.410     raeburn  2071: sub server_timezone_handler {
                   2072:     my ($cmd,$tail,$client) = @_;
                   2073:     my $userinput = "$cmd:$tail";
                   2074:     my $timezone;
                   2075:     my $clockfile = '/etc/sysconfig/clock'; # Fedora/CentOS/SuSE
                   2076:     my $tzfile = '/etc/timezone'; # Debian/Ubuntu
                   2077:     if (-e $clockfile) {
                   2078:         if (open(my $fh,"<$clockfile")) {
                   2079:             while (<$fh>) {
                   2080:                 next if (/^[\#\s]/);
                   2081:                 if (/^(?:TIME)?ZONE\s*=\s*['"]?\s*([\w\/]+)/) {
                   2082:                     $timezone = $1;
                   2083:                     last;
                   2084:                 }
                   2085:             }
                   2086:             close($fh);
                   2087:         }
                   2088:     } elsif (-e $tzfile) {
                   2089:         if (open(my $fh,"<$tzfile")) {
                   2090:             $timezone = <$fh>;
                   2091:             close($fh);
                   2092:             chomp($timezone);
                   2093:             if ($timezone =~ m{^Etc/(\w+)$}) {
                   2094:                 $timezone = $1;
                   2095:             }
                   2096:         }
                   2097:     }
                   2098:     &Reply($client,\$timezone,$userinput); # This supports debug logging.
                   2099:     return 1;
                   2100: }
                   2101: &register_handler("servertimezone", \&server_timezone_handler, 0, 1, 0);
                   2102: 
1.413     raeburn  2103: sub server_loncaparev_handler {
                   2104:     my ($cmd,$tail,$client) = @_;
                   2105:     my $userinput = "$cmd:$tail";
                   2106:     &Reply($client,\$perlvar{'lonVersion'},$userinput);
                   2107:     return 1;
                   2108: }
                   2109: &register_handler("serverloncaparev", \&server_loncaparev_handler, 0, 1, 0);
                   2110: 
1.448     raeburn  2111: sub server_homeID_handler {
                   2112:     my ($cmd,$tail,$client) = @_;
                   2113:     my $userinput = "$cmd:$tail";
                   2114:     &Reply($client,\$perlvar{'lonHostID'},$userinput);
                   2115:     return 1;
                   2116: }
                   2117: &register_handler("serverhomeID", \&server_homeID_handler, 0, 1, 0);
                   2118: 
1.471     raeburn  2119: sub server_distarch_handler {
                   2120:     my ($cmd,$tail,$client) = @_;
                   2121:     my $userinput = "$cmd:$tail";
                   2122:     my $reply = &distro_and_arch();
                   2123:     &Reply($client,\$reply,$userinput);
                   2124:     return 1;
                   2125: }
                   2126: &register_handler("serverdistarch", \&server_distarch_handler, 0, 1, 0);
                   2127: 
1.523     raeburn  2128: sub server_certs_handler {
                   2129:     my ($cmd,$tail,$client) = @_;
                   2130:     my $userinput = "$cmd:$tail";
1.548     raeburn  2131:     my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
                   2132:     my $result = &LONCAPA::Lond::server_certs(\%perlvar,$perlvar{'lonHostID'},$hostname);
1.523     raeburn  2133:     &Reply($client,\$result,$userinput);
                   2134:     return;
                   2135: }
                   2136: &register_handler("servercerts", \&server_certs_handler, 0, 1, 0);
                   2137: 
1.218     foxr     2138: #   Process a reinit request.  Reinit requests that either
                   2139: #   lonc or lond be reinitialized so that an updated 
                   2140: #   host.tab or domain.tab can be processed.
                   2141: #
                   2142: # Parameters:
                   2143: #      $cmd    - the actual keyword that invoked us.
                   2144: #      $tail   - the tail of the request that invoked us.
                   2145: #      $client - File descriptor connected to the client
                   2146: #  Returns:
                   2147: #      1       - Ok to continue processing.
                   2148: #      0       - Program should exit
                   2149: #  Implicit output:
                   2150: #     a reply is sent to the client.
                   2151: #
                   2152: sub reinit_process_handler {
                   2153:     my ($cmd, $tail, $client) = @_;
                   2154:    
                   2155:     my $userinput = "$cmd:$tail";
                   2156:    
                   2157:     my $cert = &GetCertificate($userinput);
                   2158:     if(&ValidManager($cert)) {
                   2159: 	chomp($userinput);
                   2160: 	my $reply = &ReinitProcess($userinput);
1.387     albertel 2161: 	&Reply( $client,  \$reply, $userinput);
1.218     foxr     2162:     } else {
                   2163: 	&Failure( $client, "refused\n", $userinput);
                   2164:     }
                   2165:     return 1;
                   2166: }
                   2167: &register_handler("reinit", \&reinit_process_handler, 1, 0, 1);
                   2168: 
                   2169: #  Process the editing script for a table edit operation.
                   2170: #  the editing operation must be encrypted and requested by
                   2171: #  a manager host.
                   2172: #
                   2173: # Parameters:
                   2174: #      $cmd    - the actual keyword that invoked us.
                   2175: #      $tail   - the tail of the request that invoked us.
                   2176: #      $client - File descriptor connected to the client
                   2177: #  Returns:
                   2178: #      1       - Ok to continue processing.
                   2179: #      0       - Program should exit
                   2180: #  Implicit output:
                   2181: #     a reply is sent to the client.
                   2182: #
                   2183: sub edit_table_handler {
                   2184:     my ($command, $tail, $client) = @_;
                   2185:    
                   2186:     my $userinput = "$command:$tail";
                   2187: 
                   2188:     my $cert = &GetCertificate($userinput);
                   2189:     if(&ValidManager($cert)) {
                   2190: 	my($filetype, $script) = split(/:/, $tail);
                   2191: 	if (($filetype eq "hosts") || 
                   2192: 	    ($filetype eq "domain")) {
                   2193: 	    if($script ne "") {
                   2194: 		&Reply($client,              # BUGBUG - EditFile
                   2195: 		      &EditFile($userinput), #   could fail.
                   2196: 		      $userinput);
                   2197: 	    } else {
                   2198: 		&Failure($client,"refused\n",$userinput);
                   2199: 	    }
                   2200: 	} else {
                   2201: 	    &Failure($client,"refused\n",$userinput);
                   2202: 	}
                   2203:     } else {
                   2204: 	&Failure($client,"refused\n",$userinput);
                   2205:     }
                   2206:     return 1;
                   2207: }
1.263     albertel 2208: &register_handler("edit", \&edit_table_handler, 1, 0, 1);
1.218     foxr     2209: 
1.220     foxr     2210: #
                   2211: #   Authenticate a user against the LonCAPA authentication
                   2212: #   database.  Note that there are several authentication
                   2213: #   possibilities:
                   2214: #   - unix     - The user can be authenticated against the unix
                   2215: #                password file.
                   2216: #   - internal - The user can be authenticated against a purely 
                   2217: #                internal per user password file.
                   2218: #   - kerberos - The user can be authenticated against either a kerb4 or kerb5
                   2219: #                ticket granting authority.
                   2220: #   - user     - The person tailoring LonCAPA can supply a user authentication
                   2221: #                mechanism that is per system.
                   2222: #
                   2223: # Parameters:
                   2224: #    $cmd      - The command that got us here.
                   2225: #    $tail     - Tail of the command (remaining parameters).
                   2226: #    $client   - File descriptor connected to client.
                   2227: # Returns
                   2228: #     0        - Requested to exit, caller should shut down.
                   2229: #     1        - Continue processing.
                   2230: # Implicit inputs:
                   2231: #    The authentication systems describe above have their own forms of implicit
                   2232: #    input into the authentication process that are described above.
                   2233: #
                   2234: sub authenticate_handler {
                   2235:     my ($cmd, $tail, $client) = @_;
                   2236: 
                   2237:     
                   2238:     #  Regenerate the full input line 
                   2239:     
                   2240:     my $userinput  = $cmd.":".$tail;
                   2241:     
                   2242:     #  udom    - User's domain.
                   2243:     #  uname   - Username.
                   2244:     #  upass   - User's password.
1.396     raeburn  2245:     #  checkdefauth - Pass to validate_user() to try authentication
                   2246:     #                 with default auth type(s) if no user account.
1.447     raeburn  2247:     #  clientcancheckhost - Passed by clients with functionality in lonauth.pm
                   2248:     #                       to check if session can be hosted.
1.220     foxr     2249:     
1.447     raeburn  2250:     my ($udom, $uname, $upass, $checkdefauth, $clientcancheckhost)=split(/:/,$tail);
1.399     raeburn  2251:     &Debug(" Authenticate domain = $udom, user = $uname, password = $upass,  checkdefauth = $checkdefauth");
1.220     foxr     2252:     chomp($upass);
                   2253:     $upass=&unescape($upass);
                   2254: 
1.396     raeburn  2255:     my $pwdcorrect = &validate_user($udom,$uname,$upass,$checkdefauth);
1.220     foxr     2256:     if($pwdcorrect) {
1.447     raeburn  2257:         my $canhost = 1;
                   2258:         unless ($clientcancheckhost) {
1.448     raeburn  2259:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   2260:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.452     raeburn  2261:             my @intdoms;
                   2262:             my $internet_names = &Apache::lonnet::get_internet_names($clientname);
                   2263:             if (ref($internet_names) eq 'ARRAY') {
                   2264:                 @intdoms = @{$internet_names};
                   2265:             }
1.448     raeburn  2266:             unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
1.447     raeburn  2267:                 my ($remote,$hosted);
                   2268:                 my $remotesession = &get_usersession_config($udom,'remotesession');
                   2269:                 if (ref($remotesession) eq 'HASH') {
1.525     raeburn  2270:                     $remote = $remotesession->{'remote'};
1.447     raeburn  2271:                 }
1.448     raeburn  2272:                 my $hostedsession = &get_usersession_config($clienthomedom,'hostedsession');
1.447     raeburn  2273:                 if (ref($hostedsession) eq 'HASH') {
                   2274:                     $hosted = $hostedsession->{'hosted'};
                   2275:                 }
1.448     raeburn  2276:                 $canhost = &Apache::lonnet::can_host_session($udom,$clientname,
1.492     droeschl 2277:                                                              $clientversion,
1.447     raeburn  2278:                                                              $remote,$hosted);
                   2279:             }
                   2280:         }
                   2281:         if ($canhost) {               
                   2282:             &Reply( $client, "authorized\n", $userinput);
                   2283:         } else {
                   2284:             &Reply( $client, "not_allowed_to_host\n", $userinput);
                   2285:         }
1.220     foxr     2286: 	#
                   2287: 	#  Bad credentials: Failed to authorize
                   2288: 	#
                   2289:     } else {
                   2290: 	&Failure( $client, "non_authorized\n", $userinput);
                   2291:     }
                   2292: 
                   2293:     return 1;
                   2294: }
1.263     albertel 2295: &register_handler("auth", \&authenticate_handler, 1, 1, 0);
1.214     foxr     2296: 
1.222     foxr     2297: #
                   2298: #   Change a user's password.  Note that this function is complicated by
                   2299: #   the fact that a user may be authenticated in more than one way:
                   2300: #   At present, we are not able to change the password for all types of
                   2301: #   authentication methods.  Only for:
                   2302: #      unix    - unix password or shadow passoword style authentication.
                   2303: #      local   - Locally written authentication mechanism.
                   2304: #   For now, kerb4 and kerb5 password changes are not supported and result
                   2305: #   in an error.
                   2306: # FUTURE WORK:
                   2307: #    Support kerberos passwd changes?
                   2308: # Parameters:
                   2309: #    $cmd      - The command that got us here.
                   2310: #    $tail     - Tail of the command (remaining parameters).
                   2311: #    $client   - File descriptor connected to client.
                   2312: # Returns
                   2313: #     0        - Requested to exit, caller should shut down.
                   2314: #     1        - Continue processing.
                   2315: # Implicit inputs:
                   2316: #    The authentication systems describe above have their own forms of implicit
                   2317: #    input into the authentication process that are described above.
                   2318: sub change_password_handler {
                   2319:     my ($cmd, $tail, $client) = @_;
                   2320: 
                   2321:     my $userinput = $cmd.":".$tail;           # Reconstruct client's string.
                   2322: 
                   2323:     #
                   2324:     #  udom  - user's domain.
                   2325:     #  uname - Username.
                   2326:     #  upass - Current password.
                   2327:     #  npass - New password.
1.346     raeburn  2328:     #  context - Context in which this was called 
                   2329:     #            (preferences or reset_by_email).
1.428     raeburn  2330:     #  lonhost - HostID of server where request originated 
1.222     foxr     2331:    
1.428     raeburn  2332:     my ($udom,$uname,$upass,$npass,$context,$lonhost)=split(/:/,$tail);
1.222     foxr     2333: 
                   2334:     $upass=&unescape($upass);
                   2335:     $npass=&unescape($npass);
                   2336:     &Debug("Trying to change password for $uname");
                   2337: 
                   2338:     # First require that the user can be authenticated with their
1.346     raeburn  2339:     # old password unless context was 'reset_by_email':
                   2340:     
1.428     raeburn  2341:     my ($validated,$failure);
1.346     raeburn  2342:     if ($context eq 'reset_by_email') {
1.428     raeburn  2343:         if ($lonhost eq '') {
                   2344:             $failure = 'invalid_client';
                   2345:         } else {
                   2346:             $validated = 1;
                   2347:         }
1.346     raeburn  2348:     } else {
                   2349:         $validated = &validate_user($udom, $uname, $upass);
                   2350:     }
1.222     foxr     2351:     if($validated) {
                   2352: 	my $realpasswd  = &get_auth_type($udom, $uname); # Defined since authd.
                   2353: 	my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
1.558     raeburn  2354:         my $notunique;
1.222     foxr     2355: 	if ($howpwd eq 'internal') {
                   2356: 	    &Debug("internal auth");
1.518     raeburn  2357:             my $ncpass = &hash_passwd($udom,$npass);
1.558     raeburn  2358:             my (undef,$method,@rest) = split(/!/,$contentpwd);
                   2359:             if ($method eq 'bcrypt') {
                   2360:                 my %passwdconf = &Apache::lonnet::get_passwdconf($udom);
                   2361:                 if (($passwdconf{'numsaved'}) && ($passwdconf{'numsaved'} =~ /^\d+$/)) {
                   2362:                     my @oldpasswds;
                   2363:                     my $userpath = &propath($udom,$uname);
                   2364:                     my $fullpath = $userpath.'/oldpasswds';
                   2365:                     if (-d $userpath) {
                   2366:                         my @oldfiles;
                   2367:                         if (-e $fullpath) {
                   2368:                             if (opendir(my $dir,$fullpath)) {
                   2369:                                 (@oldfiles) = grep(/^\d+$/,readdir($dir));
                   2370:                                 closedir($dir);
                   2371:                             }
                   2372:                             if (@oldfiles) {
                   2373:                                 @oldfiles = sort { $b <=> $a } (@oldfiles);
                   2374:                                 my $numremoved = 0;
                   2375:                                 for (my $i=0; $i<@oldfiles; $i++) {
                   2376:                                     if ($i>=$passwdconf{'numsaved'}) {
                   2377:                                         if (-f "$fullpath/$oldfiles[$i]") {
                   2378:                                             if (unlink("$fullpath/$oldfiles[$i]")) {
                   2379:                                                 $numremoved ++;
                   2380:                                             }
                   2381:                                         }
                   2382:                                     } elsif (open(my $fh,'<',"$fullpath/$oldfiles[$i]")) {
                   2383:                                         while (my $line = <$fh>) {
                   2384:                                             push(@oldpasswds,$line);
                   2385:                                         }
                   2386:                                         close($fh);
                   2387:                                     }
                   2388:                                 }
                   2389:                                 if ($numremoved) {
                   2390:                                     &logthis("unlinked $numremoved old password files for $uname:$udom");
                   2391:                                 }
                   2392:                             }
                   2393:                         }
                   2394:                         push(@oldpasswds,$contentpwd);
                   2395:                         foreach my $item (@oldpasswds) {
                   2396:                             my (undef,$method,@rest) = split(/!/,$item);
                   2397:                             if ($method eq 'bcrypt') {
                   2398:                                 my $result = &hash_passwd($udom,$npass,@rest);
                   2399:                                 if ($result eq $item) {
                   2400:                                     $notunique = 1;
                   2401:                                     last;
                   2402:                                 }
                   2403:                             }
                   2404:                         }
                   2405:                         unless ($notunique) {
                   2406:                             unless (-e $fullpath) {
                   2407:                                 if (&mkpath("$fullpath/")) {
                   2408:                                     chmod(0700,$fullpath);
                   2409:                                 }
                   2410:                             }
                   2411:                             if (-d $fullpath) {
                   2412:                                 my $now = time;
                   2413:                                 if (open(my $fh,'>',"$fullpath/$now")) {
                   2414:                                     print $fh $contentpwd;
                   2415:                                     close($fh);
                   2416:                                     chmod(0400,"$fullpath/$now");
                   2417:                                 }
                   2418:                             }
                   2419:                         }
                   2420:                     }
                   2421:                 }
                   2422:             }
                   2423:             if ($notunique) {
                   2424:                 my $msg="Result of password change for $uname:$udom - password matches one used before";
                   2425:                 if ($lonhost) {
                   2426:                     $msg .= " - request originated from: $lonhost";
                   2427:                 }
                   2428:                 &logthis($msg);
                   2429:                 &Reply($client, "prioruse\n", $userinput);
                   2430: 	    } elsif (&rewrite_password_file($udom, $uname, "internal:$ncpass")) {
1.428     raeburn  2431: 		my $msg="Result of password change for $uname: pwchange_success";
                   2432:                 if ($lonhost) {
                   2433:                     $msg .= " - request originated from: $lonhost";
                   2434:                 }
                   2435:                 &logthis($msg);
1.518     raeburn  2436:                 &update_passwd_history($uname,$udom,$howpwd,$context);
1.222     foxr     2437: 		&Reply($client, "ok\n", $userinput);
                   2438: 	    } else {
                   2439: 		&logthis("Unable to open $uname passwd "               
                   2440: 			 ."to change password");
                   2441: 		&Failure( $client, "non_authorized\n",$userinput);
                   2442: 	    }
1.346     raeburn  2443: 	} elsif ($howpwd eq 'unix' && $context ne 'reset_by_email') {
1.287     foxr     2444: 	    my $result = &change_unix_password($uname, $npass);
1.518     raeburn  2445:             if ($result eq 'ok') {
                   2446:                 &update_passwd_history($uname,$udom,$howpwd,$context);
1.561     raeburn  2447:             }
1.222     foxr     2448: 	    &logthis("Result of password change for $uname: ".
1.287     foxr     2449: 		     $result);
1.387     albertel 2450: 	    &Reply($client, \$result, $userinput);
1.222     foxr     2451: 	} else {
                   2452: 	    # this just means that the current password mode is not
                   2453: 	    # one we know how to change (e.g the kerberos auth modes or
                   2454: 	    # locally written auth handler).
                   2455: 	    #
                   2456: 	    &Failure( $client, "auth_mode_error\n", $userinput);
                   2457: 	}  
1.224     foxr     2458:     } else {
1.428     raeburn  2459: 	if ($failure eq '') {
                   2460: 	    $failure = 'non_authorized';
                   2461: 	}
                   2462: 	&Failure( $client, "$failure\n", $userinput);
1.222     foxr     2463:     }
                   2464: 
                   2465:     return 1;
                   2466: }
1.263     albertel 2467: &register_handler("passwd", \&change_password_handler, 1, 1, 0);
1.222     foxr     2468: 
1.518     raeburn  2469: sub hash_passwd {
                   2470:     my ($domain,$plainpass,@rest) = @_;
                   2471:     my ($salt,$cost);
                   2472:     if (@rest) {
                   2473:         $cost = $rest[0];
                   2474:         # salt is first 22 characters, base-64 encoded by bcrypt
                   2475:         my $plainsalt = substr($rest[1],0,22);
                   2476:         $salt = Crypt::Eksblowfish::Bcrypt::de_base64($plainsalt);
                   2477:     } else {
1.533     raeburn  2478:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   2479:         my $defaultcost = $domdefaults{'intauth_cost'};
1.518     raeburn  2480:         if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
                   2481:             $cost = 10;
                   2482:         } else {
                   2483:             $cost = $defaultcost;
                   2484:         }
                   2485:         # Generate random 16-octet base64 salt
                   2486:         $salt = "";
                   2487:         $salt .= pack("C", int rand(256)) for 1..16;
                   2488:     }
                   2489:     my $hash = &Crypt::Eksblowfish::Bcrypt::bcrypt_hash({
                   2490:         key_nul => 1,
                   2491:         cost    => $cost,
                   2492:         salt    => $salt,
                   2493:     }, Digest::SHA::sha512(Encode::encode('UTF-8',$plainpass)));
                   2494: 
                   2495:     my $result = join("!", "", "bcrypt", sprintf("%02d",$cost),
                   2496:                 &Crypt::Eksblowfish::Bcrypt::en_base64($salt).
                   2497:                 &Crypt::Eksblowfish::Bcrypt::en_base64($hash));
                   2498:     return $result;
                   2499: }
                   2500: 
1.225     foxr     2501: #
                   2502: #   Create a new user.  User in this case means a lon-capa user.
                   2503: #   The user must either already exist in some authentication realm
                   2504: #   like kerberos or the /etc/passwd.  If not, a user completely local to
                   2505: #   this loncapa system is created.
                   2506: #
                   2507: # Parameters:
                   2508: #    $cmd      - The command that got us here.
                   2509: #    $tail     - Tail of the command (remaining parameters).
                   2510: #    $client   - File descriptor connected to client.
                   2511: # Returns
                   2512: #     0        - Requested to exit, caller should shut down.
                   2513: #     1        - Continue processing.
                   2514: # Implicit inputs:
                   2515: #    The authentication systems describe above have their own forms of implicit
                   2516: #    input into the authentication process that are described above.
                   2517: sub add_user_handler {
                   2518: 
                   2519:     my ($cmd, $tail, $client) = @_;
                   2520: 
                   2521: 
                   2522:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   2523:     my $userinput = $cmd.":".$tail; # Reconstruct the full request line.
                   2524: 
                   2525:     &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
                   2526: 
                   2527: 
                   2528:     if($udom eq $currentdomainid) { # Reject new users for other domains...
                   2529: 	
                   2530: 	my $oldumask=umask(0077);
                   2531: 	chomp($npass);
                   2532: 	$npass=&unescape($npass);
                   2533: 	my $passfilename  = &password_path($udom, $uname);
                   2534: 	&Debug("Password file created will be:".$passfilename);
                   2535: 	if (-e $passfilename) {
                   2536: 	    &Failure( $client, "already_exists\n", $userinput);
                   2537: 	} else {
                   2538: 	    my $fperror='';
1.264     albertel 2539: 	    if (!&mkpath($passfilename)) {
                   2540: 		$fperror="error: ".($!+0)." mkdir failed while attempting "
                   2541: 		    ."makeuser";
1.225     foxr     2542: 	    }
                   2543: 	    unless ($fperror) {
1.518     raeburn  2544: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
                   2545:                                              $passfilename,'makeuser');
1.390     raeburn  2546: 		&Reply($client,\$result, $userinput);     #BUGBUG - could be fail
1.225     foxr     2547: 	    } else {
1.387     albertel 2548: 		&Failure($client, \$fperror, $userinput);
1.225     foxr     2549: 	    }
                   2550: 	}
                   2551: 	umask($oldumask);
                   2552:     }  else {
                   2553: 	&Failure($client, "not_right_domain\n",
                   2554: 		$userinput);	# Even if we are multihomed.
                   2555:     
                   2556:     }
                   2557:     return 1;
                   2558: 
                   2559: }
                   2560: &register_handler("makeuser", \&add_user_handler, 1, 1, 0);
                   2561: 
                   2562: #
                   2563: #   Change the authentication method of a user.  Note that this may
                   2564: #   also implicitly change the user's password if, for example, the user is
                   2565: #   joining an existing authentication realm.  Known authentication realms at
                   2566: #   this time are:
                   2567: #    internal   - Purely internal password file (only loncapa knows this user)
                   2568: #    local      - Institutionally written authentication module.
                   2569: #    unix       - Unix user (/etc/passwd with or without /etc/shadow).
                   2570: #    kerb4      - kerberos version 4
                   2571: #    kerb5      - kerberos version 5
                   2572: #
                   2573: # Parameters:
                   2574: #    $cmd      - The command that got us here.
                   2575: #    $tail     - Tail of the command (remaining parameters).
                   2576: #    $client   - File descriptor connected to client.
                   2577: # Returns
                   2578: #     0        - Requested to exit, caller should shut down.
                   2579: #     1        - Continue processing.
                   2580: # Implicit inputs:
                   2581: #    The authentication systems describe above have their own forms of implicit
                   2582: #    input into the authentication process that are described above.
1.287     foxr     2583: # NOTE:
                   2584: #   This is also used to change the authentication credential values (e.g. passwd).
                   2585: #   
1.225     foxr     2586: #
                   2587: sub change_authentication_handler {
                   2588: 
                   2589:     my ($cmd, $tail, $client) = @_;
                   2590:    
                   2591:     my $userinput  = "$cmd:$tail";              # Reconstruct user input.
                   2592: 
                   2593:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   2594:     &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
                   2595:     if ($udom ne $currentdomainid) {
                   2596: 	&Failure( $client, "not_right_domain\n", $client);
                   2597:     } else {
                   2598: 	
                   2599: 	chomp($npass);
                   2600: 	
                   2601: 	$npass=&unescape($npass);
1.261     foxr     2602: 	my $oldauth = &get_auth_type($udom, $uname); # Get old auth info.
1.225     foxr     2603: 	my $passfilename = &password_path($udom, $uname);
                   2604: 	if ($passfilename) {	# Not allowed to create a new user!!
1.287     foxr     2605: 	    # If just changing the unix passwd. need to arrange to run
1.502     raeburn  2606: 	    # passwd since otherwise make_passwd_file will fail as 
                   2607: 	    # creation of unix authenticated users is no longer supported
                   2608:             # except from the command line, when running make_domain_coordinator.pl
1.287     foxr     2609: 
                   2610: 	    if(($oldauth =~/^unix/) && ($umode eq "unix")) {
                   2611: 		my $result = &change_unix_password($uname, $npass);
                   2612: 		&logthis("Result of password change for $uname: ".$result);
                   2613: 		if ($result eq "ok") {
1.518     raeburn  2614:                     &update_passwd_history($uname,$udom,$umode,'changeuserauth'); 
1.390     raeburn  2615: 		    &Reply($client, \$result);
1.288     albertel 2616: 		} else {
1.387     albertel 2617: 		    &Failure($client, \$result);
1.287     foxr     2618: 		}
1.288     albertel 2619: 	    } else {
1.518     raeburn  2620: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
                   2621:                                              $passfilename,'changeuserauth');
1.287     foxr     2622: 		#
                   2623: 		#  If the current auth mode is internal, and the old auth mode was
                   2624: 		#  unix, or krb*,  and the user is an author for this domain,
                   2625: 		#  re-run manage_permissions for that role in order to be able
                   2626: 		#  to take ownership of the construction space back to www:www
                   2627: 		#
1.502     raeburn  2628: 
                   2629: 
1.387     albertel 2630: 		&Reply($client, \$result, $userinput);
1.261     foxr     2631: 	    }
                   2632: 	       
                   2633: 
1.225     foxr     2634: 	} else {	       
1.251     foxr     2635: 	    &Failure($client, "non_authorized\n", $userinput); # Fail the user now.
1.225     foxr     2636: 	}
                   2637:     }
                   2638:     return 1;
                   2639: }
                   2640: &register_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
                   2641: 
1.518     raeburn  2642: sub update_passwd_history {
                   2643:     my ($uname,$udom,$umode,$context) = @_;
                   2644:     my $proname=&propath($udom,$uname);
                   2645:     my $now = time;
                   2646:     if (open(my $fh,">>$proname/passwd.log")) {
                   2647:         print $fh "$now:$umode:$context\n";
                   2648:         close($fh);
                   2649:     }
                   2650:     return;
                   2651: }
                   2652: 
1.225     foxr     2653: #
                   2654: #   Determines if this is the home server for a user.  The home server
                   2655: #   for a user will have his/her lon-capa passwd file.  Therefore all we need
                   2656: #   to do is determine if this file exists.
                   2657: #
                   2658: # Parameters:
                   2659: #    $cmd      - The command that got us here.
                   2660: #    $tail     - Tail of the command (remaining parameters).
                   2661: #    $client   - File descriptor connected to client.
                   2662: # Returns
                   2663: #     0        - Requested to exit, caller should shut down.
                   2664: #     1        - Continue processing.
                   2665: # Implicit inputs:
                   2666: #    The authentication systems describe above have their own forms of implicit
                   2667: #    input into the authentication process that are described above.
                   2668: #
                   2669: sub is_home_handler {
                   2670:     my ($cmd, $tail, $client) = @_;
                   2671:    
                   2672:     my $userinput  = "$cmd:$tail";
                   2673:    
                   2674:     my ($udom,$uname)=split(/:/,$tail);
                   2675:     chomp($uname);
                   2676:     my $passfile = &password_filename($udom, $uname);
                   2677:     if($passfile) {
                   2678: 	&Reply( $client, "found\n", $userinput);
                   2679:     } else {
                   2680: 	&Failure($client, "not_found\n", $userinput);
                   2681:     }
                   2682:     return 1;
                   2683: }
                   2684: &register_handler("home", \&is_home_handler, 0,1,0);
                   2685: 
                   2686: #
1.434     www      2687: #   Process an update request for a resource.
                   2688: #   A resource has been modified that we hold a subscription to.
1.225     foxr     2689: #   If the resource is not local, then we must update, or at least invalidate our
                   2690: #   cached copy of the resource. 
                   2691: # Parameters:
                   2692: #    $cmd      - The command that got us here.
                   2693: #    $tail     - Tail of the command (remaining parameters).
                   2694: #    $client   - File descriptor connected to client.
                   2695: # Returns
                   2696: #     0        - Requested to exit, caller should shut down.
                   2697: #     1        - Continue processing.
                   2698: # Implicit inputs:
                   2699: #    The authentication systems describe above have their own forms of implicit
                   2700: #    input into the authentication process that are described above.
                   2701: #
                   2702: sub update_resource_handler {
                   2703: 
                   2704:     my ($cmd, $tail, $client) = @_;
                   2705:    
                   2706:     my $userinput = "$cmd:$tail";
                   2707:    
                   2708:     my $fname= $tail;		# This allows interactive testing
                   2709: 
                   2710: 
                   2711:     my $ownership=ishome($fname);
                   2712:     if ($ownership eq 'not_owner') {
                   2713: 	if (-e $fname) {
1.434     www      2714:             # Delete preview file, if exists
                   2715:             unlink("$fname.tmp");
                   2716:             # Get usage stats
1.225     foxr     2717: 	    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
                   2718: 		$atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
                   2719: 	    my $now=time;
                   2720: 	    my $since=$now-$atime;
1.434     www      2721:             # If the file has not been used within lonExpire seconds,
                   2722:             # unsubscribe from it and delete local copy
1.225     foxr     2723: 	    if ($since>$perlvar{'lonExpire'}) {
1.365     albertel 2724: 		my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
1.308     albertel 2725: 		&devalidate_meta_cache($fname);
1.225     foxr     2726: 		unlink("$fname");
1.334     albertel 2727: 		unlink("$fname.meta");
1.225     foxr     2728: 	    } else {
1.434     www      2729:             # Yes, this is in active use. Get a fresh copy. Since it might be in
                   2730:             # very active use and huge (like a movie), copy it to "in.transfer" filename first.
1.225     foxr     2731: 		my $transname="$fname.in.transfer";
1.365     albertel 2732: 		my $remoteurl=&Apache::lonnet::reply("sub:$fname","$clientname");
1.225     foxr     2733: 		my $response;
1.537     raeburn  2734: # FIXME: cannot replicate files that take more than two minutes to transfer -- needs checking now 1200s timeout used
                   2735: # for LWP request.
                   2736: 		my $request=new HTTP::Request('GET',"$remoteurl");
                   2737:                 $response=&LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,0,1);
1.225     foxr     2738: 		if ($response->is_error()) {
1.541     raeburn  2739:                     my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
                   2740:                     &devalidate_meta_cache($fname);
                   2741:                     if (-e $transname) {
                   2742:                         unlink($transname);
                   2743:                     }
                   2744:                     unlink($fname);
1.225     foxr     2745: 		    my $message=$response->status_line;
                   2746: 		    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   2747: 		} else {
                   2748: 		    if ($remoteurl!~/\.meta$/) {
1.537     raeburn  2749: 			my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2750:                         my $mresponse = &LONCAPA::LWPReq::makerequest($clientname,$mrequest,$fname.'.meta',\%perlvar,120,0,1);
                   2751: 			if ($mresponse->is_error()) {
                   2752: 			    unlink($fname.'.meta');
1.225     foxr     2753: 			}
                   2754: 		    }
1.434     www      2755:                     # we successfully transfered, copy file over to real name
1.225     foxr     2756: 		    rename($transname,$fname);
1.308     albertel 2757: 		    &devalidate_meta_cache($fname);
1.225     foxr     2758: 		}
                   2759: 	    }
                   2760: 	    &Reply( $client, "ok\n", $userinput);
                   2761: 	} else {
                   2762: 	    &Failure($client, "not_found\n", $userinput);
                   2763: 	}
                   2764:     } else {
                   2765: 	&Failure($client, "rejected\n", $userinput);
                   2766:     }
                   2767:     return 1;
                   2768: }
                   2769: &register_handler("update", \&update_resource_handler, 0 ,1, 0);
                   2770: 
1.308     albertel 2771: sub devalidate_meta_cache {
                   2772:     my ($url) = @_;
                   2773:     use Cache::Memcached;
                   2774:     my $memcache = new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.365     albertel 2775:     $url = &Apache::lonnet::declutter($url);
1.308     albertel 2776:     $url =~ s-\.meta$--;
                   2777:     my $id = &escape('meta:'.$url);
                   2778:     $memcache->delete($id);
                   2779: }
                   2780: 
1.225     foxr     2781: #
1.226     foxr     2782: #   Fetch a user file from a remote server to the user's home directory
                   2783: #   userfiles subdir.
1.225     foxr     2784: # Parameters:
                   2785: #    $cmd      - The command that got us here.
                   2786: #    $tail     - Tail of the command (remaining parameters).
                   2787: #    $client   - File descriptor connected to client.
                   2788: # Returns
                   2789: #     0        - Requested to exit, caller should shut down.
                   2790: #     1        - Continue processing.
                   2791: #
                   2792: sub fetch_user_file_handler {
                   2793: 
                   2794:     my ($cmd, $tail, $client) = @_;
                   2795: 
                   2796:     my $userinput = "$cmd:$tail";
                   2797:     my $fname           = $tail;
1.232     foxr     2798:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
1.225     foxr     2799:     my $udir=&propath($udom,$uname).'/userfiles';
                   2800:     unless (-e $udir) {
                   2801: 	mkdir($udir,0770); 
                   2802:     }
1.232     foxr     2803:     Debug("fetch user file for $fname");
1.225     foxr     2804:     if (-e $udir) {
                   2805: 	$ufile=~s/^[\.\~]+//;
1.232     foxr     2806: 
                   2807: 	# IF necessary, create the path right down to the file.
                   2808: 	# Note that any regular files in the way of this path are
                   2809: 	# wiped out to deal with some earlier folly of mine.
                   2810: 
1.267     raeburn  2811: 	if (!&mkpath($udir.'/'.$ufile)) {
1.264     albertel 2812: 	    &Failure($client, "unable_to_create\n", $userinput);	    
1.232     foxr     2813: 	}
                   2814: 
1.225     foxr     2815: 	my $destname=$udir.'/'.$ufile;
                   2816: 	my $transname=$udir.'/'.$ufile.'.in.transit';
1.476     raeburn  2817:         my $clientprotocol=$Apache::lonnet::protocol{$clientname};
                   2818:         $clientprotocol = 'http' if ($clientprotocol ne 'https');
1.486     raeburn  2819: 	my $clienthost = &Apache::lonnet::hostname($clientname);
                   2820: 	my $remoteurl=$clientprotocol.'://'.$clienthost.'/userfiles/'.$fname;
1.225     foxr     2821: 	my $response;
1.232     foxr     2822: 	Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
1.537     raeburn  2823: 	my $request=new HTTP::Request('GET',"$remoteurl");
                   2824:         my $verifycert = 1;
                   2825:         my @machine_ids = &Apache::lonnet::current_machine_ids();
                   2826:         if (grep(/^\Q$clientname\E$/,@machine_ids)) {
                   2827:             $verifycert = 0;
                   2828:         }
                   2829:         $response = &LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,$verifycert);
1.225     foxr     2830: 	if ($response->is_error()) {
                   2831: 	    unlink($transname);
                   2832: 	    my $message=$response->status_line;
                   2833: 	    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   2834: 	    &Failure($client, "failed\n", $userinput);
                   2835: 	} else {
1.232     foxr     2836: 	    Debug("Renaming $transname to $destname");
1.225     foxr     2837: 	    if (!rename($transname,$destname)) {
                   2838: 		&logthis("Unable to move $transname to $destname");
                   2839: 		unlink($transname);
                   2840: 		&Failure($client, "failed\n", $userinput);
                   2841: 	    } else {
1.495     raeburn  2842:                 if ($fname =~ /^default.+\.(page|sequence)$/) {
                   2843:                     my ($major,$minor) = split(/\./,$clientversion);
                   2844:                     if (($major < 2) || ($major == 2 && $minor < 11)) {
                   2845:                         my $now = time;
                   2846:                         &Apache::lonnet::do_cache_new('crschange',$udom.'_'.$uname,$now,600);
                   2847:                         my $key = &escape('internal.contentchange');
                   2848:                         my $what = "$key=$now";
                   2849:                         my $hashref = &tie_user_hash($udom,$uname,'environment',
                   2850:                                                      &GDBM_WRCREAT(),"P",$what);
                   2851:                         if ($hashref) {
                   2852:                             $hashref->{$key}=$now;
                   2853:                             if (!&untie_user_hash($hashref)) {
                   2854:                                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
                   2855:                                          "when updating internal.contentchange");
                   2856:                             }
                   2857:                         }
                   2858:                     }
                   2859:                 }
1.225     foxr     2860: 		&Reply($client, "ok\n", $userinput);
                   2861: 	    }
                   2862: 	}   
                   2863:     } else {
                   2864: 	&Failure($client, "not_home\n", $userinput);
                   2865:     }
                   2866:     return 1;
                   2867: }
                   2868: &register_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
                   2869: 
1.226     foxr     2870: #
                   2871: #   Remove a file from a user's home directory userfiles subdirectory.
                   2872: # Parameters:
                   2873: #    cmd   - the Lond request keyword that got us here.
                   2874: #    tail  - the part of the command past the keyword.
                   2875: #    client- File descriptor connected with the client.
                   2876: #
                   2877: # Returns:
                   2878: #    1    - Continue processing.
                   2879: sub remove_user_file_handler {
                   2880:     my ($cmd, $tail, $client) = @_;
                   2881: 
                   2882:     my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2883: 
                   2884:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2885:     if ($ufile =~m|/\.\./|) {
                   2886: 	# any files paths with /../ in them refuse 
                   2887: 	# to deal with
                   2888: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2889:     } else {
                   2890: 	my $udir = &propath($udom,$uname);
                   2891: 	if (-e $udir) {
                   2892: 	    my $file=$udir.'/userfiles/'.$ufile;
                   2893: 	    if (-e $file) {
1.253     foxr     2894: 		#
                   2895: 		#   If the file is a regular file unlink is fine...
1.520     raeburn  2896: 		#   However it's possible the client wants a dir 
                   2897: 		#   removed, in which case rmdir is more appropriate.
                   2898: 		#   Note: rmdir will only remove an empty directory.
1.253     foxr     2899: 		#
1.240     banghart 2900: 	        if (-f $file){
1.241     albertel 2901: 		    unlink($file);
1.520     raeburn  2902:                     # for html files remove the associated .bak file 
                   2903:                     # which may have been created by the editor.
                   2904:                     if ($ufile =~ m{^((docs|supplemental)/(?:\d+|default)/\d+(?:|/.+)/)[^/]+\.x?html?$}i) {
                   2905:                         my $path = $1;
                   2906:                         if (-e $file.'.bak') {
                   2907:                             unlink($file.'.bak');
                   2908:                         }
                   2909:                     }
1.241     albertel 2910: 		} elsif(-d $file) {
                   2911: 		    rmdir($file);
1.240     banghart 2912: 		}
1.226     foxr     2913: 		if (-e $file) {
1.253     foxr     2914: 		    #  File is still there after we deleted it ?!?
                   2915: 
1.226     foxr     2916: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2917: 		} else {
                   2918: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2919: 		}
                   2920: 	    } else {
                   2921: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2922: 	    }
                   2923: 	} else {
                   2924: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2925: 	}
                   2926:     }
                   2927:     return 1;
                   2928: }
                   2929: &register_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
                   2930: 
1.236     albertel 2931: #
                   2932: #   make a directory in a user's home directory userfiles subdirectory.
                   2933: # Parameters:
                   2934: #    cmd   - the Lond request keyword that got us here.
                   2935: #    tail  - the part of the command past the keyword.
                   2936: #    client- File descriptor connected with the client.
                   2937: #
                   2938: # Returns:
                   2939: #    1    - Continue processing.
                   2940: sub mkdir_user_file_handler {
                   2941:     my ($cmd, $tail, $client) = @_;
                   2942: 
                   2943:     my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2944:     $dir=&unescape($dir);
                   2945:     my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2946:     if ($ufile =~m|/\.\./|) {
                   2947: 	# any files paths with /../ in them refuse 
                   2948: 	# to deal with
                   2949: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2950:     } else {
                   2951: 	my $udir = &propath($udom,$uname);
                   2952: 	if (-e $udir) {
1.264     albertel 2953: 	    my $newdir=$udir.'/userfiles/'.$ufile.'/';
                   2954: 	    if (!&mkpath($newdir)) {
                   2955: 		&Failure($client, "failed\n", "$cmd:$tail");
1.236     albertel 2956: 	    }
1.264     albertel 2957: 	    &Reply($client, "ok\n", "$cmd:$tail");
1.236     albertel 2958: 	} else {
                   2959: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2960: 	}
                   2961:     }
                   2962:     return 1;
                   2963: }
                   2964: &register_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
                   2965: 
1.237     albertel 2966: #
                   2967: #   rename a file in a user's home directory userfiles subdirectory.
                   2968: # Parameters:
                   2969: #    cmd   - the Lond request keyword that got us here.
                   2970: #    tail  - the part of the command past the keyword.
                   2971: #    client- File descriptor connected with the client.
                   2972: #
                   2973: # Returns:
                   2974: #    1    - Continue processing.
                   2975: sub rename_user_file_handler {
                   2976:     my ($cmd, $tail, $client) = @_;
                   2977: 
                   2978:     my ($udom,$uname,$old,$new) = split(/:/, $tail);
                   2979:     $old=&unescape($old);
                   2980:     $new=&unescape($new);
                   2981:     if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
                   2982: 	# any files paths with /../ in them refuse to deal with
                   2983: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2984:     } else {
                   2985: 	my $udir = &propath($udom,$uname);
                   2986: 	if (-e $udir) {
                   2987: 	    my $oldfile=$udir.'/userfiles/'.$old;
                   2988: 	    my $newfile=$udir.'/userfiles/'.$new;
                   2989: 	    if (-e $newfile) {
                   2990: 		&Failure($client, "exists\n", "$cmd:$tail");
                   2991: 	    } elsif (! -e $oldfile) {
                   2992: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2993: 	    } else {
                   2994: 		if (!rename($oldfile,$newfile)) {
                   2995: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2996: 		} else {
                   2997: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2998: 		}
                   2999: 	    }
                   3000: 	} else {
                   3001: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   3002: 	}
                   3003:     }
                   3004:     return 1;
                   3005: }
                   3006: &register_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
                   3007: 
1.227     foxr     3008: #
1.382     albertel 3009: #  Checks if the specified user has an active session on the server
                   3010: #  return ok if so, not_found if not
                   3011: #
                   3012: # Parameters:
                   3013: #   cmd      - The request keyword that dispatched to tus.
                   3014: #   tail     - The tail of the request (colon separated parameters).
                   3015: #   client   - Filehandle open on the client.
                   3016: # Return:
                   3017: #    1.
                   3018: sub user_has_session_handler {
                   3019:     my ($cmd, $tail, $client) = @_;
                   3020: 
                   3021:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
                   3022:     
                   3023:     opendir(DIR,$perlvar{'lonIDsDir'});
                   3024:     my $filename;
                   3025:     while ($filename=readdir(DIR)) {
                   3026: 	last if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/);
                   3027:     }
                   3028:     if ($filename) {
                   3029: 	&Reply($client, "ok\n", "$cmd:$tail");
                   3030:     } else {
                   3031: 	&Failure($client, "not_found\n", "$cmd:$tail");
                   3032:     }
                   3033:     return 1;
                   3034: 
                   3035: }
                   3036: &register_handler("userhassession", \&user_has_session_handler, 0,1,0);
                   3037: 
1.560     raeburn  3038: sub del_usersession_handler {
                   3039:     my ($cmd, $tail, $client) = @_;
                   3040: 
                   3041:     my $result;
                   3042:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
                   3043:     if (($udom =~ /^$LONCAPA::match_domain$/) && ($uname =~ /^$LONCAPA::match_username$/)) {
                   3044:         my $lonidsdir = $perlvar{'lonIDsDir'};
                   3045:         if (-d $lonidsdir) {
                   3046:             if (opendir(DIR,$lonidsdir)) {
                   3047:                 my $filename;
                   3048:                 while ($filename=readdir(DIR)) {
                   3049:                     if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/) {
                   3050:                         if (tie(my %oldenv,'GDBM_File',"$lonidsdir/$filename",
                   3051:                                 &GDBM_READER(),0640)) {
                   3052:                             my $linkedfile;
                   3053:                             if (exists($oldenv{'user.linkedenv'})) {
                   3054:                                 $linkedfile = $oldenv{'user.linkedenv'};
                   3055:                             }
                   3056:                             untie(%oldenv);
                   3057:                             $result = unlink("$lonidsdir/$filename");
                   3058:                             if ($result) {
                   3059:                                 if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   3060:                                     if (-l "$lonidsdir/$linkedfile.id") {
                   3061:                                         unlink("$lonidsdir/$linkedfile.id");
                   3062:                                     }
                   3063:                                 }
                   3064:                             }
                   3065:                         } else {
                   3066:                             $result = unlink("$lonidsdir/$filename");
                   3067:                         }
                   3068:                         last;
                   3069:                     }
                   3070:                 }
                   3071:             }
                   3072:         }
                   3073:         if ($result == 1) {
                   3074:             &Reply($client, "$result\n", "$cmd:$tail");
                   3075:         } else {
                   3076:             &Reply($client, "not_found\n", "$cmd:$tail");
                   3077:         }
                   3078:     } else {
                   3079:         &Failure($client, "invalid_user\n", "$cmd:$tail");
                   3080:     }
                   3081:     return 1;
                   3082: }
                   3083: 
                   3084: &register_handler("delusersession", \&del_usersession_handler, 0,1,0);
                   3085: 
1.382     albertel 3086: #
1.263     albertel 3087: #  Authenticate access to a user file by checking that the token the user's 
                   3088: #  passed also exists in their session file
1.227     foxr     3089: #
                   3090: # Parameters:
                   3091: #   cmd      - The request keyword that dispatched to tus.
                   3092: #   tail     - The tail of the request (colon separated parameters).
                   3093: #   client   - Filehandle open on the client.
                   3094: # Return:
                   3095: #    1.
                   3096: sub token_auth_user_file_handler {
                   3097:     my ($cmd, $tail, $client) = @_;
                   3098: 
                   3099:     my ($fname, $session) = split(/:/, $tail);
                   3100:     
                   3101:     chomp($session);
1.393     raeburn  3102:     my $reply="non_auth";
1.343     albertel 3103:     my $file = $perlvar{'lonIDsDir'}.'/'.$session.'.id';
                   3104:     if (open(ENVIN,"$file")) {
1.332     albertel 3105: 	flock(ENVIN,LOCK_SH);
1.343     albertel 3106: 	tie(my %disk_env,'GDBM_File',"$file",&GDBM_READER(),0640);
                   3107: 	if (exists($disk_env{"userfile.$fname"})) {
1.393     raeburn  3108: 	    $reply="ok";
1.343     albertel 3109: 	} else {
                   3110: 	    foreach my $envname (keys(%disk_env)) {
                   3111: 		if ($envname=~ m|^userfile\.\Q$fname\E|) {
1.393     raeburn  3112: 		    $reply="ok";
1.343     albertel 3113: 		    last;
                   3114: 		}
                   3115: 	    }
1.227     foxr     3116: 	}
1.343     albertel 3117: 	untie(%disk_env);
1.227     foxr     3118: 	close(ENVIN);
1.387     albertel 3119: 	&Reply($client, \$reply, "$cmd:$tail");
1.227     foxr     3120:     } else {
                   3121: 	&Failure($client, "invalid_token\n", "$cmd:$tail");
                   3122:     }
                   3123:     return 1;
                   3124: 
                   3125: }
                   3126: &register_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
1.229     foxr     3127: 
                   3128: #
                   3129: #   Unsubscribe from a resource.
                   3130: #
                   3131: # Parameters:
                   3132: #    $cmd      - The command that got us here.
                   3133: #    $tail     - Tail of the command (remaining parameters).
                   3134: #    $client   - File descriptor connected to client.
                   3135: # Returns
                   3136: #     0        - Requested to exit, caller should shut down.
                   3137: #     1        - Continue processing.
                   3138: #
                   3139: sub unsubscribe_handler {
                   3140:     my ($cmd, $tail, $client) = @_;
                   3141: 
                   3142:     my $userinput= "$cmd:$tail";
                   3143:     
                   3144:     my ($fname) = split(/:/,$tail); # Split in case there's extrs.
                   3145: 
                   3146:     &Debug("Unsubscribing $fname");
                   3147:     if (-e $fname) {
                   3148: 	&Debug("Exists");
                   3149: 	&Reply($client, &unsub($fname,$clientip), $userinput);
                   3150:     } else {
                   3151: 	&Failure($client, "not_found\n", $userinput);
                   3152:     }
                   3153:     return 1;
                   3154: }
                   3155: &register_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
1.263     albertel 3156: 
1.230     foxr     3157: #   Subscribe to a resource
                   3158: #
                   3159: # Parameters:
                   3160: #    $cmd      - The command that got us here.
                   3161: #    $tail     - Tail of the command (remaining parameters).
                   3162: #    $client   - File descriptor connected to client.
                   3163: # Returns
                   3164: #     0        - Requested to exit, caller should shut down.
                   3165: #     1        - Continue processing.
                   3166: #
                   3167: sub subscribe_handler {
                   3168:     my ($cmd, $tail, $client)= @_;
                   3169: 
                   3170:     my $userinput  = "$cmd:$tail";
                   3171: 
                   3172:     &Reply( $client, &subscribe($userinput,$clientip), $userinput);
                   3173: 
                   3174:     return 1;
                   3175: }
                   3176: &register_handler("sub", \&subscribe_handler, 0, 1, 0);
                   3177: 
                   3178: #
1.379     albertel 3179: #   Determine the latest version of a resource (it looks for the highest
                   3180: #   past version and then returns that +1)
1.230     foxr     3181: #
                   3182: # Parameters:
                   3183: #    $cmd      - The command that got us here.
                   3184: #    $tail     - Tail of the command (remaining parameters).
1.379     albertel 3185: #                 (Should consist of an absolute path to a file)
1.230     foxr     3186: #    $client   - File descriptor connected to client.
                   3187: # Returns
                   3188: #     0        - Requested to exit, caller should shut down.
                   3189: #     1        - Continue processing.
                   3190: #
                   3191: sub current_version_handler {
                   3192:     my ($cmd, $tail, $client) = @_;
                   3193: 
                   3194:     my $userinput= "$cmd:$tail";
                   3195:    
                   3196:     my $fname   = $tail;
                   3197:     &Reply( $client, &currentversion($fname)."\n", $userinput);
                   3198:     return 1;
                   3199: 
                   3200: }
                   3201: &register_handler("currentversion", \&current_version_handler, 0, 1, 0);
                   3202: 
                   3203: #  Make an entry in a user's activity log.
                   3204: #
                   3205: # Parameters:
                   3206: #    $cmd      - The command that got us here.
                   3207: #    $tail     - Tail of the command (remaining parameters).
                   3208: #    $client   - File descriptor connected to client.
                   3209: # Returns
                   3210: #     0        - Requested to exit, caller should shut down.
                   3211: #     1        - Continue processing.
                   3212: #
                   3213: sub activity_log_handler {
                   3214:     my ($cmd, $tail, $client) = @_;
                   3215: 
                   3216: 
                   3217:     my $userinput= "$cmd:$tail";
                   3218: 
                   3219:     my ($udom,$uname,$what)=split(/:/,$tail);
                   3220:     chomp($what);
                   3221:     my $proname=&propath($udom,$uname);
                   3222:     my $now=time;
                   3223:     my $hfh;
                   3224:     if ($hfh=IO::File->new(">>$proname/activity.log")) { 
                   3225: 	print $hfh "$now:$clientname:$what\n";
                   3226: 	&Reply( $client, "ok\n", $userinput); 
                   3227:     } else {
                   3228: 	&Failure($client, "error: ".($!+0)." IO::File->new Failed "
                   3229: 		 ."while attempting log\n", 
                   3230: 		 $userinput);
                   3231:     }
                   3232: 
                   3233:     return 1;
                   3234: }
1.263     albertel 3235: &register_handler("log", \&activity_log_handler, 0, 1, 0);
1.230     foxr     3236: 
                   3237: #
                   3238: #   Put a namespace entry in a user profile hash.
                   3239: #   My druthers would be for this to be an encrypted interaction too.
                   3240: #   anything that might be an inadvertent covert channel about either
                   3241: #   user authentication or user personal information....
                   3242: #
                   3243: # Parameters:
                   3244: #    $cmd      - The command that got us here.
                   3245: #    $tail     - Tail of the command (remaining parameters).
                   3246: #    $client   - File descriptor connected to client.
                   3247: # Returns
                   3248: #     0        - Requested to exit, caller should shut down.
                   3249: #     1        - Continue processing.
                   3250: #
                   3251: sub put_user_profile_entry {
                   3252:     my ($cmd, $tail, $client)  = @_;
1.229     foxr     3253: 
1.230     foxr     3254:     my $userinput = "$cmd:$tail";
                   3255:     
1.242     raeburn  3256:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
1.230     foxr     3257:     if ($namespace ne 'roles') {
                   3258: 	chomp($what);
                   3259: 	my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3260: 				  &GDBM_WRCREAT(),"P",$what);
                   3261: 	if($hashref) {
                   3262: 	    my @pairs=split(/\&/,$what);
                   3263: 	    foreach my $pair (@pairs) {
                   3264: 		my ($key,$value)=split(/=/,$pair);
                   3265: 		$hashref->{$key}=$value;
                   3266: 	    }
1.311     albertel 3267: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     3268: 		&Reply( $client, "ok\n", $userinput);
                   3269: 	    } else {
                   3270: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3271: 			"while attempting put\n", 
                   3272: 			$userinput);
                   3273: 	    }
                   3274: 	} else {
1.316     albertel 3275: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.230     foxr     3276: 		     "while attempting put\n", $userinput);
                   3277: 	}
                   3278:     } else {
                   3279:         &Failure( $client, "refused\n", $userinput);
                   3280:     }
                   3281:     
                   3282:     return 1;
                   3283: }
                   3284: &register_handler("put", \&put_user_profile_entry, 0, 1, 0);
                   3285: 
1.283     albertel 3286: #   Put a piece of new data in hash, returns error if entry already exists
                   3287: # Parameters:
                   3288: #    $cmd      - The command that got us here.
                   3289: #    $tail     - Tail of the command (remaining parameters).
                   3290: #    $client   - File descriptor connected to client.
                   3291: # Returns
                   3292: #     0        - Requested to exit, caller should shut down.
                   3293: #     1        - Continue processing.
                   3294: #
                   3295: sub newput_user_profile_entry {
                   3296:     my ($cmd, $tail, $client)  = @_;
                   3297: 
                   3298:     my $userinput = "$cmd:$tail";
                   3299: 
                   3300:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
                   3301:     if ($namespace eq 'roles') {
                   3302:         &Failure( $client, "refused\n", $userinput);
                   3303: 	return 1;
                   3304:     }
                   3305: 
                   3306:     chomp($what);
                   3307: 
                   3308:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3309: 				 &GDBM_WRCREAT(),"N",$what);
                   3310:     if(!$hashref) {
1.316     albertel 3311: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.283     albertel 3312: 		  "while attempting put\n", $userinput);
                   3313: 	return 1;
                   3314:     }
                   3315: 
                   3316:     my @pairs=split(/\&/,$what);
                   3317:     foreach my $pair (@pairs) {
                   3318: 	my ($key,$value)=split(/=/,$pair);
                   3319: 	if (exists($hashref->{$key})) {
1.513     raeburn  3320:             if (!&untie_user_hash($hashref)) {
                   3321:                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
                   3322:                          "while attempting newput - early out as key exists");
                   3323:             }
                   3324:             &Failure($client, "key_exists: ".$key."\n",$userinput);
                   3325:             return 1;
1.283     albertel 3326: 	}
                   3327:     }
                   3328: 
                   3329:     foreach my $pair (@pairs) {
                   3330: 	my ($key,$value)=split(/=/,$pair);
                   3331: 	$hashref->{$key}=$value;
                   3332:     }
                   3333: 
1.311     albertel 3334:     if (&untie_user_hash($hashref)) {
1.283     albertel 3335: 	&Reply( $client, "ok\n", $userinput);
                   3336:     } else {
                   3337: 	&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3338: 		 "while attempting put\n", 
                   3339: 		 $userinput);
                   3340:     }
                   3341:     return 1;
                   3342: }
                   3343: &register_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
                   3344: 
1.230     foxr     3345: # 
                   3346: #   Increment a profile entry in the user history file.
                   3347: #   The history contains keyword value pairs.  In this case,
                   3348: #   The value itself is a pair of numbers.  The first, the current value
                   3349: #   the second an increment that this function applies to the current
                   3350: #   value.
                   3351: #
                   3352: # Parameters:
                   3353: #    $cmd      - The command that got us here.
                   3354: #    $tail     - Tail of the command (remaining parameters).
                   3355: #    $client   - File descriptor connected to client.
                   3356: # Returns
                   3357: #     0        - Requested to exit, caller should shut down.
                   3358: #     1        - Continue processing.
                   3359: #
                   3360: sub increment_user_value_handler {
                   3361:     my ($cmd, $tail, $client) = @_;
                   3362:     
                   3363:     my $userinput   = "$cmd:$tail";
                   3364:     
                   3365:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
                   3366:     if ($namespace ne 'roles') {
                   3367:         chomp($what);
                   3368: 	my $hashref = &tie_user_hash($udom, $uname,
                   3369: 				     $namespace, &GDBM_WRCREAT(),
                   3370: 				     "P",$what);
                   3371: 	if ($hashref) {
                   3372: 	    my @pairs=split(/\&/,$what);
                   3373: 	    foreach my $pair (@pairs) {
                   3374: 		my ($key,$value)=split(/=/,$pair);
1.284     raeburn  3375:                 $value = &unescape($value);
1.230     foxr     3376: 		# We could check that we have a number...
                   3377: 		if (! defined($value) || $value eq '') {
                   3378: 		    $value = 1;
                   3379: 		}
                   3380: 		$hashref->{$key}+=$value;
1.284     raeburn  3381:                 if ($namespace eq 'nohist_resourcetracker') {
                   3382:                     if ($hashref->{$key} < 0) {
                   3383:                         $hashref->{$key} = 0;
                   3384:                     }
                   3385:                 }
1.230     foxr     3386: 	    }
1.311     albertel 3387: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     3388: 		&Reply( $client, "ok\n", $userinput);
                   3389: 	    } else {
                   3390: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3391: 			 "while attempting inc\n", $userinput);
                   3392: 	    }
                   3393: 	} else {
                   3394: 	    &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3395: 		     "while attempting inc\n", $userinput);
                   3396: 	}
                   3397:     } else {
                   3398: 	&Failure($client, "refused\n", $userinput);
                   3399:     }
                   3400:     
                   3401:     return 1;
                   3402: }
                   3403: &register_handler("inc", \&increment_user_value_handler, 0, 1, 0);
                   3404: 
                   3405: #
                   3406: #   Put a new role for a user.  Roles are LonCAPA's packaging of permissions.
                   3407: #   Each 'role' a user has implies a set of permissions.  Adding a new role
                   3408: #   for a person grants the permissions packaged with that role
                   3409: #   to that user when the role is selected.
                   3410: #
                   3411: # Parameters:
                   3412: #    $cmd       - The command string (rolesput).
                   3413: #    $tail      - The remainder of the request line.  For rolesput this
                   3414: #                 consists of a colon separated list that contains:
                   3415: #                 The domain and user that is granting the role (logged).
                   3416: #                 The domain and user that is getting the role.
                   3417: #                 The roles being granted as a set of & separated pairs.
                   3418: #                 each pair a key value pair.
                   3419: #    $client    - File descriptor connected to the client.
                   3420: # Returns:
                   3421: #     0         - If the daemon should exit
                   3422: #     1         - To continue processing.
                   3423: #
                   3424: #
                   3425: sub roles_put_handler {
                   3426:     my ($cmd, $tail, $client) = @_;
                   3427: 
                   3428:     my $userinput  = "$cmd:$tail";
                   3429: 
                   3430:     my ( $exedom, $exeuser, $udom, $uname,  $what) = split(/:/,$tail);
                   3431:     
                   3432: 
                   3433:     my $namespace='roles';
                   3434:     chomp($what);
                   3435:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3436: 				 &GDBM_WRCREAT(), "P",
                   3437: 				 "$exedom:$exeuser:$what");
                   3438:     #
                   3439:     #  Log the attempt to set a role.  The {}'s here ensure that the file 
                   3440:     #  handle is open for the minimal amount of time.  Since the flush
                   3441:     #  is done on close this improves the chances the log will be an un-
                   3442:     #  corrupted ordered thing.
                   3443:     if ($hashref) {
1.261     foxr     3444: 	my $pass_entry = &get_auth_type($udom, $uname);
                   3445: 	my ($auth_type,$pwd)  = split(/:/, $pass_entry);
                   3446: 	$auth_type = $auth_type.":";
1.230     foxr     3447: 	my @pairs=split(/\&/,$what);
                   3448: 	foreach my $pair (@pairs) {
                   3449: 	    my ($key,$value)=split(/=/,$pair);
                   3450: 	    &manage_permissions($key, $udom, $uname,
1.260     foxr     3451: 			       $auth_type);
1.230     foxr     3452: 	    $hashref->{$key}=$value;
                   3453: 	}
1.311     albertel 3454: 	if (&untie_user_hash($hashref)) {
1.230     foxr     3455: 	    &Reply($client, "ok\n", $userinput);
                   3456: 	} else {
                   3457: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3458: 		     "while attempting rolesput\n", $userinput);
                   3459: 	}
                   3460:     } else {
                   3461: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3462: 		 "while attempting rolesput\n", $userinput);
                   3463:     }
                   3464:     return 1;
                   3465: }
                   3466: &register_handler("rolesput", \&roles_put_handler, 1,1,0);  # Encoded client only.
                   3467: 
                   3468: #
1.231     foxr     3469: #   Deletes (removes) a role for a user.   This is equivalent to removing
                   3470: #  a permissions package associated with the role from the user's profile.
                   3471: #
                   3472: # Parameters:
                   3473: #     $cmd                 - The command (rolesdel)
                   3474: #     $tail                - The remainder of the request line. This consists
                   3475: #                             of:
                   3476: #                             The domain and user requesting the change (logged)
                   3477: #                             The domain and user being changed.
                   3478: #                             The roles being revoked.  These are shipped to us
                   3479: #                             as a bunch of & separated role name keywords.
                   3480: #     $client              - The file handle open on the client.
                   3481: # Returns:
                   3482: #     1                    - Continue processing
                   3483: #     0                    - Exit.
                   3484: #
                   3485: sub roles_delete_handler {
                   3486:     my ($cmd, $tail, $client)  = @_;
                   3487: 
                   3488:     my $userinput    = "$cmd:$tail";
                   3489:    
                   3490:     my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
                   3491:     &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
                   3492: 	   "what = ".$what);
                   3493:     my $namespace='roles';
                   3494:     chomp($what);
                   3495:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3496: 				 &GDBM_WRCREAT(), "D",
                   3497: 				 "$exedom:$exeuser:$what");
                   3498:     
                   3499:     if ($hashref) {
                   3500: 	my @rolekeys=split(/\&/,$what);
                   3501: 	
                   3502: 	foreach my $key (@rolekeys) {
                   3503: 	    delete $hashref->{$key};
                   3504: 	}
1.315     albertel 3505: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3506: 	    &Reply($client, "ok\n", $userinput);
                   3507: 	} else {
                   3508: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3509: 		     "while attempting rolesdel\n", $userinput);
                   3510: 	}
                   3511:     } else {
                   3512:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3513: 		 "while attempting rolesdel\n", $userinput);
                   3514:     }
                   3515:     
                   3516:     return 1;
                   3517: }
                   3518: &register_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
                   3519: 
                   3520: # Unencrypted get from a user's profile database.  See 
                   3521: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
                   3522: # This function retrieves a keyed item from a specific named database in the
                   3523: # user's directory.
                   3524: #
                   3525: # Parameters:
                   3526: #   $cmd             - Command request keyword (get).
                   3527: #   $tail            - Tail of the command.  This is a colon separated list
                   3528: #                      consisting of the domain and username that uniquely
                   3529: #                      identifies the profile,
                   3530: #                      The 'namespace' which selects the gdbm file to 
                   3531: #                      do the lookup in, 
                   3532: #                      & separated list of keys to lookup.  Note that
                   3533: #                      the values are returned as an & separated list too.
                   3534: #   $client          - File descriptor open on the client.
                   3535: # Returns:
                   3536: #   1       - Continue processing.
                   3537: #   0       - Exit.
                   3538: #
                   3539: sub get_profile_entry {
                   3540:     my ($cmd, $tail, $client) = @_;
                   3541: 
                   3542:     my $userinput= "$cmd:$tail";
                   3543:    
                   3544:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   3545:     chomp($what);
1.255     foxr     3546: 
1.390     raeburn  3547: 
1.255     foxr     3548:     my $replystring = read_profile($udom, $uname, $namespace, $what);
                   3549:     my ($first) = split(/:/,$replystring);
                   3550:     if($first ne "error") {
1.387     albertel 3551: 	&Reply($client, \$replystring, $userinput);
1.231     foxr     3552:     } else {
1.255     foxr     3553: 	&Failure($client, $replystring." while attempting get\n", $userinput);
1.231     foxr     3554:     }
                   3555:     return 1;
1.255     foxr     3556: 
                   3557: 
1.231     foxr     3558: }
                   3559: &register_handler("get", \&get_profile_entry, 0,1,0);
                   3560: 
                   3561: #
                   3562: #  Process the encrypted get request.  Note that the request is sent
                   3563: #  in clear, but the reply is encrypted.  This is a small covert channel:
                   3564: #  information about the sensitive keys is given to the snooper.  Just not
                   3565: #  information about the values of the sensitive key.  Hmm if I wanted to
                   3566: #  know these I'd snoop for the egets. Get the profile item names from them
                   3567: #  and then issue a get for them since there's no enforcement of the
                   3568: #  requirement of an encrypted get for particular profile items.  If I
                   3569: #  were re-doing this, I'd force the request to be encrypted as well as the
                   3570: #  reply.  I'd also just enforce encrypted transactions for all gets since
                   3571: #  that would prevent any covert channel snooping.
                   3572: #
                   3573: #  Parameters:
                   3574: #     $cmd               - Command keyword of request (eget).
1.536     raeburn  3575: #     $tail              - Tail of the command.  See GetProfileEntry
                   3576: #                          for more information about this.
1.231     foxr     3577: #     $client            - File open on the client.
                   3578: #  Returns:
                   3579: #     1      - Continue processing
                   3580: #     0      - server should exit.
                   3581: sub get_profile_entry_encrypted {
                   3582:     my ($cmd, $tail, $client) = @_;
                   3583: 
                   3584:     my $userinput = "$cmd:$tail";
                   3585:    
1.339     albertel 3586:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
1.231     foxr     3587:     chomp($what);
1.255     foxr     3588:     my $qresult = read_profile($udom, $uname, $namespace, $what);
                   3589:     my ($first) = split(/:/, $qresult);
                   3590:     if($first ne "error") {
                   3591: 	
                   3592: 	if ($cipher) {
                   3593: 	    my $cmdlength=length($qresult);
                   3594: 	    $qresult.="         ";
                   3595: 	    my $encqresult='';
                   3596: 	    for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   3597: 		$encqresult.= unpack("H16", 
                   3598: 				     $cipher->encrypt(substr($qresult,
                   3599: 							     $encidx,
                   3600: 							     8)));
                   3601: 	    }
                   3602: 	    &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
                   3603: 	} else {
1.231     foxr     3604: 		&Failure( $client, "error:no_key\n", $userinput);
                   3605: 	    }
                   3606:     } else {
1.255     foxr     3607: 	&Failure($client, "$qresult while attempting eget\n", $userinput);
                   3608: 
1.231     foxr     3609:     }
                   3610:     
                   3611:     return 1;
                   3612: }
1.255     foxr     3613: &register_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
1.263     albertel 3614: 
1.231     foxr     3615: #
                   3616: #   Deletes a key in a user profile database.
                   3617: #   
                   3618: #   Parameters:
                   3619: #       $cmd                  - Command keyword (del).
                   3620: #       $tail                 - Command tail.  IN this case a colon
                   3621: #                               separated list containing:
                   3622: #                               The domain and user that identifies uniquely
                   3623: #                               the identity of the user.
                   3624: #                               The profile namespace (name of the profile
                   3625: #                               database file).
                   3626: #                               & separated list of keywords to delete.
                   3627: #       $client              - File open on client socket.
                   3628: # Returns:
                   3629: #     1   - Continue processing
                   3630: #     0   - Exit server.
                   3631: #
                   3632: #
                   3633: sub delete_profile_entry {
                   3634:     my ($cmd, $tail, $client) = @_;
                   3635: 
                   3636:     my $userinput = "cmd:$tail";
                   3637: 
                   3638:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   3639:     chomp($what);
                   3640:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3641: 				 &GDBM_WRCREAT(),
                   3642: 				 "D",$what);
                   3643:     if ($hashref) {
                   3644:         my @keys=split(/\&/,$what);
                   3645: 	foreach my $key (@keys) {
                   3646: 	    delete($hashref->{$key});
                   3647: 	}
1.315     albertel 3648: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3649: 	    &Reply($client, "ok\n", $userinput);
                   3650: 	} else {
                   3651: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3652: 		    "while attempting del\n", $userinput);
                   3653: 	}
                   3654:     } else {
                   3655: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3656: 		 "while attempting del\n", $userinput);
                   3657:     }
                   3658:     return 1;
                   3659: }
                   3660: &register_handler("del", \&delete_profile_entry, 0, 1, 0);
1.263     albertel 3661: 
1.231     foxr     3662: #
                   3663: #  List the set of keys that are defined in a profile database file.
                   3664: #  A successful reply from this will contain an & separated list of
                   3665: #  the keys. 
                   3666: # Parameters:
                   3667: #     $cmd              - Command request (keys).
                   3668: #     $tail             - Remainder of the request, a colon separated
                   3669: #                         list containing domain/user that identifies the
                   3670: #                         user being queried, and the database namespace
                   3671: #                         (database filename essentially).
                   3672: #     $client           - File open on the client.
                   3673: #  Returns:
                   3674: #    1    - Continue processing.
                   3675: #    0    - Exit the server.
                   3676: #
                   3677: sub get_profile_keys {
                   3678:     my ($cmd, $tail, $client) = @_;
                   3679: 
                   3680:     my $userinput = "$cmd:$tail";
                   3681: 
                   3682:     my ($udom,$uname,$namespace)=split(/:/,$tail);
                   3683:     my $qresult='';
                   3684:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3685: 				  &GDBM_READER());
                   3686:     if ($hashref) {
                   3687: 	foreach my $key (keys %$hashref) {
                   3688: 	    $qresult.="$key&";
                   3689: 	}
1.315     albertel 3690: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3691: 	    $qresult=~s/\&$//;
1.387     albertel 3692: 	    &Reply($client, \$qresult, $userinput);
1.231     foxr     3693: 	} else {
                   3694: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3695: 		    "while attempting keys\n", $userinput);
                   3696: 	}
                   3697:     } else {
                   3698: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3699: 		 "while attempting keys\n", $userinput);
                   3700:     }
                   3701:    
                   3702:     return 1;
                   3703: }
                   3704: &register_handler("keys", \&get_profile_keys, 0, 1, 0);
                   3705: 
                   3706: #
                   3707: #   Dump the contents of a user profile database.
                   3708: #   Note that this constitutes a very large covert channel too since
                   3709: #   the dump will return sensitive information that is not encrypted.
                   3710: #   The naive security assumption is that the session negotiation ensures
                   3711: #   our client is trusted and I don't believe that's assured at present.
                   3712: #   Sure want badly to go to ssl or tls.  Of course if my peer isn't really
                   3713: #   a LonCAPA node they could have negotiated an encryption key too so >sigh<.
                   3714: # 
                   3715: #  Parameters:
                   3716: #     $cmd           - The command request keyword (currentdump).
                   3717: #     $tail          - Remainder of the request, consisting of a colon
                   3718: #                      separated list that has the domain/username and
                   3719: #                      the namespace to dump (database file).
                   3720: #     $client        - file open on the remote client.
                   3721: # Returns:
                   3722: #     1    - Continue processing.
                   3723: #     0    - Exit the server.
                   3724: #
                   3725: sub dump_profile_database {
                   3726:     my ($cmd, $tail, $client) = @_;
                   3727: 
1.494     droeschl 3728:     my $res = LONCAPA::Lond::dump_profile_database($tail);
                   3729: 
                   3730:     if ($res =~ /^error:/) {
                   3731:         Failure($client, \$res, "$cmd:$tail");
                   3732:     } else {
                   3733:         Reply($client, \$res, "$cmd:$tail");
                   3734:     }
                   3735: 
                   3736:     return 1;  
                   3737: 
                   3738:     #TODO remove 
1.231     foxr     3739:     my $userinput = "$cmd:$tail";
                   3740:    
                   3741:     my ($udom,$uname,$namespace) = split(/:/,$tail);
                   3742:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3743: 				 &GDBM_READER());
                   3744:     if ($hashref) {
                   3745: 	# Structure of %data:
                   3746: 	# $data{$symb}->{$parameter}=$value;
                   3747: 	# $data{$symb}->{'v.'.$parameter}=$version;
                   3748: 	# since $parameter will be unescaped, we do not
                   3749:  	# have to worry about silly parameter names...
                   3750: 	
                   3751:         my $qresult='';
                   3752: 	my %data = ();                     # A hash of anonymous hashes..
                   3753: 	while (my ($key,$value) = each(%$hashref)) {
                   3754: 	    my ($v,$symb,$param) = split(/:/,$key);
                   3755: 	    next if ($v eq 'version' || $symb eq 'keys');
                   3756: 	    next if (exists($data{$symb}) && 
                   3757: 		     exists($data{$symb}->{$param}) &&
                   3758: 		     $data{$symb}->{'v.'.$param} > $v);
                   3759: 	    $data{$symb}->{$param}=$value;
                   3760: 	    $data{$symb}->{'v.'.$param}=$v;
                   3761: 	}
1.311     albertel 3762: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3763: 	    while (my ($symb,$param_hash) = each(%data)) {
                   3764: 		while(my ($param,$value) = each (%$param_hash)){
                   3765: 		    next if ($param =~ /^v\./);       # Ignore versions...
                   3766: 		    #
                   3767: 		    #   Just dump the symb=value pairs separated by &
                   3768: 		    #
                   3769: 		    $qresult.=$symb.':'.$param.'='.$value.'&';
                   3770: 		}
                   3771: 	    }
                   3772: 	    chop($qresult);
1.387     albertel 3773: 	    &Reply($client , \$qresult, $userinput);
1.231     foxr     3774: 	} else {
                   3775: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3776: 		     "while attempting currentdump\n", $userinput);
                   3777: 	}
                   3778:     } else {
                   3779: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3780: 		"while attempting currentdump\n", $userinput);
                   3781:     }
                   3782: 
                   3783:     return 1;
                   3784: }
                   3785: &register_handler("currentdump", \&dump_profile_database, 0, 1, 0);
                   3786: 
                   3787: #
                   3788: #   Dump a profile database with an optional regular expression
                   3789: #   to match against the keys.  In this dump, no effort is made
                   3790: #   to separate symb from version information. Presumably the
                   3791: #   databases that are dumped by this command are of a different
                   3792: #   structure.  Need to look at this and improve the documentation of
                   3793: #   both this and the currentdump handler.
                   3794: # Parameters:
                   3795: #    $cmd                     - The command keyword.
                   3796: #    $tail                    - All of the characters after the $cmd:
                   3797: #                               These are expected to be a colon
                   3798: #                               separated list containing:
                   3799: #                               domain/user - identifying the user.
                   3800: #                               namespace   - identifying the database.
                   3801: #                               regexp      - optional regular expression
                   3802: #                                             that is matched against
                   3803: #                                             database keywords to do
                   3804: #                                             selective dumps.
1.488     raeburn  3805: #                               range       - optional range of entries
                   3806: #                                             e.g., 10-20 would return the
                   3807: #                                             10th to 19th items, etc.  
1.231     foxr     3808: #   $client                   - Channel open on the client.
                   3809: # Returns:
                   3810: #    1    - Continue processing.
                   3811: # Side effects:
                   3812: #    response is written to $client.
                   3813: #
                   3814: sub dump_with_regexp {
                   3815:     my ($cmd, $tail, $client) = @_;
                   3816: 
1.494     droeschl 3817:     my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
1.490     droeschl 3818:     
                   3819:     if ($res =~ /^error:/) {
                   3820:         Failure($client, \$res, "$cmd:$tail");
                   3821:     } else {
                   3822:         Reply($client, \$res, "$cmd:$tail");
                   3823:     }
1.231     foxr     3824: 
                   3825:     return 1;
                   3826: }
                   3827: &register_handler("dump", \&dump_with_regexp, 0, 1, 0);
                   3828: 
                   3829: #  Store a set of key=value pairs associated with a versioned name.
                   3830: #
                   3831: #  Parameters:
                   3832: #    $cmd                - Request command keyword.
                   3833: #    $tail               - Tail of the request.  This is a colon
                   3834: #                          separated list containing:
                   3835: #                          domain/user - User and authentication domain.
                   3836: #                          namespace   - Name of the database being modified
                   3837: #                          rid         - Resource keyword to modify.
                   3838: #                          what        - new value associated with rid.
1.512     raeburn  3839: #                          laststore   - (optional) version=timestamp
                   3840: #                                        for most recent transaction for rid
                   3841: #                                        in namespace, when cstore was called
1.231     foxr     3842: #
                   3843: #    $client             - Socket open on the client.
                   3844: #
                   3845: #
                   3846: #  Returns:
                   3847: #      1 (keep on processing).
                   3848: #  Side-Effects:
                   3849: #    Writes to the client
1.512     raeburn  3850: #    Successful storage will cause either 'ok', or, if $laststore was included
                   3851: #    in the tail of the request, and the version number for the last transaction
                   3852: #    is larger than the version in $laststore, delay:$numtrans , where $numtrans
                   3853: #    is the number of store evevnts recorded for rid in namespace since
                   3854: #    lonnet::store() was called by the client.
                   3855: #
1.231     foxr     3856: sub store_handler {
                   3857:     my ($cmd, $tail, $client) = @_;
                   3858:  
                   3859:     my $userinput = "$cmd:$tail";
1.512     raeburn  3860:     chomp($tail);
                   3861:     my ($udom,$uname,$namespace,$rid,$what,$laststore) =split(/:/,$tail);
1.231     foxr     3862:     if ($namespace ne 'roles') {
                   3863: 
                   3864: 	my @pairs=split(/\&/,$what);
                   3865: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
1.268     albertel 3866: 				       &GDBM_WRCREAT(), "S",
1.231     foxr     3867: 				       "$rid:$what");
                   3868: 	if ($hashref) {
                   3869: 	    my $now = time;
1.512     raeburn  3870:             my $numtrans;
                   3871:             if ($laststore) {
                   3872:                 my ($previousversion,$previoustime) = split(/\=/,$laststore);
                   3873:                 my ($lastversion,$lasttime) = (0,0);
                   3874:                 $lastversion = $hashref->{"version:$rid"};
                   3875:                 if ($lastversion) {
                   3876:                     $lasttime = $hashref->{"$lastversion:$rid:timestamp"};
                   3877:                 }
                   3878:                 if (($previousversion) && ($previousversion !~ /\D/)) {
                   3879:                     if (($lastversion > $previousversion) && ($lasttime >= $previoustime)) {
                   3880:                         $numtrans = $lastversion - $previousversion;
                   3881:                     }
                   3882:                 } elsif ($lastversion) {
                   3883:                     $numtrans = $lastversion;
                   3884:                 }
                   3885:                 if ($numtrans) {
                   3886:                     $numtrans =~ s/D//g;
                   3887:                 }
                   3888:             }
1.231     foxr     3889: 	    $hashref->{"version:$rid"}++;
                   3890: 	    my $version=$hashref->{"version:$rid"};
                   3891: 	    my $allkeys=''; 
                   3892: 	    foreach my $pair (@pairs) {
                   3893: 		my ($key,$value)=split(/=/,$pair);
                   3894: 		$allkeys.=$key.':';
                   3895: 		$hashref->{"$version:$rid:$key"}=$value;
                   3896: 	    }
                   3897: 	    $hashref->{"$version:$rid:timestamp"}=$now;
                   3898: 	    $allkeys.='timestamp';
                   3899: 	    $hashref->{"$version:keys:$rid"}=$allkeys;
1.311     albertel 3900: 	    if (&untie_user_hash($hashref)) {
1.512     raeburn  3901:                 my $msg = 'ok';
                   3902:                 if ($numtrans) {
                   3903:                     $msg = 'delay:'.$numtrans;
                   3904:                 }
                   3905: 		&Reply($client, "$msg\n", $userinput);
1.231     foxr     3906: 	    } else {
                   3907: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3908: 			"while attempting store\n", $userinput);
                   3909: 	    }
                   3910: 	} else {
                   3911: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3912: 		     "while attempting store\n", $userinput);
                   3913: 	}
                   3914:     } else {
                   3915: 	&Failure($client, "refused\n", $userinput);
                   3916:     }
                   3917: 
                   3918:     return 1;
                   3919: }
                   3920: &register_handler("store", \&store_handler, 0, 1, 0);
1.263     albertel 3921: 
1.323     albertel 3922: #  Modify a set of key=value pairs associated with a versioned name.
                   3923: #
                   3924: #  Parameters:
                   3925: #    $cmd                - Request command keyword.
                   3926: #    $tail               - Tail of the request.  This is a colon
                   3927: #                          separated list containing:
                   3928: #                          domain/user - User and authentication domain.
                   3929: #                          namespace   - Name of the database being modified
                   3930: #                          rid         - Resource keyword to modify.
                   3931: #                          v           - Version item to modify
                   3932: #                          what        - new value associated with rid.
                   3933: #
                   3934: #    $client             - Socket open on the client.
                   3935: #
                   3936: #
                   3937: #  Returns:
                   3938: #      1 (keep on processing).
                   3939: #  Side-Effects:
                   3940: #    Writes to the client
                   3941: sub putstore_handler {
                   3942:     my ($cmd, $tail, $client) = @_;
                   3943:  
                   3944:     my $userinput = "$cmd:$tail";
                   3945: 
                   3946:     my ($udom,$uname,$namespace,$rid,$v,$what) =split(/:/,$tail);
                   3947:     if ($namespace ne 'roles') {
                   3948: 
                   3949: 	chomp($what);
                   3950: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
                   3951: 				       &GDBM_WRCREAT(), "M",
                   3952: 				       "$rid:$v:$what");
                   3953: 	if ($hashref) {
                   3954: 	    my $now = time;
                   3955: 	    my %data = &hash_extract($what);
                   3956: 	    my @allkeys;
                   3957: 	    while (my($key,$value) = each(%data)) {
                   3958: 		push(@allkeys,$key);
                   3959: 		$hashref->{"$v:$rid:$key"} = $value;
                   3960: 	    }
                   3961: 	    my $allkeys = join(':',@allkeys);
                   3962: 	    $hashref->{"$v:keys:$rid"}=$allkeys;
                   3963: 
                   3964: 	    if (&untie_user_hash($hashref)) {
                   3965: 		&Reply($client, "ok\n", $userinput);
                   3966: 	    } else {
                   3967: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3968: 			"while attempting store\n", $userinput);
                   3969: 	    }
                   3970: 	} else {
                   3971: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3972: 		     "while attempting store\n", $userinput);
                   3973: 	}
                   3974:     } else {
                   3975: 	&Failure($client, "refused\n", $userinput);
                   3976:     }
                   3977: 
                   3978:     return 1;
                   3979: }
                   3980: &register_handler("putstore", \&putstore_handler, 0, 1, 0);
                   3981: 
                   3982: sub hash_extract {
                   3983:     my ($str)=@_;
                   3984:     my %hash;
                   3985:     foreach my $pair (split(/\&/,$str)) {
                   3986: 	my ($key,$value)=split(/=/,$pair);
                   3987: 	$hash{$key}=$value;
                   3988:     }
                   3989:     return (%hash);
                   3990: }
                   3991: sub hash_to_str {
                   3992:     my ($hash_ref)=@_;
                   3993:     my $str;
                   3994:     foreach my $key (keys(%$hash_ref)) {
                   3995: 	$str.=$key.'='.$hash_ref->{$key}.'&';
                   3996:     }
                   3997:     $str=~s/\&$//;
                   3998:     return $str;
                   3999: }
                   4000: 
1.231     foxr     4001: #
                   4002: #  Dump out all versions of a resource that has key=value pairs associated
                   4003: # with it for each version.  These resources are built up via the store
                   4004: # command.
                   4005: #
                   4006: #  Parameters:
                   4007: #     $cmd               - Command keyword.
                   4008: #     $tail              - Remainder of the request which consists of:
                   4009: #                          domain/user   - User and auth. domain.
                   4010: #                          namespace     - name of resource database.
                   4011: #                          rid           - Resource id.
                   4012: #    $client             - socket open on the client.
                   4013: #
                   4014: # Returns:
                   4015: #      1  indicating the caller should not yet exit.
                   4016: # Side-effects:
                   4017: #   Writes a reply to the client.
                   4018: #   The reply is a string of the following shape:
                   4019: #   version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
                   4020: #    Where the 1 above represents version 1.
                   4021: #    this continues for all pairs of keys in all versions.
                   4022: #
                   4023: #
                   4024: #    
                   4025: #
                   4026: sub restore_handler {
                   4027:     my ($cmd, $tail, $client) = @_;
                   4028: 
                   4029:     my $userinput = "$cmd:$tail";	# Only used for logging purposes.
1.351     banghart 4030:     my ($udom,$uname,$namespace,$rid) = split(/:/,$tail);
1.352     albertel 4031:     $namespace=~s/\//\_/g;
1.350     albertel 4032:     $namespace = &LONCAPA::clean_username($namespace);
1.349     albertel 4033: 
1.231     foxr     4034:     chomp($rid);
                   4035:     my $qresult='';
1.309     albertel 4036:     my $hashref = &tie_user_hash($udom, $uname, $namespace, &GDBM_READER());
                   4037:     if ($hashref) {
                   4038: 	my $version=$hashref->{"version:$rid"};
1.231     foxr     4039: 	$qresult.="version=$version&";
                   4040: 	my $scope;
                   4041: 	for ($scope=1;$scope<=$version;$scope++) {
1.309     albertel 4042: 	    my $vkeys=$hashref->{"$scope:keys:$rid"};
1.231     foxr     4043: 	    my @keys=split(/:/,$vkeys);
                   4044: 	    my $key;
                   4045: 	    $qresult.="$scope:keys=$vkeys&";
                   4046: 	    foreach $key (@keys) {
1.309     albertel 4047: 		$qresult.="$scope:$key=".$hashref->{"$scope:$rid:$key"}."&";
1.231     foxr     4048: 	    }                                  
                   4049: 	}
1.311     albertel 4050: 	if (&untie_user_hash($hashref)) {
1.231     foxr     4051: 	    $qresult=~s/\&$//;
1.387     albertel 4052: 	    &Reply( $client, \$qresult, $userinput);
1.231     foxr     4053: 	} else {
                   4054: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4055: 		    "while attempting restore\n", $userinput);
                   4056: 	}
                   4057:     } else {
                   4058: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4059: 		"while attempting restore\n", $userinput);
                   4060:     }
                   4061:   
                   4062:     return 1;
                   4063: 
                   4064: 
                   4065: }
                   4066: &register_handler("restore", \&restore_handler, 0,1,0);
1.234     foxr     4067: 
                   4068: #
1.324     raeburn  4069: #   Add a chat message to a synchronous discussion board.
1.234     foxr     4070: #
                   4071: # Parameters:
                   4072: #    $cmd                - Request keyword.
                   4073: #    $tail               - Tail of the command. A colon separated list
                   4074: #                          containing:
                   4075: #                          cdom    - Domain on which the chat board lives
1.324     raeburn  4076: #                          cnum    - Course containing the chat board.
                   4077: #                          newpost - Body of the posting.
                   4078: #                          group   - Optional group, if chat board is only 
                   4079: #                                    accessible in a group within the course 
1.234     foxr     4080: #   $client              - Socket open on the client.
                   4081: # Returns:
                   4082: #   1    - Indicating caller should keep on processing.
                   4083: #
                   4084: # Side-effects:
                   4085: #   writes a reply to the client.
                   4086: #
                   4087: #
                   4088: sub send_chat_handler {
                   4089:     my ($cmd, $tail, $client) = @_;
                   4090: 
                   4091:     
                   4092:     my $userinput = "$cmd:$tail";
                   4093: 
1.324     raeburn  4094:     my ($cdom,$cnum,$newpost,$group)=split(/\:/,$tail);
                   4095:     &chat_add($cdom,$cnum,$newpost,$group);
1.234     foxr     4096:     &Reply($client, "ok\n", $userinput);
                   4097: 
                   4098:     return 1;
                   4099: }
                   4100: &register_handler("chatsend", \&send_chat_handler, 0, 1, 0);
1.263     albertel 4101: 
1.234     foxr     4102: #
1.324     raeburn  4103: #   Retrieve the set of chat messages from a discussion board.
1.234     foxr     4104: #
                   4105: #  Parameters:
                   4106: #    $cmd             - Command keyword that initiated the request.
                   4107: #    $tail            - Remainder of the request after the command
                   4108: #                       keyword.  In this case a colon separated list of
                   4109: #                       chat domain    - Which discussion board.
                   4110: #                       chat id        - Discussion thread(?)
                   4111: #                       domain/user    - Authentication domain and username
                   4112: #                                        of the requesting person.
1.324     raeburn  4113: #                       group          - Optional course group containing
                   4114: #                                        the board.      
1.234     foxr     4115: #   $client           - Socket open on the client program.
                   4116: # Returns:
                   4117: #    1     - continue processing
                   4118: # Side effects:
                   4119: #    Response is written to the client.
                   4120: #
                   4121: sub retrieve_chat_handler {
                   4122:     my ($cmd, $tail, $client) = @_;
                   4123: 
                   4124: 
                   4125:     my $userinput = "$cmd:$tail";
                   4126: 
1.324     raeburn  4127:     my ($cdom,$cnum,$udom,$uname,$group)=split(/\:/,$tail);
1.234     foxr     4128:     my $reply='';
1.324     raeburn  4129:     foreach (&get_chat($cdom,$cnum,$udom,$uname,$group)) {
1.234     foxr     4130: 	$reply.=&escape($_).':';
                   4131:     }
                   4132:     $reply=~s/\:$//;
1.387     albertel 4133:     &Reply($client, \$reply, $userinput);
1.234     foxr     4134: 
                   4135: 
                   4136:     return 1;
                   4137: }
                   4138: &register_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
                   4139: 
                   4140: #
                   4141: #  Initiate a query of an sql database.  SQL query repsonses get put in
                   4142: #  a file for later retrieval.  This prevents sql query results from
                   4143: #  bottlenecking the system.  Note that with loncnew, perhaps this is
                   4144: #  less of an issue since multiple outstanding requests can be concurrently
                   4145: #  serviced.
                   4146: #
                   4147: #  Parameters:
1.535     raeburn  4148: #     $cmd       - Command keyword that initiated the request.
1.234     foxr     4149: #     $tail      - Remainder of the command after the keyword.
                   4150: #                  For this function, this consists of a query and
                   4151: #                  3 arguments that are self-documentingly labelled
                   4152: #                  in the original arg1, arg2, arg3.
                   4153: #     $client    - Socket open on the client.
                   4154: # Return:
                   4155: #    1   - Indicating processing should continue.
                   4156: # Side-effects:
                   4157: #    a reply is written to $client.
                   4158: #
                   4159: sub send_query_handler {
                   4160:     my ($cmd, $tail, $client) = @_;
                   4161: 
                   4162:     my $userinput = "$cmd:$tail";
                   4163: 
                   4164:     my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
                   4165:     $query=~s/\n*$//g;
1.534     raeburn  4166:     if (($query eq 'usersearch') || ($query eq 'instdirsearch')) {
                   4167:         my $usersearchconf = &get_usersearch_config($currentdomainid,'directorysrch');
                   4168:         my $earlyout;
                   4169:         if (ref($usersearchconf) eq 'HASH') {
                   4170:             if ($currentdomainid eq $clienthomedom) {
                   4171:                 if ($query eq 'usersearch') {
                   4172:                     if ($usersearchconf->{'lcavailable'} eq '0') {
                   4173:                         $earlyout = 1;
                   4174:                     }
                   4175:                 } else {
                   4176:                     if ($usersearchconf->{'available'} eq '0') {
                   4177:                         $earlyout = 1;
                   4178:                     }
                   4179:                 }
                   4180:             } else {
                   4181:                 if ($query eq 'usersearch') {
                   4182:                     if ($usersearchconf->{'lclocalonly'}) {
                   4183:                         $earlyout = 1;
                   4184:                     }
                   4185:                 } else {
                   4186:                     if ($usersearchconf->{'localonly'}) {
                   4187:                         $earlyout = 1;
                   4188:                     }
                   4189:                 }
                   4190:             }
                   4191:         }
                   4192:         if ($earlyout) {
                   4193:             &Reply($client, "query_not_authorized\n");
                   4194:             return 1;
                   4195:         }
                   4196:     }
1.234     foxr     4197:     &Reply($client, "". &sql_reply("$clientname\&$query".
                   4198: 				"\&$arg1"."\&$arg2"."\&$arg3")."\n",
                   4199: 	  $userinput);
                   4200:     
                   4201:     return 1;
                   4202: }
                   4203: &register_handler("querysend", \&send_query_handler, 0, 1, 0);
                   4204: 
                   4205: #
                   4206: #   Add a reply to an sql query.  SQL queries are done asyncrhonously.
                   4207: #   The query is submitted via a "querysend" transaction.
                   4208: #   There it is passed on to the lonsql daemon, queued and issued to
                   4209: #   mysql.
                   4210: #     This transaction is invoked when the sql transaction is complete
                   4211: #   it stores the query results in flie and indicates query completion.
                   4212: #   presumably local software then fetches this response... I'm guessing
                   4213: #   the sequence is: lonc does a querysend, we ask lonsql to do it.
                   4214: #   lonsql on completion of the query interacts with the lond of our
                   4215: #   client to do a query reply storing two files:
                   4216: #    - id     - The results of the query.
                   4217: #    - id.end - Indicating the transaction completed. 
                   4218: #    NOTE: id is a unique id assigned to the query and querysend time.
                   4219: # Parameters:
                   4220: #    $cmd        - Command keyword that initiated this request.
                   4221: #    $tail       - Remainder of the tail.  In this case that's a colon
                   4222: #                  separated list containing the query Id and the 
                   4223: #                  results of the query.
                   4224: #    $client     - Socket open on the client.
                   4225: # Return:
                   4226: #    1           - Indicating that we should continue processing.
                   4227: # Side effects:
                   4228: #    ok written to the client.
                   4229: #
                   4230: sub reply_query_handler {
                   4231:     my ($cmd, $tail, $client) = @_;
                   4232: 
                   4233: 
                   4234:     my $userinput = "$cmd:$tail";
                   4235: 
1.339     albertel 4236:     my ($id,$reply)=split(/:/,$tail); 
1.234     foxr     4237:     my $store;
                   4238:     my $execdir=$perlvar{'lonDaemons'};
                   4239:     if ($store=IO::File->new(">$execdir/tmp/$id")) {
                   4240: 	$reply=~s/\&/\n/g;
                   4241: 	print $store $reply;
                   4242: 	close $store;
                   4243: 	my $store2=IO::File->new(">$execdir/tmp/$id.end");
                   4244: 	print $store2 "done\n";
                   4245: 	close $store2;
                   4246: 	&Reply($client, "ok\n", $userinput);
                   4247:     } else {
                   4248: 	&Failure($client, "error: ".($!+0)
                   4249: 		." IO::File->new Failed ".
                   4250: 		"while attempting queryreply\n", $userinput);
                   4251:     }
                   4252:  
                   4253: 
                   4254:     return 1;
                   4255: }
                   4256: &register_handler("queryreply", \&reply_query_handler, 0, 1, 0);
                   4257: 
                   4258: #
                   4259: #  Process the courseidput request.  Not quite sure what this means
                   4260: #  at the system level sense.  It appears a gdbm file in the 
                   4261: #  /home/httpd/lonUsers/$domain/nohist_courseids is tied and
                   4262: #  a set of entries made in that database.
                   4263: #
                   4264: # Parameters:
                   4265: #   $cmd      - The command keyword that initiated this request.
                   4266: #   $tail     - Tail of the command.  In this case consists of a colon
                   4267: #               separated list contaning the domain to apply this to and
                   4268: #               an ampersand separated list of keyword=value pairs.
1.272     raeburn  4269: #               Each value is a colon separated list that includes:  
                   4270: #               description, institutional code and course owner.
                   4271: #               For backward compatibility with versions included
                   4272: #               in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
                   4273: #               code and/or course owner are preserved from the existing 
                   4274: #               record when writing a new record in response to 1.1 or 
                   4275: #               1.2 implementations of lonnet::flushcourselogs().   
                   4276: #                      
1.234     foxr     4277: #   $client   - Socket open on the client.
                   4278: # Returns:
                   4279: #   1    - indicating that processing should continue
                   4280: #
                   4281: # Side effects:
                   4282: #   reply is written to the client.
                   4283: #
                   4284: sub put_course_id_handler {
                   4285:     my ($cmd, $tail, $client) = @_;
                   4286: 
                   4287: 
                   4288:     my $userinput = "$cmd:$tail";
                   4289: 
1.266     raeburn  4290:     my ($udom, $what) = split(/:/, $tail,2);
1.234     foxr     4291:     chomp($what);
                   4292:     my $now=time;
                   4293:     my @pairs=split(/\&/,$what);
                   4294: 
                   4295:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   4296:     if ($hashref) {
                   4297: 	foreach my $pair (@pairs) {
1.271     raeburn  4298:             my ($key,$courseinfo) = split(/=/,$pair,2);
                   4299:             $courseinfo =~ s/=/:/g;
1.384     raeburn  4300:             if (defined($hashref->{$key})) {
                   4301:                 my $value = &Apache::lonnet::thaw_unescape($hashref->{$key});
                   4302:                 if (ref($value) eq 'HASH') {
                   4303:                     my @items = ('description','inst_code','owner','type');
                   4304:                     my @new_items = split(/:/,$courseinfo,-1);
                   4305:                     my %storehash; 
                   4306:                     for (my $i=0; $i<@new_items; $i++) {
1.391     raeburn  4307:                         $storehash{$items[$i]} = &unescape($new_items[$i]);
1.384     raeburn  4308:                     }
                   4309:                     $hashref->{$key} = 
                   4310:                         &Apache::lonnet::freeze_escape(\%storehash);
                   4311:                     my $unesc_key = &unescape($key);
                   4312:                     $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
                   4313:                     next;
1.383     raeburn  4314:                 }
1.384     raeburn  4315:             }
                   4316:             my @current_items = split(/:/,$hashref->{$key},-1);
                   4317:             shift(@current_items); # remove description
                   4318:             pop(@current_items);   # remove last access
                   4319:             my $numcurrent = scalar(@current_items);
                   4320:             if ($numcurrent > 3) {
                   4321:                 $numcurrent = 3;
                   4322:             }
                   4323:             my @new_items = split(/:/,$courseinfo,-1);
                   4324:             my $numnew = scalar(@new_items);
                   4325:             if ($numcurrent > 0) {
                   4326:                 if ($numnew <= $numcurrent) { # flushcourselogs() from pre 2.2 
                   4327:                     for (my $j=$numcurrent-$numnew; $j>=0; $j--) {
                   4328:                         $courseinfo .= ':'.$current_items[$numcurrent-$j-1];
1.333     raeburn  4329:                     }
1.272     raeburn  4330:                 }
                   4331:             }
1.384     raeburn  4332:             $hashref->{$key}=$courseinfo.':'.$now;
1.234     foxr     4333: 	}
1.311     albertel 4334: 	if (&untie_domain_hash($hashref)) {
1.253     foxr     4335: 	    &Reply( $client, "ok\n", $userinput);
1.234     foxr     4336: 	} else {
1.253     foxr     4337: 	    &Failure($client, "error: ".($!+0)
1.234     foxr     4338: 		     ." untie(GDBM) Failed ".
                   4339: 		     "while attempting courseidput\n", $userinput);
                   4340: 	}
                   4341:     } else {
1.253     foxr     4342: 	&Failure($client, "error: ".($!+0)
1.234     foxr     4343: 		 ." tie(GDBM) Failed ".
                   4344: 		 "while attempting courseidput\n", $userinput);
                   4345:     }
                   4346: 
                   4347:     return 1;
                   4348: }
                   4349: &register_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
                   4350: 
1.383     raeburn  4351: sub put_course_id_hash_handler {
                   4352:     my ($cmd, $tail, $client) = @_;
                   4353:     my $userinput = "$cmd:$tail";
1.384     raeburn  4354:     my ($udom,$mode,$what) = split(/:/, $tail,3);
1.383     raeburn  4355:     chomp($what);
                   4356:     my $now=time;
                   4357:     my @pairs=split(/\&/,$what);
1.384     raeburn  4358:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
1.383     raeburn  4359:     if ($hashref) {
                   4360:         foreach my $pair (@pairs) {
                   4361:             my ($key,$value)=split(/=/,$pair);
1.384     raeburn  4362:             my $unesc_key = &unescape($key);
                   4363:             if ($mode ne 'timeonly') {
                   4364:                 if (!defined($hashref->{&escape('lasttime:'.$unesc_key)})) {
                   4365:                     my $curritems = &Apache::lonnet::thaw_unescape($key); 
                   4366:                     if (ref($curritems) ne 'HASH') {
                   4367:                         my @current_items = split(/:/,$hashref->{$key},-1);
                   4368:                         my $lasttime = pop(@current_items);
                   4369:                         $hashref->{&escape('lasttime:'.$unesc_key)} = $lasttime;
                   4370:                     } else {
                   4371:                         $hashref->{&escape('lasttime:'.$unesc_key)} = '';
                   4372:                     }
                   4373:                 } 
                   4374:                 $hashref->{$key} = $value;
                   4375:             }
                   4376:             if ($mode ne 'notime') {
                   4377:                 $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
                   4378:             }
1.383     raeburn  4379:         }
                   4380:         if (&untie_domain_hash($hashref)) {
                   4381:             &Reply($client, "ok\n", $userinput);
                   4382:         } else {
                   4383:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4384:                      "while attempting courseidputhash\n", $userinput);
                   4385:         }
                   4386:     } else {
                   4387:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4388:                   "while attempting courseidputhash\n", $userinput);
                   4389:     }
                   4390:     return 1;
                   4391: }
                   4392: &register_handler("courseidputhash", \&put_course_id_hash_handler, 0, 1, 0);
                   4393: 
1.234     foxr     4394: #  Retrieves the value of a course id resource keyword pattern
                   4395: #  defined since a starting date.  Both the starting date and the
                   4396: #  keyword pattern are optional.  If the starting date is not supplied it
                   4397: #  is treated as the beginning of time.  If the pattern is not found,
                   4398: #  it is treatred as "." matching everything.
                   4399: #
                   4400: #  Parameters:
                   4401: #     $cmd     - Command keyword that resulted in us being dispatched.
                   4402: #     $tail    - The remainder of the command that, in this case, consists
                   4403: #                of a colon separated list of:
                   4404: #                 domain   - The domain in which the course database is 
                   4405: #                            defined.
                   4406: #                 since    - Optional parameter describing the minimum
                   4407: #                            time of definition(?) of the resources that
                   4408: #                            will match the dump.
                   4409: #                 description - regular expression that is used to filter
                   4410: #                            the dump.  Only keywords matching this regexp
                   4411: #                            will be used.
1.272     raeburn  4412: #                 institutional code - optional supplied code to filter 
                   4413: #                            the dump. Only courses with an institutional code 
                   4414: #                            that match the supplied code will be returned.
1.336     raeburn  4415: #                 owner    - optional supplied username and domain of owner to
                   4416: #                            filter the dump.  Only courses for which the course
                   4417: #                            owner matches the supplied username and/or domain
                   4418: #                            will be returned. Pre-2.2.0 legacy entries from 
                   4419: #                            nohist_courseiddump will only contain usernames.
1.384     raeburn  4420: #                 type     - optional parameter for selection 
1.418     raeburn  4421: #                 regexp_ok - if 1 or -1 allow the supplied institutional code
                   4422: #                            filter to behave as a regular expression:
                   4423: #	                      1 will not exclude the course if the instcode matches the RE 
                   4424: #                            -1 will exclude the course if the instcode matches the RE
1.384     raeburn  4425: #                 rtn_as_hash - whether to return the information available for
                   4426: #                            each matched item as a frozen hash of all 
                   4427: #                            key, value pairs in the item's hash, or as a 
                   4428: #                            colon-separated list of (in order) description,
                   4429: #                            institutional code, and course owner.
1.404     raeburn  4430: #                 selfenrollonly - filter by courses allowing self-enrollment  
                   4431: #                                  now or in the future (selfenrollonly = 1).
                   4432: #                 catfilter - filter by course category, assigned to a course 
                   4433: #                             using manually defined categories (i.e., not
1.407     raeburn  4434: #                             self-cataloging based on on institutional code).   
1.404     raeburn  4435: #                 showhidden - include course in results even if course  
1.407     raeburn  4436: #                              was set to be excluded from course catalog (DC only).
1.404     raeburn  4437: #                 caller -  if set to 'coursecatalog', courses set to be hidden
                   4438: #                           from course catalog will be excluded from results (unless
                   4439: #                           overridden by "showhidden".
1.427     raeburn  4440: #                 cloner - escaped username:domain of course cloner (if picking course to
1.419     raeburn  4441: #                          clone).
                   4442: #                 cc_clone_list - escaped comma separated list of courses for which 
                   4443: #                                 course cloner has active CC role (and so can clone
                   4444: #                                 automatically).
1.427     raeburn  4445: #                 cloneonly - filter by courses for which cloner has rights to clone.
                   4446: #                 createdbefore - include courses for which creation date preceeded this date.
                   4447: #                 createdafter - include courses for which creation date followed this date.
                   4448: #                 creationcontext - include courses created in specified context 
1.404     raeburn  4449: #
1.445     raeburn  4450: #                 domcloner - flag to indicate if user can create CCs in course's domain.
1.505     raeburn  4451: #                             If so, ability to clone course is automatic.
                   4452: #                 hasuniquecode - filter by courses for which a six character unique code has 
                   4453: #                                 been set.
1.445     raeburn  4454: #
1.234     foxr     4455: #     $client  - The socket open on the client.
                   4456: # Returns:
                   4457: #    1     - Continue processing.
                   4458: # Side Effects:
                   4459: #   a reply is written to $client.
                   4460: sub dump_course_id_handler {
                   4461:     my ($cmd, $tail, $client) = @_;
1.494     droeschl 4462: 
                   4463:     my $res = LONCAPA::Lond::dump_course_id_handler($tail);
                   4464:     if ($res =~ /^error:/) {
                   4465:         Failure($client, \$res, "$cmd:$tail");
                   4466:     } else {
                   4467:         Reply($client, \$res, "$cmd:$tail");
                   4468:     }
                   4469: 
                   4470:     return 1;  
                   4471: 
                   4472:     #TODO remove
1.234     foxr     4473:     my $userinput = "$cmd:$tail";
                   4474: 
1.333     raeburn  4475:     my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter,
1.404     raeburn  4476:         $typefilter,$regexp_ok,$rtn_as_hash,$selfenrollonly,$catfilter,$showhidden,
1.427     raeburn  4477:         $caller,$cloner,$cc_clone_list,$cloneonly,$createdbefore,$createdafter,
1.505     raeburn  4478:         $creationcontext,$domcloner,$hasuniquecode) =split(/:/,$tail);
1.397     raeburn  4479:     my $now = time;
1.419     raeburn  4480:     my ($cloneruname,$clonerudom,%cc_clone);
1.234     foxr     4481:     if (defined($description)) {
                   4482: 	$description=&unescape($description);
                   4483:     } else {
                   4484: 	$description='.';
                   4485:     }
1.266     raeburn  4486:     if (defined($instcodefilter)) {
                   4487:         $instcodefilter=&unescape($instcodefilter);
                   4488:     } else {
                   4489:         $instcodefilter='.';
                   4490:     }
1.336     raeburn  4491:     my ($ownerunamefilter,$ownerdomfilter);
1.266     raeburn  4492:     if (defined($ownerfilter)) {
                   4493:         $ownerfilter=&unescape($ownerfilter);
1.336     raeburn  4494:         if ($ownerfilter ne '.' && defined($ownerfilter)) {
                   4495:             if ($ownerfilter =~ /^([^:]*):([^:]*)$/) {
                   4496:                  $ownerunamefilter = $1;
                   4497:                  $ownerdomfilter = $2;
                   4498:             } else {
                   4499:                 $ownerunamefilter = $ownerfilter;
                   4500:                 $ownerdomfilter = '';
                   4501:             }
                   4502:         }
1.266     raeburn  4503:     } else {
                   4504:         $ownerfilter='.';
                   4505:     }
1.336     raeburn  4506: 
1.282     raeburn  4507:     if (defined($coursefilter)) {
                   4508:         $coursefilter=&unescape($coursefilter);
                   4509:     } else {
                   4510:         $coursefilter='.';
                   4511:     }
1.333     raeburn  4512:     if (defined($typefilter)) {
                   4513:         $typefilter=&unescape($typefilter);
                   4514:     } else {
                   4515:         $typefilter='.';
                   4516:     }
1.344     raeburn  4517:     if (defined($regexp_ok)) {
                   4518:         $regexp_ok=&unescape($regexp_ok);
                   4519:     }
1.401     raeburn  4520:     if (defined($catfilter)) {
                   4521:         $catfilter=&unescape($catfilter);
                   4522:     }
1.419     raeburn  4523:     if (defined($cloner)) {
                   4524:         $cloner = &unescape($cloner);
                   4525:         ($cloneruname,$clonerudom) = ($cloner =~ /^($LONCAPA::match_username):($LONCAPA::match_domain)$/); 
                   4526:     }
                   4527:     if (defined($cc_clone_list)) {
                   4528:         $cc_clone_list = &unescape($cc_clone_list);
                   4529:         my @cc_cloners = split('&',$cc_clone_list);
                   4530:         foreach my $cid (@cc_cloners) {
                   4531:             my ($clonedom,$clonenum) = split(':',$cid);
                   4532:             next if ($clonedom ne $udom); 
                   4533:             $cc_clone{$clonedom.'_'.$clonenum} = 1;
                   4534:         } 
                   4535:     }
1.431     raeburn  4536:     if ($createdbefore ne '') {
1.427     raeburn  4537:         $createdbefore = &unescape($createdbefore);
                   4538:     } else {
                   4539:        $createdbefore = 0;
                   4540:     }
1.431     raeburn  4541:     if ($createdafter ne '') {
1.427     raeburn  4542:         $createdafter = &unescape($createdafter);
                   4543:     } else {
                   4544:         $createdafter = 0;
                   4545:     }
1.431     raeburn  4546:     if ($creationcontext ne '') {
1.427     raeburn  4547:         $creationcontext = &unescape($creationcontext);
                   4548:     } else {
                   4549:         $creationcontext = '.';
                   4550:     }
1.505     raeburn  4551:     unless ($hasuniquecode) {
                   4552:         $hasuniquecode = '.';
                   4553:     }
1.384     raeburn  4554:     my $unpack = 1;
1.485     raeburn  4555:     if ($description eq '.' && $instcodefilter eq '.' && $ownerfilter eq '.' && 
1.384     raeburn  4556:         $typefilter eq '.') {
                   4557:         $unpack = 0;
                   4558:     }
                   4559:     if (!defined($since)) { $since=0; }
1.234     foxr     4560:     my $qresult='';
                   4561:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   4562:     if ($hashref) {
1.384     raeburn  4563: 	while (my ($key,$value) = each(%$hashref)) {
1.397     raeburn  4564:             my ($unesc_key,$lasttime_key,$lasttime,$is_hash,%val,
1.427     raeburn  4565:                 %unesc_val,$selfenroll_end,$selfenroll_types,$created,
                   4566:                 $context);
1.384     raeburn  4567:             $unesc_key = &unescape($key);
                   4568:             if ($unesc_key =~ /^lasttime:/) {
                   4569:                 next;
                   4570:             } else {
                   4571:                 $lasttime_key = &escape('lasttime:'.$unesc_key);
                   4572:             }
                   4573:             if ($hashref->{$lasttime_key} ne '') {
                   4574:                 $lasttime = $hashref->{$lasttime_key};
                   4575:                 next if ($lasttime<$since);
                   4576:             }
1.419     raeburn  4577:             my ($canclone,$valchange);
1.384     raeburn  4578:             my $items = &Apache::lonnet::thaw_unescape($value);
                   4579:             if (ref($items) eq 'HASH') {
1.429     raeburn  4580:                 if ($hashref->{$lasttime_key} eq '') {
1.430     raeburn  4581:                     next if ($since > 1);
1.429     raeburn  4582:                 }
1.384     raeburn  4583:                 $is_hash =  1;
1.445     raeburn  4584:                 if ($domcloner) {
                   4585:                     $canclone = 1;
                   4586:                 } elsif (defined($clonerudom)) {
1.419     raeburn  4587:                     if ($items->{'cloners'}) {
                   4588:                         my @cloneable = split(',',$items->{'cloners'});
                   4589:                         if (@cloneable) {
                   4590:                             if (grep(/^\*$/,@cloneable))  {
                   4591:                                 $canclone = 1;
                   4592:                             } elsif (grep(/^\*:\Q$clonerudom\E$/,@cloneable)) {
                   4593:                                 $canclone = 1;
                   4594:                             } elsif (grep(/^\Q$cloneruname\E:\Q$clonerudom\E$/,@cloneable)) {
                   4595:                                 $canclone = 1;
                   4596:                             }
                   4597:                         }
                   4598:                         unless ($canclone) {
                   4599:                             if ($cloneruname ne '' && $clonerudom ne '') {
                   4600:                                 if ($cc_clone{$unesc_key}) {
                   4601:                                     $canclone = 1;
                   4602:                                     $items->{'cloners'} .= ','.$cloneruname.':'.
                   4603:                                                            $clonerudom;
                   4604:                                     $valchange = 1;
                   4605:                                 }
                   4606:                             }
                   4607:                         }
                   4608:                     } elsif (defined($cloneruname)) {
                   4609:                         if ($cc_clone{$unesc_key}) {
                   4610:                             $canclone = 1;
                   4611:                             $items->{'cloners'} = $cloneruname.':'.$clonerudom;
                   4612:                             $valchange = 1;
                   4613:                         }
1.437     raeburn  4614:                         unless ($canclone) {
                   4615:                             if ($items->{'owner'} =~ /:/) {
                   4616:                                 if ($items->{'owner'} eq $cloner) {
                   4617:                                     $canclone = 1;
                   4618:                                 }
1.444     raeburn  4619:                             } elsif ($cloner eq $items->{'owner'}.':'.$udom) {
1.437     raeburn  4620:                                 $canclone = 1;
                   4621:                             }
                   4622:                             if ($canclone) {
                   4623:                                 $items->{'cloners'} = $cloneruname.':'.$clonerudom;
                   4624:                                 $valchange = 1;
                   4625:                             }
                   4626:                         }
1.419     raeburn  4627:                     }
                   4628:                 }
1.384     raeburn  4629:                 if ($unpack || !$rtn_as_hash) {
                   4630:                     $unesc_val{'descr'} = $items->{'description'};
                   4631:                     $unesc_val{'inst_code'} = $items->{'inst_code'};
                   4632:                     $unesc_val{'owner'} = $items->{'owner'};
                   4633:                     $unesc_val{'type'} = $items->{'type'};
1.419     raeburn  4634:                     $unesc_val{'cloners'} = $items->{'cloners'};
1.427     raeburn  4635:                     $unesc_val{'created'} = $items->{'created'};
                   4636:                     $unesc_val{'context'} = $items->{'context'};
1.404     raeburn  4637:                 }
                   4638:                 $selfenroll_types = $items->{'selfenroll_types'};
                   4639:                 $selfenroll_end = $items->{'selfenroll_end_date'};
1.427     raeburn  4640:                 $created = $items->{'created'};
                   4641:                 $context = $items->{'context'};
1.505     raeburn  4642:                 if ($hasuniquecode ne '.') {
                   4643:                     next unless ($items->{'uniquecode'});
                   4644:                 }
1.404     raeburn  4645:                 if ($selfenrollonly) {
                   4646:                     next if (!$selfenroll_types);
                   4647:                     if (($selfenroll_end > 0) && ($selfenroll_end <= $now)) {
                   4648:                         next;
1.397     raeburn  4649:                     }
1.404     raeburn  4650:                 }
1.427     raeburn  4651:                 if ($creationcontext ne '.') {
                   4652:                     next if (($context ne '') && ($context ne $creationcontext));  
                   4653:                 }
                   4654:                 if ($createdbefore > 0) {
                   4655:                     next if (($created eq '') || ($created > $createdbefore));   
                   4656:                 }
                   4657:                 if ($createdafter > 0) {
                   4658:                     next if (($created eq '') || ($created <= $createdafter)); 
                   4659:                 }
1.404     raeburn  4660:                 if ($catfilter ne '') {
1.406     raeburn  4661:                     next if ($items->{'categories'} eq '');
                   4662:                     my @categories = split('&',$items->{'categories'}); 
1.407     raeburn  4663:                     next if (@categories == 0);
                   4664:                     my @subcats = split('&',$catfilter);
                   4665:                     my $matchcat = 0;
                   4666:                     foreach my $cat (@categories) {
                   4667:                         if (grep(/^\Q$cat\E$/,@subcats)) {
                   4668:                             $matchcat = 1;
                   4669:                             last;
                   4670:                         }
                   4671:                     }
                   4672:                     next if (!$matchcat);
1.404     raeburn  4673:                 }
                   4674:                 if ($caller eq 'coursecatalog') {
1.405     raeburn  4675:                     if ($items->{'hidefromcat'} eq 'yes') {
                   4676:                         next if !$showhidden;
1.401     raeburn  4677:                     }
1.384     raeburn  4678:                 }
1.383     raeburn  4679:             } else {
1.401     raeburn  4680:                 next if ($catfilter ne '');
1.419     raeburn  4681:                 next if ($selfenrollonly);
1.427     raeburn  4682:                 next if ($createdbefore || $createdafter);
                   4683:                 next if ($creationcontext ne '.');
1.419     raeburn  4684:                 if ((defined($clonerudom)) && (defined($cloneruname)))  {
                   4685:                     if ($cc_clone{$unesc_key}) {
                   4686:                         $canclone = 1;
                   4687:                         $val{'cloners'} = &escape($cloneruname.':'.$clonerudom);
                   4688:                     }
                   4689:                 }
1.384     raeburn  4690:                 $is_hash =  0;
1.388     raeburn  4691:                 my @courseitems = split(/:/,$value);
1.403     raeburn  4692:                 $lasttime = pop(@courseitems);
1.402     raeburn  4693:                 if ($hashref->{$lasttime_key} eq '') {
                   4694:                     next if ($lasttime<$since);
                   4695:                 }
1.384     raeburn  4696: 	        ($val{'descr'},$val{'inst_code'},$val{'owner'},$val{'type'}) = @courseitems;
1.383     raeburn  4697:             }
1.419     raeburn  4698:             if ($cloneonly) {
                   4699:                next unless ($canclone);
                   4700:             }
1.266     raeburn  4701:             my $match = 1;
1.384     raeburn  4702: 	    if ($description ne '.') {
                   4703:                 if (!$is_hash) {
                   4704:                     $unesc_val{'descr'} = &unescape($val{'descr'});
                   4705:                 }
                   4706:                 if (eval{$unesc_val{'descr'} !~ /\Q$description\E/i}) {
1.266     raeburn  4707:                     $match = 0;
1.384     raeburn  4708:                 }
1.266     raeburn  4709:             }
1.384     raeburn  4710:             if ($instcodefilter ne '.') {
                   4711:                 if (!$is_hash) {
                   4712:                     $unesc_val{'inst_code'} = &unescape($val{'inst_code'});
                   4713:                 }
1.418     raeburn  4714:                 if ($regexp_ok == 1) {
1.384     raeburn  4715:                     if (eval{$unesc_val{'inst_code'} !~ /$instcodefilter/}) {
1.344     raeburn  4716:                         $match = 0;
                   4717:                     }
1.418     raeburn  4718:                 } elsif ($regexp_ok == -1) {
                   4719:                     if (eval{$unesc_val{'inst_code'} =~ /$instcodefilter/}) {
                   4720:                         $match = 0;
                   4721:                     }
1.344     raeburn  4722:                 } else {
1.384     raeburn  4723:                     if (eval{$unesc_val{'inst_code'} !~ /\Q$instcodefilter\E/i}) {
1.344     raeburn  4724:                         $match = 0;
                   4725:                     }
1.266     raeburn  4726:                 }
1.234     foxr     4727: 	    }
1.384     raeburn  4728:             if ($ownerfilter ne '.') {
                   4729:                 if (!$is_hash) {
                   4730:                     $unesc_val{'owner'} = &unescape($val{'owner'});
                   4731:                 }
1.336     raeburn  4732:                 if (($ownerunamefilter ne '') && ($ownerdomfilter ne '')) {
1.384     raeburn  4733:                     if ($unesc_val{'owner'} =~ /:/) {
                   4734:                         if (eval{$unesc_val{'owner'} !~ 
                   4735:                              /\Q$ownerunamefilter\E:\Q$ownerdomfilter\E$/i}) {
1.336     raeburn  4736:                             $match = 0;
                   4737:                         } 
                   4738:                     } else {
1.384     raeburn  4739:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336     raeburn  4740:                             $match = 0;
                   4741:                         }
                   4742:                     }
                   4743:                 } elsif ($ownerunamefilter ne '') {
1.384     raeburn  4744:                     if ($unesc_val{'owner'} =~ /:/) {
                   4745:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E:[^:]+$/i}) {
1.336     raeburn  4746:                              $match = 0;
                   4747:                         }
                   4748:                     } else {
1.384     raeburn  4749:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336     raeburn  4750:                             $match = 0;
                   4751:                         }
                   4752:                     }
                   4753:                 } elsif ($ownerdomfilter ne '') {
1.384     raeburn  4754:                     if ($unesc_val{'owner'} =~ /:/) {
                   4755:                         if (eval{$unesc_val{'owner'} !~ /^[^:]+:\Q$ownerdomfilter\E/}) {
1.336     raeburn  4756:                              $match = 0;
                   4757:                         }
                   4758:                     } else {
                   4759:                         if ($ownerdomfilter ne $udom) {
                   4760:                             $match = 0;
                   4761:                         }
                   4762:                     }
1.266     raeburn  4763:                 }
                   4764:             }
1.384     raeburn  4765:             if ($coursefilter ne '.') {
                   4766:                 if (eval{$unesc_key !~ /^$udom(_)\Q$coursefilter\E$/}) {
1.282     raeburn  4767:                     $match = 0;
                   4768:                 }
                   4769:             }
1.384     raeburn  4770:             if ($typefilter ne '.') {
                   4771:                 if (!$is_hash) {
                   4772:                     $unesc_val{'type'} = &unescape($val{'type'});
                   4773:                 }
                   4774:                 if ($unesc_val{'type'} eq '') {
1.333     raeburn  4775:                     if ($typefilter ne 'Course') {
                   4776:                         $match = 0;
                   4777:                     }
1.383     raeburn  4778:                 } else {
1.384     raeburn  4779:                     if (eval{$unesc_val{'type'} !~ /^\Q$typefilter\E$/}) {
1.333     raeburn  4780:                         $match = 0;
                   4781:                     }
                   4782:                 }
                   4783:             }
1.266     raeburn  4784:             if ($match == 1) {
1.384     raeburn  4785:                 if ($rtn_as_hash) {
                   4786:                     if ($is_hash) {
1.419     raeburn  4787:                         if ($valchange) {
                   4788:                             my $newvalue = &Apache::lonnet::freeze_escape($items);
                   4789:                             $qresult.=$key.'='.$newvalue.'&';
                   4790:                         } else {
                   4791:                             $qresult.=$key.'='.$value.'&';
                   4792:                         }
1.384     raeburn  4793:                     } else {
1.388     raeburn  4794:                         my %rtnhash = ( 'description' => &unescape($val{'descr'}),
                   4795:                                         'inst_code' => &unescape($val{'inst_code'}),
                   4796:                                         'owner'     => &unescape($val{'owner'}),
                   4797:                                         'type'      => &unescape($val{'type'}),
1.419     raeburn  4798:                                         'cloners'   => &unescape($val{'cloners'}),
1.384     raeburn  4799:                                       );
                   4800:                         my $items = &Apache::lonnet::freeze_escape(\%rtnhash);
                   4801:                         $qresult.=$key.'='.$items.'&';
                   4802:                     }
1.383     raeburn  4803:                 } else {
1.384     raeburn  4804:                     if ($is_hash) {
                   4805:                         $qresult .= $key.'='.&escape($unesc_val{'descr'}).':'.
                   4806:                                     &escape($unesc_val{'inst_code'}).':'.
                   4807:                                     &escape($unesc_val{'owner'}).'&';
                   4808:                     } else {
                   4809:                         $qresult .= $key.'='.$val{'descr'}.':'.$val{'inst_code'}.
                   4810:                                     ':'.$val{'owner'}.'&';
                   4811:                     }
1.383     raeburn  4812:                 }
1.266     raeburn  4813:             }
1.234     foxr     4814: 	}
1.311     albertel 4815: 	if (&untie_domain_hash($hashref)) {
1.234     foxr     4816: 	    chop($qresult);
1.387     albertel 4817: 	    &Reply($client, \$qresult, $userinput);
1.234     foxr     4818: 	} else {
                   4819: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4820: 		    "while attempting courseiddump\n", $userinput);
                   4821: 	}
                   4822:     } else {
                   4823: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4824: 		"while attempting courseiddump\n", $userinput);
                   4825:     }
                   4826:     return 1;
                   4827: }
                   4828: &register_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
1.238     foxr     4829: 
1.438     raeburn  4830: sub course_lastaccess_handler {
                   4831:     my ($cmd, $tail, $client) = @_;
                   4832:     my $userinput = "$cmd:$tail";
                   4833:     my ($cdom,$cnum) = split(':',$tail); 
                   4834:     my (%lastaccess,$qresult);
                   4835:     my $hashref = &tie_domain_hash($cdom, "nohist_courseids", &GDBM_WRCREAT());
                   4836:     if ($hashref) {
                   4837:         while (my ($key,$value) = each(%$hashref)) {
                   4838:             my ($unesc_key,$lasttime);
                   4839:             $unesc_key = &unescape($key);
                   4840:             if ($cnum) {
                   4841:                 next unless ($unesc_key =~ /\Q$cdom\E_\Q$cnum\E$/);
                   4842:             }
                   4843:             if ($unesc_key =~ /^lasttime:($LONCAPA::match_domain\_$LONCAPA::match_courseid)/) {
                   4844:                 $lastaccess{$1} = $value;
                   4845:             } else {
                   4846:                 my $items = &Apache::lonnet::thaw_unescape($value);
                   4847:                 if (ref($items) eq 'HASH') {
                   4848:                     unless ($lastaccess{$unesc_key}) {
                   4849:                         $lastaccess{$unesc_key} = '';
                   4850:                     }
                   4851:                 } else {
                   4852:                     my @courseitems = split(':',$value);
                   4853:                     $lastaccess{$unesc_key} = pop(@courseitems);
                   4854:                 }
                   4855:             }
                   4856:         }
                   4857:         foreach my $cid (sort(keys(%lastaccess))) {
                   4858:             $qresult.=&escape($cid).'='.$lastaccess{$cid}.'&'; 
                   4859:         }
                   4860:         if (&untie_domain_hash($hashref)) {
                   4861:             if ($qresult) {
                   4862:                 chop($qresult);
                   4863:             }
                   4864:             &Reply($client, \$qresult, $userinput);
                   4865:         } else {
                   4866:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4867:                     "while attempting lastacourseaccess\n", $userinput);
                   4868:         }
                   4869:     } else {
                   4870:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4871:                 "while attempting lastcourseaccess\n", $userinput);
                   4872:     }
                   4873:     return 1;
                   4874: }
                   4875: &register_handler("courselastaccess",\&course_lastaccess_handler, 0, 1, 0);
                   4876: 
1.561     raeburn  4877: sub course_sessions_handler {
                   4878:     my ($cmd, $tail, $client) = @_;
                   4879:     my $userinput = "$cmd:$tail";
                   4880:     my ($cdom,$cnum,$lastactivity) = split(':',$tail);
                   4881:     my $dbsuffix = '_'.$cdom.'_'.$cnum.'.db';
                   4882:     my (%sessions,$qresult);
                   4883:     my $now=time;
                   4884:     if (opendir(DIR,$perlvar{'lonIDsDir'})) {
                   4885:         my $filename;
                   4886:         while ($filename=readdir(DIR)) {
                   4887:             next if ($filename=~/^\./);
                   4888:             next if ($filename=~/^publicuser_/);
                   4889:             next if ($filename=~/^[a-f0-9]+_(linked|lti_\d+)\.id$/);
1.562     raeburn  4890:             if ($filename =~ /^($LONCAPA::match_username)_\d+_($LONCAPA::match_domain)_/) {
1.561     raeburn  4891:                 my ($uname,$udom) = ($1,$2);
1.562     raeburn  4892:                 next unless (-e "$perlvar{'lonDaemons'}/tmp/$uname$dbsuffix");
1.561     raeburn  4893:                 my $mtime = (stat("$perlvar{'lonIDsDir'}/$filename"))[9];
                   4894:                 if ($lastactivity < 0) {
1.563   ! raeburn  4895:                     next if ($mtime-$now > $lastactivity);
1.561     raeburn  4896:                 } else {
1.563   ! raeburn  4897:                     next if ($now-$mtime > $lastactivity);
1.561     raeburn  4898:                 }
                   4899:                 $sessions{$uname.':'.$udom} = $mtime;
                   4900:             }
                   4901:         }
                   4902:         closedir(DIR); 
                   4903:     }
                   4904:     foreach my $user (keys(%sessions)) {
                   4905:         $qresult.=&escape($user).'='.$sessions{$user}.'&';
                   4906:     }
                   4907:     if ($qresult) {
                   4908:         chop($qresult);
                   4909:     }
                   4910:     &Reply($client, \$qresult, $userinput);
                   4911:     return 1;
                   4912: }
                   4913: &register_handler("coursesessions",\&course_sessions_handler, 0, 1, 0);
                   4914: 
1.238     foxr     4915: #
1.348     raeburn  4916: # Puts an unencrypted entry in a namespace db file at the domain level 
                   4917: #
                   4918: # Parameters:
                   4919: #    $cmd      - The command that got us here.
                   4920: #    $tail     - Tail of the command (remaining parameters).
                   4921: #    $client   - File descriptor connected to client.
                   4922: # Returns
                   4923: #     0        - Requested to exit, caller should shut down.
                   4924: #     1        - Continue processing.
                   4925: #  Side effects:
                   4926: #     reply is written to $client.
                   4927: #
                   4928: sub put_domain_handler {
                   4929:     my ($cmd,$tail,$client) = @_;
                   4930: 
                   4931:     my $userinput = "$cmd:$tail";
                   4932: 
                   4933:     my ($udom,$namespace,$what) =split(/:/,$tail,3);
                   4934:     chomp($what);
                   4935:     my @pairs=split(/\&/,$what);
                   4936:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_WRCREAT(),
                   4937:                                    "P", $what);
                   4938:     if ($hashref) {
                   4939:         foreach my $pair (@pairs) {
                   4940:             my ($key,$value)=split(/=/,$pair);
                   4941:             $hashref->{$key}=$value;
                   4942:         }
                   4943:         if (&untie_domain_hash($hashref)) {
                   4944:             &Reply($client, "ok\n", $userinput);
                   4945:         } else {
                   4946:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4947:                      "while attempting putdom\n", $userinput);
                   4948:         }
                   4949:     } else {
                   4950:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4951:                   "while attempting putdom\n", $userinput);
                   4952:     }
                   4953: 
                   4954:     return 1;
                   4955: }
                   4956: &register_handler("putdom", \&put_domain_handler, 0, 1, 0);
                   4957: 
1.517     raeburn  4958: # Updates one or more entries in clickers.db file at the domain level
                   4959: #
                   4960: # Parameters:
                   4961: #    $cmd      - The command that got us here.
                   4962: #    $tail     - Tail of the command (remaining parameters).
                   4963: #                In this case a colon separated list containing:
                   4964: #                (a) the domain for which we are updating the entries,
                   4965: #                (b) the action required -- add or del -- and
                   4966: #                (c) a &-separated list of entries to add or delete.
                   4967: #    $client   - File descriptor connected to client.
                   4968: # Returns
                   4969: #     1        - Continue processing.
                   4970: #     0        - Requested to exit, caller should shut down.
                   4971: #  Side effects:
                   4972: #     reply is written to $client.
                   4973: #
                   4974: 
                   4975: 
                   4976: sub update_clickers {
                   4977:     my ($cmd, $tail, $client)  = @_;
                   4978: 
                   4979:     my $userinput = "$cmd:$tail";
                   4980:     my ($udom,$action,$what) =split(/:/,$tail,3);
                   4981:     chomp($what);
                   4982: 
                   4983:     my $hashref = &tie_domain_hash($udom, "clickers", &GDBM_WRCREAT(),
                   4984:                                  "U","$action:$what");
                   4985: 
                   4986:     if (!$hashref) {
                   4987:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4988:                   "while attempting updateclickers\n", $userinput);
                   4989:         return 1;
                   4990:     }
                   4991: 
                   4992:     my @pairs=split(/\&/,$what);
                   4993:     foreach my $pair (@pairs) {
                   4994:         my ($key,$value)=split(/=/,$pair);
                   4995:         if ($action eq 'add') {
                   4996:             if (exists($hashref->{$key})) {
                   4997:                 my @newvals = split(/,/,&unescape($value));
                   4998:                 my @currvals = split(/,/,&unescape($hashref->{$key}));
                   4999:                 my @merged = sort(keys(%{{map { $_ => 1 } (@newvals,@currvals)}}));
                   5000:                 $hashref->{$key}=&escape(join(',',@merged));
                   5001:             } else {
                   5002:                 $hashref->{$key}=$value;
                   5003:             }
                   5004:         } elsif ($action eq 'del') {
                   5005:             if (exists($hashref->{$key})) {
                   5006:                 my %current;
                   5007:                 map { $current{$_} = 1; } split(/,/,&unescape($hashref->{$key}));
                   5008:                 map { delete($current{$_}); } split(/,/,&unescape($value));
                   5009:                 if (keys(%current)) {
                   5010:                     $hashref->{$key}=&escape(join(',',sort(keys(%current))));
                   5011:                 } else {
                   5012:                     delete($hashref->{$key});
                   5013:                 }
                   5014:             }
                   5015:         }
                   5016:     }
                   5017:     if (&untie_user_hash($hashref)) {
                   5018:         &Reply( $client, "ok\n", $userinput);
                   5019:     } else {
                   5020:         &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   5021:                  "while attempting put\n",
                   5022:                  $userinput);
                   5023:     }
                   5024:     return 1;
                   5025: }
                   5026: &register_handler("updateclickers", \&update_clickers, 0, 1, 0);
                   5027: 
                   5028: 
                   5029: # Deletes one or more entries in a namespace db file at the domain level
                   5030: #
                   5031: # Parameters:
                   5032: #    $cmd      - The command that got us here.
                   5033: #    $tail     - Tail of the command (remaining parameters).
                   5034: #                In this case a colon separated list containing:
                   5035: #                (a) the domain for which we are deleting the entries,
                   5036: #                (b) &-separated list of keys to delete.  
                   5037: #    $client   - File descriptor connected to client.
                   5038: # Returns
                   5039: #     1        - Continue processing.
                   5040: #     0        - Requested to exit, caller should shut down.
                   5041: #  Side effects:
                   5042: #     reply is written to $client.
                   5043: #
                   5044: 
                   5045: sub del_domain_handler {
                   5046:     my ($cmd,$tail,$client) = @_;
                   5047: 
                   5048:     my $userinput = "$cmd:$tail";
                   5049: 
                   5050:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   5051:     chomp($what);
                   5052:     my $hashref = &tie_domain_hash($udom,$namespace,&GDBM_WRCREAT(),
                   5053:                                    "D", $what);
                   5054:     if ($hashref) {
                   5055:         my @keys=split(/\&/,$what);
                   5056:         foreach my $key (@keys) {
                   5057:             delete($hashref->{$key});
                   5058:         }
                   5059:         if (&untie_user_hash($hashref)) {
                   5060:             &Reply($client, "ok\n", $userinput);
                   5061:         } else {
                   5062:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5063:                     "while attempting deldom\n", $userinput);
                   5064:         }
                   5065:     } else {
                   5066:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5067:                  "while attempting deldom\n", $userinput);
                   5068:     }
                   5069:     return 1;
                   5070: }
                   5071: &register_handler("deldom", \&del_domain_handler, 0, 1, 0);
                   5072: 
                   5073: 
1.348     raeburn  5074: # Unencrypted get from the namespace database file at the domain level.
                   5075: # This function retrieves a keyed item from a specific named database in the
                   5076: # domain directory.
                   5077: #
                   5078: # Parameters:
                   5079: #   $cmd             - Command request keyword (get).
                   5080: #   $tail            - Tail of the command.  This is a colon separated list
                   5081: #                      consisting of the domain and the 'namespace' 
                   5082: #                      which selects the gdbm file to do the lookup in,
                   5083: #                      & separated list of keys to lookup.  Note that
                   5084: #                      the values are returned as an & separated list too.
                   5085: #   $client          - File descriptor open on the client.
                   5086: # Returns:
                   5087: #   1       - Continue processing.
                   5088: #   0       - Exit.
                   5089: #  Side effects:
                   5090: #     reply is written to $client.
                   5091: #
                   5092: 
                   5093: sub get_domain_handler {
                   5094:     my ($cmd, $tail, $client) = @_;
                   5095: 
1.461     foxr     5096: 
1.536     raeburn  5097:     my $userinput = "$cmd:$tail";
                   5098: 
                   5099:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   5100:     chomp($what);
                   5101:     if ($namespace =~ /^enc/) {
                   5102:         &Failure( $client, "refused\n", $userinput);
                   5103:     } else {
                   5104:         my @queries=split(/\&/,$what);
                   5105:         my $qresult='';
                   5106:         my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_READER());
                   5107:         if ($hashref) {
                   5108:             for (my $i=0;$i<=$#queries;$i++) {
                   5109:                 $qresult.="$hashref->{$queries[$i]}&";
                   5110:             }
                   5111:             if (&untie_domain_hash($hashref)) {
                   5112:                 $qresult=~s/\&$//;
                   5113:                 &Reply($client, \$qresult, $userinput);
                   5114:             } else {
                   5115:                 &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5116:                           "while attempting getdom\n",$userinput);
                   5117:             }
                   5118:         } else {
                   5119:             &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5120:                      "while attempting getdom\n",$userinput);
                   5121:         }
                   5122:     }
                   5123: 
                   5124:     return 1;
                   5125: }
                   5126: &register_handler("getdom", \&get_domain_handler, 0, 1, 0);
                   5127: 
                   5128: sub encrypted_get_domain_handler {
                   5129:     my ($cmd, $tail, $client) = @_;
                   5130: 
                   5131:     my $userinput = "$cmd:$tail";
1.348     raeburn  5132: 
                   5133:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   5134:     chomp($what);
                   5135:     my @queries=split(/\&/,$what);
                   5136:     my $qresult='';
                   5137:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_READER());
                   5138:     if ($hashref) {
                   5139:         for (my $i=0;$i<=$#queries;$i++) {
                   5140:             $qresult.="$hashref->{$queries[$i]}&";
                   5141:         }
                   5142:         if (&untie_domain_hash($hashref)) {
                   5143:             $qresult=~s/\&$//;
1.536     raeburn  5144:             if ($cipher) {
                   5145:                 my $cmdlength=length($qresult);
                   5146:                 $qresult.="         ";
                   5147:                 my $encqresult='';
                   5148:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   5149:                     $encqresult.= unpack("H16",
                   5150:                                          $cipher->encrypt(substr($qresult,
                   5151:                                                                  $encidx,
                   5152:                                                                  8)));
                   5153:                 }
                   5154:                 &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
                   5155:             } else {
                   5156:                 &Failure( $client, "error:no_key\n", $userinput);
                   5157:             }
1.348     raeburn  5158:         } else {
                   5159:             &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
1.536     raeburn  5160:                       "while attempting egetdom\n",$userinput);
1.348     raeburn  5161:         }
                   5162:     } else {
                   5163:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
1.536     raeburn  5164:                  "while attempting egetdom\n",$userinput);
1.348     raeburn  5165:     }
                   5166:     return 1;
                   5167: }
1.536     raeburn  5168: &register_handler("egetdom", \&encrypted_get_domain_handler, 1, 1, 0);
1.348     raeburn  5169: 
1.420     raeburn  5170: #
1.238     foxr     5171: #  Puts an id to a domains id database. 
                   5172: #
                   5173: #  Parameters:
                   5174: #   $cmd     - The command that triggered us.
                   5175: #   $tail    - Remainder of the request other than the command. This is a 
                   5176: #              colon separated list containing:
                   5177: #              $domain  - The domain for which we are writing the id.
                   5178: #              $pairs  - The id info to write... this is and & separated list
                   5179: #                        of keyword=value.
                   5180: #   $client  - Socket open on the client.
                   5181: #  Returns:
                   5182: #    1   - Continue processing.
                   5183: #  Side effects:
                   5184: #     reply is written to $client.
                   5185: #
                   5186: sub put_id_handler {
                   5187:     my ($cmd,$tail,$client) = @_;
                   5188: 
                   5189: 
                   5190:     my $userinput = "$cmd:$tail";
                   5191: 
                   5192:     my ($udom,$what)=split(/:/,$tail);
                   5193:     chomp($what);
                   5194:     my @pairs=split(/\&/,$what);
                   5195:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   5196: 				   "P", $what);
                   5197:     if ($hashref) {
                   5198: 	foreach my $pair (@pairs) {
                   5199: 	    my ($key,$value)=split(/=/,$pair);
                   5200: 	    $hashref->{$key}=$value;
                   5201: 	}
1.311     albertel 5202: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     5203: 	    &Reply($client, "ok\n", $userinput);
                   5204: 	} else {
                   5205: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5206: 		     "while attempting idput\n", $userinput);
                   5207: 	}
                   5208:     } else {
                   5209: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5210: 		  "while attempting idput\n", $userinput);
                   5211:     }
                   5212: 
                   5213:     return 1;
                   5214: }
1.263     albertel 5215: &register_handler("idput", \&put_id_handler, 0, 1, 0);
1.238     foxr     5216: 
                   5217: #
                   5218: #  Retrieves a set of id values from the id database.
                   5219: #  Returns an & separated list of results, one for each requested id to the
                   5220: #  client.
                   5221: #
                   5222: # Parameters:
                   5223: #   $cmd       - Command keyword that caused us to be dispatched.
                   5224: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5225: #               domain - the domain whose id table we dump
                   5226: #               ids      Consists of an & separated list of
                   5227: #                        id keywords whose values will be fetched.
                   5228: #                        nonexisting keywords will have an empty value.
                   5229: #   $client    - Socket open on the client.
                   5230: #
                   5231: # Returns:
                   5232: #    1 - indicating processing should continue.
                   5233: # Side effects:
                   5234: #   An & separated list of results is written to $client.
                   5235: #
                   5236: sub get_id_handler {
                   5237:     my ($cmd, $tail, $client) = @_;
                   5238: 
                   5239:     
                   5240:     my $userinput = "$client:$tail";
                   5241:     
                   5242:     my ($udom,$what)=split(/:/,$tail);
                   5243:     chomp($what);
                   5244:     my @queries=split(/\&/,$what);
                   5245:     my $qresult='';
                   5246:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
                   5247:     if ($hashref) {
                   5248: 	for (my $i=0;$i<=$#queries;$i++) {
                   5249: 	    $qresult.="$hashref->{$queries[$i]}&";
                   5250: 	}
1.311     albertel 5251: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     5252: 	    $qresult=~s/\&$//;
1.387     albertel 5253: 	    &Reply($client, \$qresult, $userinput);
1.238     foxr     5254: 	} else {
                   5255: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5256: 		      "while attempting idget\n",$userinput);
                   5257: 	}
                   5258:     } else {
                   5259: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5260: 		 "while attempting idget\n",$userinput);
                   5261:     }
                   5262:     
                   5263:     return 1;
                   5264: }
1.263     albertel 5265: &register_handler("idget", \&get_id_handler, 0, 1, 0);
1.238     foxr     5266: 
1.501     raeburn  5267: #   Deletes one or more ids in a domain's id database.
                   5268: #
                   5269: #   Parameters:
                   5270: #       $cmd                  - Command keyword (iddel).
                   5271: #       $tail                 - Command tail.  In this case a colon
                   5272: #                               separated list containing:
                   5273: #                               The domain for which we are deleting the id(s).
                   5274: #                               &-separated list of id(s) to delete.
                   5275: #       $client               - File open on client socket.
                   5276: # Returns:
                   5277: #     1   - Continue processing
                   5278: #     0   - Exit server.
                   5279: #     
                   5280: #
                   5281: 
                   5282: sub del_id_handler {
                   5283:     my ($cmd,$tail,$client) = @_;
                   5284: 
                   5285:     my $userinput = "$cmd:$tail";
                   5286: 
                   5287:     my ($udom,$what)=split(/:/,$tail);
                   5288:     chomp($what);
                   5289:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   5290:                                    "D", $what);
                   5291:     if ($hashref) {
                   5292:         my @keys=split(/\&/,$what);
                   5293:         foreach my $key (@keys) {
                   5294:             delete($hashref->{$key});
                   5295:         }
                   5296:         if (&untie_user_hash($hashref)) {
                   5297:             &Reply($client, "ok\n", $userinput);
                   5298:         } else {
                   5299:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5300:                     "while attempting iddel\n", $userinput);
                   5301:         }
                   5302:     } else {
                   5303:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5304:                  "while attempting iddel\n", $userinput);
                   5305:     }
                   5306:     return 1;
                   5307: }
                   5308: &register_handler("iddel", \&del_id_handler, 0, 1, 0);
                   5309: 
1.238     foxr     5310: #
1.299     raeburn  5311: # Puts broadcast e-mail sent by Domain Coordinator in nohist_dcmail database 
                   5312: #
                   5313: # Parameters
                   5314: #   $cmd       - Command keyword that caused us to be dispatched.
                   5315: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5316: #               domain - the domain whose dcmail we are recording
                   5317: #               email    Consists of key=value pair 
                   5318: #                        where key is unique msgid
                   5319: #                        and value is message (in XML)
                   5320: #   $client    - Socket open on the client.
                   5321: #
                   5322: # Returns:
                   5323: #    1 - indicating processing should continue.
                   5324: # Side effects
                   5325: #     reply is written to $client.
                   5326: #
                   5327: sub put_dcmail_handler {
                   5328:     my ($cmd,$tail,$client) = @_;
                   5329:     my $userinput = "$cmd:$tail";
1.463     foxr     5330: 
                   5331: 
1.299     raeburn  5332:     my ($udom,$what)=split(/:/,$tail);
                   5333:     chomp($what);
                   5334:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   5335:     if ($hashref) {
                   5336:         my ($key,$value)=split(/=/,$what);
                   5337:         $hashref->{$key}=$value;
                   5338:     }
1.311     albertel 5339:     if (&untie_domain_hash($hashref)) {
1.299     raeburn  5340:         &Reply($client, "ok\n", $userinput);
                   5341:     } else {
                   5342:         &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5343:                  "while attempting dcmailput\n", $userinput);
                   5344:     }
                   5345:     return 1;
                   5346: }
                   5347: &register_handler("dcmailput", \&put_dcmail_handler, 0, 1, 0);
                   5348: 
                   5349: #
                   5350: # Retrieves broadcast e-mail from nohist_dcmail database
                   5351: # Returns to client an & separated list of key=value pairs,
                   5352: # where key is msgid and value is message information.
                   5353: #
                   5354: # Parameters
                   5355: #   $cmd       - Command keyword that caused us to be dispatched.
                   5356: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5357: #               domain - the domain whose dcmail table we dump
                   5358: #               startfilter - beginning of time window 
                   5359: #               endfilter - end of time window
                   5360: #               sendersfilter - & separated list of username:domain 
                   5361: #                 for senders to search for.
                   5362: #   $client    - Socket open on the client.
                   5363: #
                   5364: # Returns:
                   5365: #    1 - indicating processing should continue.
                   5366: # Side effects
                   5367: #     reply (& separated list of msgid=messageinfo pairs) is 
                   5368: #     written to $client.
                   5369: #
                   5370: sub dump_dcmail_handler {
                   5371:     my ($cmd, $tail, $client) = @_;
                   5372:                                                                                 
                   5373:     my $userinput = "$cmd:$tail";
                   5374:     my ($udom,$startfilter,$endfilter,$sendersfilter) = split(/:/,$tail);
                   5375:     chomp($sendersfilter);
                   5376:     my @senders = ();
                   5377:     if (defined($startfilter)) {
                   5378:         $startfilter=&unescape($startfilter);
                   5379:     } else {
                   5380:         $startfilter='.';
                   5381:     }
                   5382:     if (defined($endfilter)) {
                   5383:         $endfilter=&unescape($endfilter);
                   5384:     } else {
                   5385:         $endfilter='.';
                   5386:     }
                   5387:     if (defined($sendersfilter)) {
                   5388:         $sendersfilter=&unescape($sendersfilter);
1.300     albertel 5389: 	@senders = map { &unescape($_) } split(/\&/,$sendersfilter);
1.299     raeburn  5390:     }
                   5391: 
                   5392:     my $qresult='';
                   5393:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   5394:     if ($hashref) {
                   5395:         while (my ($key,$value) = each(%$hashref)) {
                   5396:             my $match = 1;
1.303     albertel 5397:             my ($timestamp,$subj,$uname,$udom) = 
                   5398: 		split(/:/,&unescape(&unescape($key)),5); # yes, twice really
1.299     raeburn  5399:             $subj = &unescape($subj);
                   5400:             unless ($startfilter eq '.' || !defined($startfilter)) {
                   5401:                 if ($timestamp < $startfilter) {
                   5402:                     $match = 0;
                   5403:                 }
                   5404:             }
                   5405:             unless ($endfilter eq '.' || !defined($endfilter)) {
                   5406:                 if ($timestamp > $endfilter) {
                   5407:                     $match = 0;
                   5408:                 }
                   5409:             }
                   5410:             unless (@senders < 1) {
                   5411:                 unless (grep/^$uname:$udom$/,@senders) {
                   5412:                     $match = 0;
                   5413:                 }
                   5414:             }
                   5415:             if ($match == 1) {
                   5416:                 $qresult.=$key.'='.$value.'&';
                   5417:             }
                   5418:         }
1.311     albertel 5419:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5420:             chop($qresult);
1.387     albertel 5421:             &Reply($client, \$qresult, $userinput);
1.299     raeburn  5422:         } else {
                   5423:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5424:                     "while attempting dcmaildump\n", $userinput);
                   5425:         }
                   5426:     } else {
                   5427:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5428:                 "while attempting dcmaildump\n", $userinput);
                   5429:     }
                   5430:     return 1;
                   5431: }
                   5432: 
                   5433: &register_handler("dcmaildump", \&dump_dcmail_handler, 0, 1, 0);
                   5434: 
                   5435: #
                   5436: # Puts domain roles in nohist_domainroles database
                   5437: #
                   5438: # Parameters
                   5439: #   $cmd       - Command keyword that caused us to be dispatched.
                   5440: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5441: #               domain - the domain whose roles we are recording  
                   5442: #               role -   Consists of key=value pair
                   5443: #                        where key is unique role
                   5444: #                        and value is start/end date information
                   5445: #   $client    - Socket open on the client.
                   5446: #
                   5447: # Returns:
                   5448: #    1 - indicating processing should continue.
                   5449: # Side effects
                   5450: #     reply is written to $client.
                   5451: #
                   5452: 
                   5453: sub put_domainroles_handler {
                   5454:     my ($cmd,$tail,$client) = @_;
                   5455: 
                   5456:     my $userinput = "$cmd:$tail";
                   5457:     my ($udom,$what)=split(/:/,$tail);
                   5458:     chomp($what);
                   5459:     my @pairs=split(/\&/,$what);
                   5460:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   5461:     if ($hashref) {
                   5462:         foreach my $pair (@pairs) {
                   5463:             my ($key,$value)=split(/=/,$pair);
                   5464:             $hashref->{$key}=$value;
                   5465:         }
1.311     albertel 5466:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5467:             &Reply($client, "ok\n", $userinput);
                   5468:         } else {
                   5469:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5470:                      "while attempting domroleput\n", $userinput);
                   5471:         }
                   5472:     } else {
                   5473:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5474:                   "while attempting domroleput\n", $userinput);
                   5475:     }
                   5476:                                                                                   
                   5477:     return 1;
                   5478: }
                   5479: 
                   5480: &register_handler("domroleput", \&put_domainroles_handler, 0, 1, 0);
                   5481: 
                   5482: #
                   5483: # Retrieves domain roles from nohist_domainroles database
                   5484: # Returns to client an & separated list of key=value pairs,
                   5485: # where key is role and value is start and end date information.
                   5486: #
                   5487: # Parameters
                   5488: #   $cmd       - Command keyword that caused us to be dispatched.
                   5489: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5490: #               domain - the domain whose domain roles table we dump
                   5491: #   $client    - Socket open on the client.
                   5492: #
                   5493: # Returns:
                   5494: #    1 - indicating processing should continue.
                   5495: # Side effects
                   5496: #     reply (& separated list of role=start/end info pairs) is
                   5497: #     written to $client.
                   5498: #
                   5499: sub dump_domainroles_handler {
                   5500:     my ($cmd, $tail, $client) = @_;
                   5501:                                                                                            
                   5502:     my $userinput = "$cmd:$tail";
                   5503:     my ($udom,$startfilter,$endfilter,$rolesfilter) = split(/:/,$tail);
                   5504:     chomp($rolesfilter);
                   5505:     my @roles = ();
                   5506:     if (defined($startfilter)) {
                   5507:         $startfilter=&unescape($startfilter);
                   5508:     } else {
                   5509:         $startfilter='.';
                   5510:     }
                   5511:     if (defined($endfilter)) {
                   5512:         $endfilter=&unescape($endfilter);
                   5513:     } else {
                   5514:         $endfilter='.';
                   5515:     }
                   5516:     if (defined($rolesfilter)) {
                   5517:         $rolesfilter=&unescape($rolesfilter);
1.300     albertel 5518: 	@roles = split(/\&/,$rolesfilter);
1.299     raeburn  5519:     }
1.421     raeburn  5520: 
1.299     raeburn  5521:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   5522:     if ($hashref) {
                   5523:         my $qresult = '';
                   5524:         while (my ($key,$value) = each(%$hashref)) {
                   5525:             my $match = 1;
1.421     raeburn  5526:             my ($end,$start) = split(/:/,&unescape($value));
1.299     raeburn  5527:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,&unescape($key));
1.421     raeburn  5528:             unless (@roles < 1) {
                   5529:                 unless (grep/^\Q$trole\E$/,@roles) {
                   5530:                     $match = 0;
                   5531:                     next;
                   5532:                 }
                   5533:             }
1.299     raeburn  5534:             unless ($startfilter eq '.' || !defined($startfilter)) {
1.415     raeburn  5535:                 if ((defined($start)) && ($start >= $startfilter)) {
1.299     raeburn  5536:                     $match = 0;
1.421     raeburn  5537:                     next;
1.299     raeburn  5538:                 }
                   5539:             }
                   5540:             unless ($endfilter eq '.' || !defined($endfilter)) {
1.421     raeburn  5541:                 if ((defined($end)) && (($end > 0) && ($end <= $endfilter))) {
1.299     raeburn  5542:                     $match = 0;
1.421     raeburn  5543:                     next;
1.299     raeburn  5544:                 }
                   5545:             }
                   5546:             if ($match == 1) {
                   5547:                 $qresult.=$key.'='.$value.'&';
                   5548:             }
                   5549:         }
1.311     albertel 5550:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5551:             chop($qresult);
1.387     albertel 5552:             &Reply($client, \$qresult, $userinput);
1.299     raeburn  5553:         } else {
                   5554:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5555:                     "while attempting domrolesdump\n", $userinput);
                   5556:         }
                   5557:     } else {
                   5558:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5559:                 "while attempting domrolesdump\n", $userinput);
                   5560:     }
                   5561:     return 1;
                   5562: }
                   5563: 
                   5564: &register_handler("domrolesdump", \&dump_domainroles_handler, 0, 1, 0);
                   5565: 
                   5566: 
1.238     foxr     5567: #  Process the tmpput command I'm not sure what this does.. Seems to
                   5568: #  create a file in the lonDaemons/tmp directory of the form $id.tmp
                   5569: # where Id is the client's ip concatenated with a sequence number.
                   5570: # The file will contain some value that is passed in.  Is this e.g.
                   5571: # a login token?
                   5572: #
                   5573: # Parameters:
                   5574: #    $cmd     - The command that got us dispatched.
                   5575: #    $tail    - The remainder of the request following $cmd:
                   5576: #               In this case this will be the contents of the file.
                   5577: #    $client  - Socket connected to the client.
                   5578: # Returns:
                   5579: #    1 indicating processing can continue.
                   5580: # Side effects:
                   5581: #   A file is created in the local filesystem.
                   5582: #   A reply is sent to the client.
                   5583: sub tmp_put_handler {
                   5584:     my ($cmd, $what, $client) = @_;
                   5585: 
                   5586:     my $userinput = "$cmd:$what";	# Reconstruct for logging.
                   5587: 
1.347     raeburn  5588:     my ($record,$context) = split(/:/,$what);
                   5589:     if ($context ne '') {
                   5590:         chomp($context);
                   5591:         $context = &unescape($context);
                   5592:     }
                   5593:     my ($id,$store);
1.238     foxr     5594:     $tmpsnum++;
1.454     raeburn  5595:     if (($context eq 'resetpw') || ($context eq 'createaccount')) {
1.347     raeburn  5596:         $id = &md5_hex(&md5_hex(time.{}.rand().$$));
                   5597:     } else {
                   5598:         $id = $$.'_'.$clientip.'_'.$tmpsnum;
                   5599:     }
1.238     foxr     5600:     $id=~s/\W/\_/g;
1.347     raeburn  5601:     $record=~s/\n//g;
1.238     foxr     5602:     my $execdir=$perlvar{'lonDaemons'};
                   5603:     if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
1.347     raeburn  5604: 	print $store $record;
1.238     foxr     5605: 	close $store;
1.387     albertel 5606: 	&Reply($client, \$id, $userinput);
1.238     foxr     5607:     } else {
                   5608: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   5609: 		  "while attempting tmpput\n", $userinput);
                   5610:     }
                   5611:     return 1;
                   5612:   
                   5613: }
                   5614: &register_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
1.263     albertel 5615: 
1.238     foxr     5616: #   Processes the tmpget command.  This command returns the contents
                   5617: #  of a temporary resource file(?) created via tmpput.
                   5618: #
                   5619: # Paramters:
                   5620: #    $cmd      - Command that got us dispatched.
                   5621: #    $id       - Tail of the command, contain the id of the resource
                   5622: #                we want to fetch.
                   5623: #    $client   - socket open on the client.
                   5624: # Return:
                   5625: #    1         - Inidcating processing can continue.
                   5626: # Side effects:
                   5627: #   A reply is sent to the client.
                   5628: #
                   5629: sub tmp_get_handler {
                   5630:     my ($cmd, $id, $client) = @_;
                   5631: 
                   5632:     my $userinput = "$cmd:$id"; 
                   5633:     
                   5634: 
                   5635:     $id=~s/\W/\_/g;
                   5636:     my $store;
                   5637:     my $execdir=$perlvar{'lonDaemons'};
                   5638:     if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
                   5639: 	my $reply=<$store>;
1.387     albertel 5640: 	&Reply( $client, \$reply, $userinput);
1.238     foxr     5641: 	close $store;
                   5642:     } else {
                   5643: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   5644: 		  "while attempting tmpget\n", $userinput);
                   5645:     }
                   5646: 
                   5647:     return 1;
                   5648: }
                   5649: &register_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
1.263     albertel 5650: 
1.238     foxr     5651: #
                   5652: #  Process the tmpdel command.  This command deletes a temp resource
                   5653: #  created by the tmpput command.
                   5654: #
                   5655: # Parameters:
                   5656: #   $cmd      - Command that got us here.
                   5657: #   $id       - Id of the temporary resource created.
                   5658: #   $client   - socket open on the client process.
                   5659: #
                   5660: # Returns:
                   5661: #   1     - Indicating processing should continue.
                   5662: # Side Effects:
                   5663: #   A file is deleted
                   5664: #   A reply is sent to the client.
                   5665: sub tmp_del_handler {
                   5666:     my ($cmd, $id, $client) = @_;
                   5667:     
                   5668:     my $userinput= "$cmd:$id";
                   5669:     
                   5670:     chomp($id);
                   5671:     $id=~s/\W/\_/g;
                   5672:     my $execdir=$perlvar{'lonDaemons'};
                   5673:     if (unlink("$execdir/tmp/$id.tmp")) {
                   5674: 	&Reply($client, "ok\n", $userinput);
                   5675:     } else {
                   5676: 	&Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
                   5677: 		  "while attempting tmpdel\n", $userinput);
                   5678:     }
                   5679:     
                   5680:     return 1;
                   5681: 
                   5682: }
                   5683: &register_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
1.263     albertel 5684: 
1.238     foxr     5685: #
1.551     raeburn  5686: #  Process the delbalcookie command. This command deletes a balancer
                   5687: #  cookie in the lonBalancedir directory created by switchserver
                   5688: #
                   5689: # Parameters:
                   5690: #   $cmd      - Command that got us here.
                   5691: #   $cookie   - Cookie to be deleted.
                   5692: #   $client   - socket open on the client process.
                   5693: #
                   5694: # Returns:
                   5695: #   1     - Indicating processing should continue.
                   5696: # Side Effects:
                   5697: #   A cookie file is deleted from the lonBalancedir directory
                   5698: #   A reply is sent to the client.
                   5699: sub del_balcookie_handler {
                   5700:     my ($cmd, $cookie, $client) = @_;
                   5701: 
                   5702:     my $userinput= "$cmd:$cookie";
                   5703: 
                   5704:     chomp($cookie);
                   5705:     my $deleted = '';
                   5706:     if ($cookie =~ /^$LONCAPA::match_domain\_$LONCAPA::match_username\_[a-f0-9]{32}$/) {
                   5707:         my $execdir=$perlvar{'lonBalanceDir'};
                   5708:         if (-e "$execdir/$cookie.id") {
                   5709:             if (open(my $fh,'<',"$execdir/$cookie.id")) {
                   5710:                 my $dodelete;
                   5711:                 while (my $line = <$fh>) {
                   5712:                     chomp($line);
                   5713:                     if ($line eq $clientname) {
                   5714:                         $dodelete = 1;
1.554     raeburn  5715:                         last;
1.551     raeburn  5716:                     }
                   5717:                 }
1.554     raeburn  5718:                 close($fh);
1.551     raeburn  5719:                 if ($dodelete) {
                   5720:                     if (unlink("$execdir/$cookie.id")) {
                   5721:                         $deleted = 1;
                   5722:                     }
                   5723:                 }
                   5724:             }
                   5725:         }
                   5726:     }
                   5727:     if ($deleted) {
                   5728:         &Reply($client, "ok\n", $userinput);
                   5729:     } else {
                   5730:         &Failure( $client, "error: ".($!+0)."Unlinking cookie file Failed ".
                   5731:                   "while attempting delbalcookie\n", $userinput);
                   5732:     }
                   5733:     return 1;
                   5734: }
                   5735: &register_handler("delbalcookie", \&del_balcookie_handler, 0, 1, 0);
                   5736: 
                   5737: #
1.246     foxr     5738: #   Processes the setannounce command.  This command
                   5739: #   creates a file named announce.txt in the top directory of
                   5740: #   the documentn root and sets its contents.  The announce.txt file is
                   5741: #   printed in its entirety at the LonCAPA login page.  Note:
                   5742: #   once the announcement.txt fileis created it cannot be deleted.
                   5743: #   However, setting the contents of the file to empty removes the
                   5744: #   announcement from the login page of loncapa so who cares.
                   5745: #
                   5746: # Parameters:
                   5747: #    $cmd          - The command that got us dispatched.
                   5748: #    $announcement - The text of the announcement.
                   5749: #    $client       - Socket open on the client process.
                   5750: # Retunrns:
                   5751: #   1             - Indicating request processing should continue
                   5752: # Side Effects:
                   5753: #   The file {DocRoot}/announcement.txt is created.
                   5754: #   A reply is sent to $client.
                   5755: #
                   5756: sub set_announce_handler {
                   5757:     my ($cmd, $announcement, $client) = @_;
                   5758:   
                   5759:     my $userinput    = "$cmd:$announcement";
                   5760: 
                   5761:     chomp($announcement);
                   5762:     $announcement=&unescape($announcement);
                   5763:     if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
                   5764: 				'/announcement.txt')) {
                   5765: 	print $store $announcement;
                   5766: 	close $store;
                   5767: 	&Reply($client, "ok\n", $userinput);
                   5768:     } else {
                   5769: 	&Failure($client, "error: ".($!+0)."\n", $userinput);
                   5770:     }
                   5771: 
                   5772:     return 1;
                   5773: }
                   5774: &register_handler("setannounce", \&set_announce_handler, 0, 1, 0);
1.263     albertel 5775: 
1.246     foxr     5776: #
                   5777: #  Return the version of the daemon.  This can be used to determine
                   5778: #  the compatibility of cross version installations or, alternatively to
                   5779: #  simply know who's out of date and who isn't.  Note that the version
                   5780: #  is returned concatenated with the tail.
                   5781: # Parameters:
                   5782: #   $cmd        - the request that dispatched to us.
                   5783: #   $tail       - Tail of the request (client's version?).
                   5784: #   $client     - Socket open on the client.
                   5785: #Returns:
                   5786: #   1 - continue processing requests.
                   5787: # Side Effects:
                   5788: #   Replies with version to $client.
                   5789: sub get_version_handler {
                   5790:     my ($cmd, $tail, $client) = @_;
                   5791: 
                   5792:     my $userinput  = $cmd.$tail;
                   5793:     
                   5794:     &Reply($client, &version($userinput)."\n", $userinput);
                   5795: 
                   5796: 
                   5797:     return 1;
                   5798: }
                   5799: &register_handler("version", \&get_version_handler, 0, 1, 0);
1.263     albertel 5800: 
1.246     foxr     5801: #  Set the current host and domain.  This is used to support
                   5802: #  multihomed systems.  Each IP of the system, or even separate daemons
                   5803: #  on the same IP can be treated as handling a separate lonCAPA virtual
                   5804: #  machine.  This command selects the virtual lonCAPA.  The client always
                   5805: #  knows the right one since it is lonc and it is selecting the domain/system
                   5806: #  from the hosts.tab file.
                   5807: # Parameters:
                   5808: #    $cmd      - Command that dispatched us.
                   5809: #    $tail     - Tail of the command (domain/host requested).
                   5810: #    $socket   - Socket open on the client.
                   5811: #
                   5812: # Returns:
                   5813: #     1   - Indicates the program should continue to process requests.
                   5814: # Side-effects:
                   5815: #     The default domain/system context is modified for this daemon.
                   5816: #     a reply is sent to the client.
                   5817: #
                   5818: sub set_virtual_host_handler {
                   5819:     my ($cmd, $tail, $socket) = @_;
                   5820:   
                   5821:     my $userinput  ="$cmd:$tail";
                   5822: 
                   5823:     &Reply($client, &sethost($userinput)."\n", $userinput);
                   5824: 
                   5825: 
                   5826:     return 1;
                   5827: }
1.247     albertel 5828: &register_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
1.246     foxr     5829: 
                   5830: #  Process a request to exit:
                   5831: #   - "bye" is sent to the client.
                   5832: #   - The client socket is shutdown and closed.
                   5833: #   - We indicate to the caller that we should exit.
                   5834: # Formal Parameters:
                   5835: #   $cmd                - The command that got us here.
                   5836: #   $tail               - Tail of the command (empty).
                   5837: #   $client             - Socket open on the tail.
                   5838: # Returns:
                   5839: #   0      - Indicating the program should exit!!
                   5840: #
                   5841: sub exit_handler {
                   5842:     my ($cmd, $tail, $client) = @_;
                   5843: 
                   5844:     my $userinput = "$cmd:$tail";
                   5845: 
                   5846:     &logthis("Client $clientip ($clientname) hanging up: $userinput");
                   5847:     &Reply($client, "bye\n", $userinput);
                   5848:     $client->shutdown(2);        # shutdown the socket forcibly.
                   5849:     $client->close();
                   5850: 
                   5851:     return 0;
                   5852: }
1.248     foxr     5853: &register_handler("exit", \&exit_handler, 0,1,1);
                   5854: &register_handler("init", \&exit_handler, 0,1,1);
                   5855: &register_handler("quit", \&exit_handler, 0,1,1);
                   5856: 
                   5857: #  Determine if auto-enrollment is enabled.
                   5858: #  Note that the original had what I believe to be a defect.
                   5859: #  The original returned 0 if the requestor was not a registerd client.
                   5860: #  It should return "refused".
                   5861: # Formal Parameters:
                   5862: #   $cmd       - The command that invoked us.
                   5863: #   $tail      - The tail of the command (Extra command parameters.
                   5864: #   $client    - The socket open on the client that issued the request.
                   5865: # Returns:
                   5866: #    1         - Indicating processing should continue.
                   5867: #
                   5868: sub enrollment_enabled_handler {
                   5869:     my ($cmd, $tail, $client) = @_;
                   5870:     my $userinput = $cmd.":".$tail; # For logging purposes.
                   5871: 
                   5872:     
1.337     albertel 5873:     my ($cdom) = split(/:/, $tail, 2);   # Domain we're asking about.
                   5874: 
1.248     foxr     5875:     my $outcome  = &localenroll::run($cdom);
1.387     albertel 5876:     &Reply($client, \$outcome, $userinput);
1.248     foxr     5877: 
                   5878:     return 1;
                   5879: }
                   5880: &register_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
                   5881: 
1.417     raeburn  5882: #
1.423     raeburn  5883: #   Validate an institutional code used for a LON-CAPA course.          
1.417     raeburn  5884: #
                   5885: # Formal Parameters:
                   5886: #   $cmd          - The command request that got us dispatched.
                   5887: #   $tail         - The tail of the command.  In this case,
                   5888: #                   this is a colon separated set of words that will be split
                   5889: #                   into:
1.424     raeburn  5890: #                        $dom      - The domain for which the check of 
                   5891: #                                    institutional course code will occur.
                   5892: #
                   5893: #                        $instcode - The institutional code for the course
                   5894: #                                    being requested, or validated for rights
                   5895: #                                    to request.
                   5896: #
                   5897: #                        $owner    - The course requestor (who will be the
                   5898: #                                    course owner, in the form username:domain
                   5899: #
1.417     raeburn  5900: #   $client       - Socket open on the client.
                   5901: # Returns:
                   5902: #    1           - Indicating processing should continue.
                   5903: #
                   5904: sub validate_instcode_handler {
                   5905:     my ($cmd, $tail, $client) = @_;
                   5906:     my $userinput = "$cmd:$tail";
1.423     raeburn  5907:     my ($dom,$instcode,$owner) = split(/:/, $tail);
1.422     raeburn  5908:     $instcode = &unescape($instcode);
                   5909:     $owner = &unescape($owner);
1.498     raeburn  5910:     my ($outcome,$description,$credits) = 
1.426     raeburn  5911:         &localenroll::validate_instcode($dom,$instcode,$owner);
1.498     raeburn  5912:     my $result = &escape($outcome).'&'.&escape($description).'&'.
                   5913:                  &escape($credits);
1.426     raeburn  5914:     &Reply($client, \$result, $userinput);
1.417     raeburn  5915: 
                   5916:     return 1;
                   5917: }
                   5918: &register_handler("autovalidateinstcode", \&validate_instcode_handler, 0, 1, 0);
                   5919: 
1.248     foxr     5920: #   Get the official sections for which auto-enrollment is possible.
                   5921: #   Since the admin people won't know about 'unofficial sections' 
                   5922: #   we cannot auto-enroll on them.
                   5923: # Formal Parameters:
                   5924: #    $cmd     - The command request that got us dispatched here.
                   5925: #    $tail    - The remainder of the request.  In our case this
                   5926: #               will be split into:
                   5927: #               $coursecode   - The course name from the admin point of view.
                   5928: #               $cdom         - The course's domain(?).
                   5929: #    $client  - Socket open on the client.
                   5930: # Returns:
                   5931: #    1    - Indiciting processing should continue.
                   5932: #
                   5933: sub get_sections_handler {
                   5934:     my ($cmd, $tail, $client) = @_;
                   5935:     my $userinput = "$cmd:$tail";
                   5936: 
                   5937:     my ($coursecode, $cdom) = split(/:/, $tail);
                   5938:     my @secs = &localenroll::get_sections($coursecode,$cdom);
                   5939:     my $seclist = &escape(join(':',@secs));
                   5940: 
1.387     albertel 5941:     &Reply($client, \$seclist, $userinput);
1.248     foxr     5942:     
                   5943: 
                   5944:     return 1;
                   5945: }
                   5946: &register_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
                   5947: 
                   5948: #   Validate the owner of a new course section.  
                   5949: #
                   5950: # Formal Parameters:
                   5951: #   $cmd      - Command that got us dispatched.
                   5952: #   $tail     - the remainder of the command.  For us this consists of a
                   5953: #               colon separated string containing:
                   5954: #                  $inst    - Course Id from the institutions point of view.
                   5955: #                  $owner   - Proposed owner of the course.
                   5956: #                  $cdom    - Domain of the course (from the institutions
                   5957: #                             point of view?)..
                   5958: #   $client   - Socket open on the client.
                   5959: #
                   5960: # Returns:
                   5961: #   1        - Processing should continue.
                   5962: #
                   5963: sub validate_course_owner_handler {
                   5964:     my ($cmd, $tail, $client)  = @_;
                   5965:     my $userinput = "$cmd:$tail";
1.470     raeburn  5966:     my ($inst_course_id, $owner, $cdom, $coowners) = split(/:/, $tail);
                   5967:     
1.336     raeburn  5968:     $owner = &unescape($owner);
1.470     raeburn  5969:     $coowners = &unescape($coowners);
                   5970:     my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom,$coowners);
1.387     albertel 5971:     &Reply($client, \$outcome, $userinput);
1.248     foxr     5972: 
                   5973: 
                   5974: 
                   5975:     return 1;
                   5976: }
                   5977: &register_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
1.263     albertel 5978: 
1.248     foxr     5979: #
                   5980: #   Validate a course section in the official schedule of classes
                   5981: #   from the institutions point of view (part of autoenrollment).
                   5982: #
                   5983: # Formal Parameters:
                   5984: #   $cmd          - The command request that got us dispatched.
                   5985: #   $tail         - The tail of the command.  In this case,
                   5986: #                   this is a colon separated set of words that will be split
                   5987: #                   into:
                   5988: #                        $inst_course_id - The course/section id from the
                   5989: #                                          institutions point of view.
                   5990: #                        $cdom           - The domain from the institutions
                   5991: #                                          point of view.
                   5992: #   $client       - Socket open on the client.
                   5993: # Returns:
                   5994: #    1           - Indicating processing should continue.
                   5995: #
                   5996: sub validate_course_section_handler {
                   5997:     my ($cmd, $tail, $client) = @_;
                   5998:     my $userinput = "$cmd:$tail";
                   5999:     my ($inst_course_id, $cdom) = split(/:/, $tail);
                   6000: 
                   6001:     my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
1.387     albertel 6002:     &Reply($client, \$outcome, $userinput);
1.248     foxr     6003: 
                   6004: 
                   6005:     return 1;
                   6006: }
                   6007: &register_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
                   6008: 
                   6009: #
1.340     raeburn  6010: #   Validate course owner's access to enrollment data for specific class section. 
                   6011: #   
                   6012: #
                   6013: # Formal Parameters:
                   6014: #    $cmd     - The command request that got us dispatched.
                   6015: #    $tail    - The tail of the command.   In this case this is a colon separated
1.542     raeburn  6016: #               set of values that will be split into:
1.340     raeburn  6017: #               $inst_class  - Institutional code for the specific class section   
1.542     raeburn  6018: #               $ownerlist   - An escaped comma-separated list of username:domain 
                   6019: #                              of the course owner, and co-owner(s).
1.340     raeburn  6020: #               $cdom        - The domain of the course from the institution's
                   6021: #                              point of view.
                   6022: #    $client  - The socket open on the client.
                   6023: # Returns:
                   6024: #    1 - continue processing.
                   6025: #
                   6026: 
                   6027: sub validate_class_access_handler {
                   6028:     my ($cmd, $tail, $client) = @_;
                   6029:     my $userinput = "$cmd:$tail";
1.383     raeburn  6030:     my ($inst_class,$ownerlist,$cdom) = split(/:/, $tail);
1.392     raeburn  6031:     my $owners = &unescape($ownerlist);
1.341     albertel 6032:     my $outcome;
                   6033:     eval {
                   6034: 	local($SIG{__DIE__})='DEFAULT';
1.392     raeburn  6035: 	$outcome=&localenroll::check_section($inst_class,$owners,$cdom);
1.341     albertel 6036:     };
1.387     albertel 6037:     &Reply($client,\$outcome, $userinput);
1.340     raeburn  6038: 
                   6039:     return 1;
                   6040: }
                   6041: &register_handler("autovalidateclass_sec", \&validate_class_access_handler, 0, 1, 0);
                   6042: 
                   6043: #
1.542     raeburn  6044: #   Validate course owner or co-owners(s) access to enrollment data for all sections
                   6045: #   and crosslistings for a particular course.
                   6046: #
                   6047: #
                   6048: # Formal Parameters:
                   6049: #    $cmd     - The command request that got us dispatched.
                   6050: #    $tail    - The tail of the command.   In this case this is a colon separated
                   6051: #               set of values that will be split into:
                   6052: #               $ownerlist   - An escaped comma-separated list of username:domain
                   6053: #                              of the course owner, and co-owner(s).
                   6054: #               $cdom        - The domain of the course from the institution's
                   6055: #                              point of view.
                   6056: #               $classes     - Frozen hash of institutional course sections and
                   6057: #                              crosslistings.
                   6058: #    $client  - The socket open on the client.
                   6059: # Returns:
                   6060: #    1 - continue processing.
                   6061: #
                   6062: 
                   6063: sub validate_classes_handler {
                   6064:     my ($cmd, $tail, $client) = @_;
                   6065:     my $userinput = "$cmd:$tail";
                   6066:     my ($ownerlist,$cdom,$classes) = split(/:/, $tail);
                   6067:     my $classesref = &Apache::lonnet::thaw_unescape($classes);
                   6068:     my $owners = &unescape($ownerlist);
                   6069:     my $result;
                   6070:     eval {
                   6071:         local($SIG{__DIE__})='DEFAULT';
                   6072:         my %validations;
                   6073:         my $response = &localenroll::check_instclasses($owners,$cdom,$classesref,
                   6074:                                                        \%validations);
                   6075:         if ($response eq 'ok') {
                   6076:             foreach my $key (keys(%validations)) {
                   6077:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
                   6078:             }
                   6079:             $result =~ s/\&$//;
                   6080:         } else {
                   6081:             $result = 'error';
                   6082:         }
                   6083:     };
                   6084:     if (!$@) {
                   6085:         &Reply($client, \$result, $userinput);
                   6086:     } else {
                   6087:         &Failure($client,"unknown_cmd\n",$userinput);
                   6088:     }
                   6089:     return 1;
                   6090: }
                   6091: &register_handler("autovalidateinstclasses", \&validate_classes_handler, 0, 1, 0);
                   6092: 
                   6093: #
1.340     raeburn  6094: #   Create a password for a new LON-CAPA user added by auto-enrollment.
                   6095: #   Only used for case where authentication method for new user is localauth
1.248     foxr     6096: #
                   6097: # Formal Parameters:
                   6098: #    $cmd     - The command request that got us dispatched.
                   6099: #    $tail    - The tail of the command.   In this case this is a colon separated
                   6100: #               set of words that will be split into:
1.340     raeburn  6101: #               $authparam - An authentication parameter (localauth parameter).
1.248     foxr     6102: #               $cdom      - The domain of the course from the institution's
                   6103: #                            point of view.
                   6104: #    $client  - The socket open on the client.
                   6105: # Returns:
                   6106: #    1 - continue processing.
                   6107: #
                   6108: sub create_auto_enroll_password_handler {
                   6109:     my ($cmd, $tail, $client) = @_;
                   6110:     my $userinput = "$cmd:$tail";
                   6111: 
                   6112:     my ($authparam, $cdom) = split(/:/, $userinput);
                   6113: 
                   6114:     my ($create_passwd,$authchk);
                   6115:     ($authparam,
                   6116:      $create_passwd,
                   6117:      $authchk) = &localenroll::create_password($authparam,$cdom);
                   6118: 
                   6119:     &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
                   6120: 	   $userinput);
                   6121: 
                   6122: 
                   6123:     return 1;
                   6124: }
                   6125: &register_handler("autocreatepassword", \&create_auto_enroll_password_handler, 
                   6126: 		  0, 1, 0);
                   6127: 
1.522     raeburn  6128: sub auto_export_grades_handler {
                   6129:     my ($cmd, $tail, $client) = @_;
                   6130:     my $userinput = "$cmd:$tail";
                   6131:     my ($cdom,$cnum,$info,$data) = split(/:/,$tail);
                   6132:     my $inforef = &Apache::lonnet::thaw_unescape($info);
                   6133:     my $dataref = &Apache::lonnet::thaw_unescape($data);
                   6134:     my ($outcome,$result);;
                   6135:     eval {
                   6136:         local($SIG{__DIE__})='DEFAULT';
                   6137:         my %rtnhash;
                   6138:         $outcome=&localenroll::export_grades($cdom,$cnum,$inforef,$dataref,\%rtnhash);
                   6139:         if ($outcome eq 'ok') {
                   6140:             foreach my $key (keys(%rtnhash)) {
                   6141:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
                   6142:             }
                   6143:             $result =~ s/\&$//;
                   6144:         }
                   6145:     };
                   6146:     if (!$@) {
                   6147:         if ($outcome eq 'ok') {
                   6148:             if ($cipher) {
                   6149:                 my $cmdlength=length($result);
                   6150:                 $result.="         ";
                   6151:                 my $encresult='';
                   6152:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   6153:                     $encresult.= unpack("H16",
                   6154:                                         $cipher->encrypt(substr($result,
                   6155:                                                                 $encidx,
                   6156:                                                                 8)));
                   6157:                 }
                   6158:                 &Reply( $client, "enc:$cmdlength:$encresult\n", $userinput);
                   6159:             } else {
                   6160:                 &Failure( $client, "error:no_key\n", $userinput);
                   6161:             }
                   6162:         } else {
                   6163:             &Reply($client, "$outcome\n", $userinput);
                   6164:         }
                   6165:     } else {
                   6166:         &Failure($client,"export_error\n",$userinput);
                   6167:     }
                   6168:     return 1;
                   6169: }
                   6170: &register_handler("autoexportgrades", \&auto_export_grades_handler,
1.536     raeburn  6171:                   1, 1, 0);
1.522     raeburn  6172: 
1.248     foxr     6173: #   Retrieve and remove temporary files created by/during autoenrollment.
                   6174: #
                   6175: # Formal Parameters:
                   6176: #    $cmd      - The command that got us dispatched.
                   6177: #    $tail     - The tail of the command.  In our case this is a colon 
                   6178: #                separated list that will be split into:
1.526     raeburn  6179: #                $filename - The name of the file to retrieve.
1.248     foxr     6180: #                            The filename is given as a path relative to
                   6181: #                            the LonCAPA temp file directory.
                   6182: #    $client   - Socket open on the client.
                   6183: #
                   6184: # Returns:
                   6185: #   1     - Continue processing.
                   6186: sub retrieve_auto_file_handler {
                   6187:     my ($cmd, $tail, $client)    = @_;
                   6188:     my $userinput                = "cmd:$tail";
                   6189: 
                   6190:     my ($filename)   = split(/:/, $tail);
                   6191: 
                   6192:     my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
1.521     raeburn  6193: 
                   6194:     if ($filename =~m{/\.\./}) {
                   6195:         &Failure($client, "refused\n", $userinput);
1.526     raeburn  6196:     } elsif ($filename !~ /^$LONCAPA::match_domain\_$LONCAPA::match_courseid\_.+_classlist\.xml$/) {
                   6197:         &Failure($client, "refused\n", $userinput);
1.521     raeburn  6198:     } elsif ( (-e $source) && ($filename ne '') ) {
1.248     foxr     6199: 	my $reply = '';
                   6200: 	if (open(my $fh,$source)) {
                   6201: 	    while (<$fh>) {
                   6202: 		chomp($_);
                   6203: 		$_ =~ s/^\s+//g;
                   6204: 		$_ =~ s/\s+$//g;
                   6205: 		$reply .= $_;
                   6206: 	    }
                   6207: 	    close($fh);
                   6208: 	    &Reply($client, &escape($reply)."\n", $userinput);
                   6209: 
                   6210: #   Does this have to be uncommented??!?  (RF).
                   6211: #
                   6212: #                                unlink($source);
                   6213: 	} else {
                   6214: 	    &Failure($client, "error\n", $userinput);
                   6215: 	}
                   6216:     } else {
                   6217: 	&Failure($client, "error\n", $userinput);
                   6218:     }
                   6219:     
                   6220: 
                   6221:     return 1;
                   6222: }
                   6223: &register_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
                   6224: 
1.423     raeburn  6225: sub crsreq_checks_handler {
                   6226:     my ($cmd, $tail, $client) = @_;
                   6227:     my $userinput = "$cmd:$tail";
                   6228:     my $dom = $tail;
                   6229:     my $result;
1.519     raeburn  6230:     my @reqtypes = ('official','unofficial','community','textbook','placement');
1.423     raeburn  6231:     eval {
                   6232:         local($SIG{__DIE__})='DEFAULT';
                   6233:         my %validations;
1.424     raeburn  6234:         my $response = &localenroll::crsreq_checks($dom,\@reqtypes,
                   6235:                                                    \%validations);
1.423     raeburn  6236:         if ($response eq 'ok') { 
                   6237:             foreach my $key (keys(%validations)) {
                   6238:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
                   6239:             }
                   6240:             $result =~ s/\&$//;
                   6241:         } else {
                   6242:             $result = 'error';
                   6243:         }
                   6244:     };
                   6245:     if (!$@) {
                   6246:         &Reply($client, \$result, $userinput);
                   6247:     } else {
                   6248:         &Failure($client,"unknown_cmd\n",$userinput);
                   6249:     }
                   6250:     return 1;
                   6251: }
                   6252: &register_handler("autocrsreqchecks", \&crsreq_checks_handler, 0, 1, 0);
                   6253: 
                   6254: sub validate_crsreq_handler {
                   6255:     my ($cmd, $tail, $client) = @_;
                   6256:     my $userinput = "$cmd:$tail";
1.508     raeburn  6257:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$customdata) = split(/:/, $tail);
1.423     raeburn  6258:     $instcode = &unescape($instcode);
                   6259:     $owner = &unescape($owner);
                   6260:     $crstype = &unescape($crstype);
                   6261:     $inststatuslist = &unescape($inststatuslist);
                   6262:     $instcode = &unescape($instcode);
                   6263:     $instseclist = &unescape($instseclist);
1.508     raeburn  6264:     my $custominfo = &Apache::lonnet::thaw_unescape($customdata);
1.423     raeburn  6265:     my $outcome;
                   6266:     eval {
                   6267:         local($SIG{__DIE__})='DEFAULT';
                   6268:         $outcome = &localenroll::validate_crsreq($dom,$owner,$crstype,
                   6269:                                                  $inststatuslist,$instcode,
1.508     raeburn  6270:                                                  $instseclist,$custominfo);
1.423     raeburn  6271:     };
                   6272:     if (!$@) {
                   6273:         &Reply($client, \$outcome, $userinput);
                   6274:     } else {
                   6275:         &Failure($client,"unknown_cmd\n",$userinput);
                   6276:     }
                   6277:     return 1;
                   6278: }
                   6279: &register_handler("autocrsreqvalidation", \&validate_crsreq_handler, 0, 1, 0);
                   6280: 
1.506     raeburn  6281: sub crsreq_update_handler {
                   6282:     my ($cmd, $tail, $client) = @_;
                   6283:     my $userinput = "$cmd:$tail";
1.509     raeburn  6284:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,$code,
                   6285:         $accessstart,$accessend,$infohashref) =
1.506     raeburn  6286:         split(/:/, $tail);
                   6287:     $crstype = &unescape($crstype);
                   6288:     $action = &unescape($action);
                   6289:     $ownername = &unescape($ownername);
                   6290:     $ownerdomain = &unescape($ownerdomain);
                   6291:     $fullname = &unescape($fullname);
                   6292:     $title = &unescape($title);
                   6293:     $code = &unescape($code);
1.509     raeburn  6294:     $accessstart = &unescape($accessstart);
                   6295:     $accessend = &unescape($accessend);
1.506     raeburn  6296:     my $incoming = &Apache::lonnet::thaw_unescape($infohashref);
                   6297:     my ($result,$outcome);
                   6298:     eval {
                   6299:         local($SIG{__DIE__})='DEFAULT';
                   6300:         my %rtnhash;
                   6301:         $outcome = &localenroll::crsreq_updates($cdom,$cnum,$crstype,$action,
                   6302:                                                 $ownername,$ownerdomain,$fullname,
1.509     raeburn  6303:                                                 $title,$code,$accessstart,$accessend,
                   6304:                                                 $incoming,\%rtnhash);
1.506     raeburn  6305:         if ($outcome eq 'ok') {
1.515     raeburn  6306:             my @posskeys = qw(createdweb createdmsg createdcustomized createdactions queuedweb queuedmsg formitems reviewweb validationjs onload javascript);
1.506     raeburn  6307:             foreach my $key (keys(%rtnhash)) {
                   6308:                 if (grep(/^\Q$key\E/,@posskeys)) {
                   6309:                     $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
                   6310:                 }
                   6311:             }
                   6312:             $result =~ s/\&$//;
                   6313:         }
                   6314:     };
                   6315:     if (!$@) {
                   6316:         if ($outcome eq 'ok') {
                   6317:             &Reply($client, \$result, $userinput);
                   6318:         } else {
                   6319:             &Reply($client, "format_error\n", $userinput);
                   6320:         }
                   6321:     } else {
                   6322:         &Failure($client,"unknown_cmd\n",$userinput);
                   6323:     }
                   6324:     return 1;
                   6325: }
                   6326: &register_handler("autocrsrequpdate", \&crsreq_update_handler, 0, 1, 0);
                   6327: 
1.248     foxr     6328: #
                   6329: #   Read and retrieve institutional code format (for support form).
                   6330: # Formal Parameters:
                   6331: #    $cmd        - Command that dispatched us.
                   6332: #    $tail       - Tail of the command.  In this case it conatins 
                   6333: #                  the course domain and the coursename.
                   6334: #    $client     - Socket open on the client.
                   6335: # Returns:
                   6336: #    1     - Continue processing.
                   6337: #
                   6338: sub get_institutional_code_format_handler {
                   6339:     my ($cmd, $tail, $client)   = @_;
                   6340:     my $userinput               = "$cmd:$tail";
                   6341: 
                   6342:     my $reply;
                   6343:     my($cdom,$course) = split(/:/,$tail);
                   6344:     my @pairs = split/\&/,$course;
                   6345:     my %instcodes = ();
                   6346:     my %codes = ();
                   6347:     my @codetitles = ();
                   6348:     my %cat_titles = ();
                   6349:     my %cat_order = ();
                   6350:     foreach (@pairs) {
                   6351: 	my ($key,$value) = split/=/,$_;
                   6352: 	$instcodes{&unescape($key)} = &unescape($value);
                   6353:     }
                   6354:     my $formatreply = &localenroll::instcode_format($cdom,
                   6355: 						    \%instcodes,
                   6356: 						    \%codes,
                   6357: 						    \@codetitles,
                   6358: 						    \%cat_titles,
                   6359: 						    \%cat_order);
                   6360:     if ($formatreply eq 'ok') {
1.365     albertel 6361: 	my $codes_str = &Apache::lonnet::hash2str(%codes);
                   6362: 	my $codetitles_str = &Apache::lonnet::array2str(@codetitles);
                   6363: 	my $cat_titles_str = &Apache::lonnet::hash2str(%cat_titles);
                   6364: 	my $cat_order_str = &Apache::lonnet::hash2str(%cat_order);
1.248     foxr     6365: 	&Reply($client,
                   6366: 	       $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
                   6367: 	       .$cat_order_str."\n",
                   6368: 	       $userinput);
                   6369:     } else {
                   6370: 	# this else branch added by RF since if not ok, lonc will
                   6371: 	# hang waiting on reply until timeout.
                   6372: 	#
                   6373: 	&Reply($client, "format_error\n", $userinput);
                   6374:     }
                   6375:     
                   6376:     return 1;
                   6377: }
1.265     albertel 6378: &register_handler("autoinstcodeformat",
                   6379: 		  \&get_institutional_code_format_handler,0,1,0);
1.246     foxr     6380: 
1.345     raeburn  6381: sub get_institutional_defaults_handler {
                   6382:     my ($cmd, $tail, $client)   = @_;
                   6383:     my $userinput               = "$cmd:$tail";
                   6384: 
                   6385:     my $dom = $tail;
                   6386:     my %defaults_hash;
                   6387:     my @code_order;
                   6388:     my $outcome;
                   6389:     eval {
                   6390:         local($SIG{__DIE__})='DEFAULT';
                   6391:         $outcome = &localenroll::instcode_defaults($dom,\%defaults_hash,
                   6392:                                                    \@code_order);
                   6393:     };
                   6394:     if (!$@) {
                   6395:         if ($outcome eq 'ok') {
                   6396:             my $result='';
                   6397:             while (my ($key,$value) = each(%defaults_hash)) {
                   6398:                 $result.=&escape($key).'='.&escape($value).'&';
                   6399:             }
                   6400:             $result .= 'code_order='.&escape(join('&',@code_order));
1.387     albertel 6401:             &Reply($client,\$result,$userinput);
1.345     raeburn  6402:         } else {
                   6403:             &Reply($client,"error\n", $userinput);
                   6404:         }
                   6405:     } else {
                   6406:         &Failure($client,"unknown_cmd\n",$userinput);
                   6407:     }
                   6408: }
                   6409: &register_handler("autoinstcodedefaults",
                   6410:                   \&get_institutional_defaults_handler,0,1,0);
                   6411: 
1.416     raeburn  6412: sub get_possible_instcodes_handler {
                   6413:     my ($cmd, $tail, $client)   = @_;
                   6414:     my $userinput               = "$cmd:$tail";
                   6415: 
                   6416:     my $reply;
                   6417:     my $cdom = $tail;
1.417     raeburn  6418:     my (@codetitles,%cat_titles,%cat_order,@code_order);
1.416     raeburn  6419:     my $formatreply = &localenroll::possible_instcodes($cdom,
                   6420:                                                        \@codetitles,
                   6421:                                                        \%cat_titles,
1.417     raeburn  6422:                                                        \%cat_order,
                   6423:                                                        \@code_order);
1.416     raeburn  6424:     if ($formatreply eq 'ok') {
                   6425:         my $result = join('&',map {&escape($_);} (@codetitles)).':';
1.417     raeburn  6426:         $result .= join('&',map {&escape($_);} (@code_order)).':';
1.416     raeburn  6427:         foreach my $key (keys(%cat_titles)) {
                   6428:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_titles{$key}).'&';
                   6429:         }
                   6430:         $result =~ s/\&$//;
                   6431:         $result .= ':';
                   6432:         foreach my $key (keys(%cat_order)) {
                   6433:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_order{$key}).'&';
                   6434:         }
                   6435:         $result =~ s/\&$//;
                   6436:         &Reply($client,\$result,$userinput);
                   6437:     } else {
                   6438:         &Reply($client, "format_error\n", $userinput);
                   6439:     }
                   6440:     return 1;
                   6441: }
                   6442: &register_handler("autopossibleinstcodes",
                   6443:                   \&get_possible_instcodes_handler,0,1,0);
                   6444: 
1.381     raeburn  6445: sub get_institutional_user_rules {
                   6446:     my ($cmd, $tail, $client)   = @_;
                   6447:     my $userinput               = "$cmd:$tail";
                   6448:     my $dom = &unescape($tail);
                   6449:     my (%rules_hash,@rules_order);
                   6450:     my $outcome;
                   6451:     eval {
                   6452:         local($SIG{__DIE__})='DEFAULT';
                   6453:         $outcome = &localenroll::username_rules($dom,\%rules_hash,\@rules_order);
                   6454:     };
                   6455:     if (!$@) {
                   6456:         if ($outcome eq 'ok') {
                   6457:             my $result;
                   6458:             foreach my $key (keys(%rules_hash)) {
                   6459:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6460:             }
                   6461:             $result =~ s/\&$//;
                   6462:             $result .= ':';
                   6463:             if (@rules_order > 0) {
                   6464:                 foreach my $item (@rules_order) {
                   6465:                     $result .= &escape($item).'&';
                   6466:                 }
                   6467:             }
                   6468:             $result =~ s/\&$//;
1.387     albertel 6469:             &Reply($client,\$result,$userinput);
1.381     raeburn  6470:         } else {
                   6471:             &Reply($client,"error\n", $userinput);
                   6472:         }
                   6473:     } else {
                   6474:         &Failure($client,"unknown_cmd\n",$userinput);
                   6475:     }
                   6476: }
                   6477: &register_handler("instuserrules",\&get_institutional_user_rules,0,1,0);
                   6478: 
1.389     raeburn  6479: sub get_institutional_id_rules {
                   6480:     my ($cmd, $tail, $client)   = @_;
                   6481:     my $userinput               = "$cmd:$tail";
                   6482:     my $dom = &unescape($tail);
                   6483:     my (%rules_hash,@rules_order);
                   6484:     my $outcome;
                   6485:     eval {
                   6486:         local($SIG{__DIE__})='DEFAULT';
                   6487:         $outcome = &localenroll::id_rules($dom,\%rules_hash,\@rules_order);
                   6488:     };
                   6489:     if (!$@) {
                   6490:         if ($outcome eq 'ok') {
                   6491:             my $result;
                   6492:             foreach my $key (keys(%rules_hash)) {
                   6493:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6494:             }
                   6495:             $result =~ s/\&$//;
                   6496:             $result .= ':';
                   6497:             if (@rules_order > 0) {
                   6498:                 foreach my $item (@rules_order) {
                   6499:                     $result .= &escape($item).'&';
                   6500:                 }
                   6501:             }
                   6502:             $result =~ s/\&$//;
                   6503:             &Reply($client,\$result,$userinput);
                   6504:         } else {
                   6505:             &Reply($client,"error\n", $userinput);
                   6506:         }
                   6507:     } else {
                   6508:         &Failure($client,"unknown_cmd\n",$userinput);
                   6509:     }
                   6510: }
                   6511: &register_handler("instidrules",\&get_institutional_id_rules,0,1,0);
                   6512: 
1.397     raeburn  6513: sub get_institutional_selfcreate_rules {
1.396     raeburn  6514:     my ($cmd, $tail, $client)   = @_;
                   6515:     my $userinput               = "$cmd:$tail";
                   6516:     my $dom = &unescape($tail);
                   6517:     my (%rules_hash,@rules_order);
                   6518:     my $outcome;
                   6519:     eval {
                   6520:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  6521:         $outcome = &localenroll::selfcreate_rules($dom,\%rules_hash,\@rules_order);
1.396     raeburn  6522:     };
                   6523:     if (!$@) {
                   6524:         if ($outcome eq 'ok') {
                   6525:             my $result;
                   6526:             foreach my $key (keys(%rules_hash)) {
                   6527:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6528:             }
                   6529:             $result =~ s/\&$//;
                   6530:             $result .= ':';
                   6531:             if (@rules_order > 0) {
                   6532:                 foreach my $item (@rules_order) {
                   6533:                     $result .= &escape($item).'&';
                   6534:                 }
                   6535:             }
                   6536:             $result =~ s/\&$//;
                   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("instemailrules",\&get_institutional_selfcreate_rules,0,1,0);
1.396     raeburn  6546: 
1.381     raeburn  6547: 
                   6548: sub institutional_username_check {
                   6549:     my ($cmd, $tail, $client)   = @_;
                   6550:     my $userinput               = "$cmd:$tail";
                   6551:     my %rulecheck;
                   6552:     my $outcome;
                   6553:     my ($udom,$uname,@rules) = split(/:/,$tail);
                   6554:     $udom = &unescape($udom);
                   6555:     $uname = &unescape($uname);
                   6556:     @rules = map {&unescape($_);} (@rules);
                   6557:     eval {
                   6558:         local($SIG{__DIE__})='DEFAULT';
                   6559:         $outcome = &localenroll::username_check($udom,$uname,\@rules,\%rulecheck);
                   6560:     };
                   6561:     if (!$@) {
                   6562:         if ($outcome eq 'ok') {
                   6563:             my $result='';
                   6564:             foreach my $key (keys(%rulecheck)) {
                   6565:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6566:             }
1.387     albertel 6567:             &Reply($client,\$result,$userinput);
1.381     raeburn  6568:         } else {
                   6569:             &Reply($client,"error\n", $userinput);
                   6570:         }
                   6571:     } else {
                   6572:         &Failure($client,"unknown_cmd\n",$userinput);
                   6573:     }
                   6574: }
                   6575: &register_handler("instrulecheck",\&institutional_username_check,0,1,0);
                   6576: 
1.389     raeburn  6577: sub institutional_id_check {
                   6578:     my ($cmd, $tail, $client)   = @_;
                   6579:     my $userinput               = "$cmd:$tail";
                   6580:     my %rulecheck;
                   6581:     my $outcome;
                   6582:     my ($udom,$id,@rules) = split(/:/,$tail);
                   6583:     $udom = &unescape($udom);
                   6584:     $id = &unescape($id);
                   6585:     @rules = map {&unescape($_);} (@rules);
                   6586:     eval {
                   6587:         local($SIG{__DIE__})='DEFAULT';
                   6588:         $outcome = &localenroll::id_check($udom,$id,\@rules,\%rulecheck);
                   6589:     };
                   6590:     if (!$@) {
                   6591:         if ($outcome eq 'ok') {
                   6592:             my $result='';
                   6593:             foreach my $key (keys(%rulecheck)) {
                   6594:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6595:             }
                   6596:             &Reply($client,\$result,$userinput);
                   6597:         } else {
                   6598:             &Reply($client,"error\n", $userinput);
                   6599:         }
                   6600:     } else {
                   6601:         &Failure($client,"unknown_cmd\n",$userinput);
                   6602:     }
                   6603: }
                   6604: &register_handler("instidrulecheck",\&institutional_id_check,0,1,0);
1.345     raeburn  6605: 
1.397     raeburn  6606: sub institutional_selfcreate_check {
1.396     raeburn  6607:     my ($cmd, $tail, $client)   = @_;
                   6608:     my $userinput               = "$cmd:$tail";
                   6609:     my %rulecheck;
                   6610:     my $outcome;
                   6611:     my ($udom,$email,@rules) = split(/:/,$tail);
                   6612:     $udom = &unescape($udom);
                   6613:     $email = &unescape($email);
                   6614:     @rules = map {&unescape($_);} (@rules);
                   6615:     eval {
                   6616:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  6617:         $outcome = &localenroll::selfcreate_check($udom,$email,\@rules,\%rulecheck);
1.396     raeburn  6618:     };
                   6619:     if (!$@) {
                   6620:         if ($outcome eq 'ok') {
                   6621:             my $result='';
                   6622:             foreach my $key (keys(%rulecheck)) {
                   6623:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6624:             }
                   6625:             &Reply($client,\$result,$userinput);
                   6626:         } else {
                   6627:             &Reply($client,"error\n", $userinput);
                   6628:         }
                   6629:     } else {
                   6630:         &Failure($client,"unknown_cmd\n",$userinput);
                   6631:     }
                   6632: }
1.397     raeburn  6633: &register_handler("instselfcreatecheck",\&institutional_selfcreate_check,0,1,0);
1.396     raeburn  6634: 
1.317     raeburn  6635: # Get domain specific conditions for import of student photographs to a course
                   6636: #
                   6637: # Retrieves information from photo_permission subroutine in localenroll.
                   6638: # Returns outcome (ok) if no processing errors, and whether course owner is 
                   6639: # required to accept conditions of use (yes/no).
                   6640: #
                   6641: #    
                   6642: sub photo_permission_handler {
                   6643:     my ($cmd, $tail, $client)   = @_;
                   6644:     my $userinput               = "$cmd:$tail";
                   6645:     my $cdom = $tail;
                   6646:     my ($perm_reqd,$conditions);
1.320     albertel 6647:     my $outcome;
                   6648:     eval {
                   6649: 	local($SIG{__DIE__})='DEFAULT';
                   6650: 	$outcome = &localenroll::photo_permission($cdom,\$perm_reqd,
                   6651: 						  \$conditions);
                   6652:     };
                   6653:     if (!$@) {
                   6654: 	&Reply($client, &escape($outcome.':'.$perm_reqd.':'. $conditions)."\n",
                   6655: 	       $userinput);
                   6656:     } else {
                   6657: 	&Failure($client,"unknown_cmd\n",$userinput);
                   6658:     }
                   6659:     return 1;
1.317     raeburn  6660: }
                   6661: &register_handler("autophotopermission",\&photo_permission_handler,0,1,0);
                   6662: 
                   6663: #
                   6664: # Checks if student photo is available for a user in the domain, in the user's
                   6665: # directory (in /userfiles/internal/studentphoto.jpg).
                   6666: # Uses localstudentphoto:fetch() to ensure there is an up to date copy of
                   6667: # the student's photo.   
                   6668: 
                   6669: sub photo_check_handler {
                   6670:     my ($cmd, $tail, $client)   = @_;
                   6671:     my $userinput               = "$cmd:$tail";
                   6672:     my ($udom,$uname,$pid) = split(/:/,$tail);
                   6673:     $udom = &unescape($udom);
                   6674:     $uname = &unescape($uname);
                   6675:     $pid = &unescape($pid);
                   6676:     my $path=&propath($udom,$uname).'/userfiles/internal/';
                   6677:     if (!-e $path) {
                   6678:         &mkpath($path);
                   6679:     }
                   6680:     my $response;
                   6681:     my $result = &localstudentphoto::fetch($udom,$uname,$pid,\$response);
                   6682:     $result .= ':'.$response;
                   6683:     &Reply($client, &escape($result)."\n",$userinput);
1.320     albertel 6684:     return 1;
1.317     raeburn  6685: }
                   6686: &register_handler("autophotocheck",\&photo_check_handler,0,1,0);
                   6687: 
                   6688: #
                   6689: # Retrieve information from localenroll about whether to provide a button     
                   6690: # for users who have enbled import of student photos to initiate an 
                   6691: # update of photo files for registered students. Also include 
                   6692: # comment to display alongside button.  
                   6693: 
                   6694: sub photo_choice_handler {
                   6695:     my ($cmd, $tail, $client) = @_;
                   6696:     my $userinput             = "$cmd:$tail";
                   6697:     my $cdom                  = &unescape($tail);
1.320     albertel 6698:     my ($update,$comment);
                   6699:     eval {
                   6700: 	local($SIG{__DIE__})='DEFAULT';
                   6701: 	($update,$comment)    = &localenroll::manager_photo_update($cdom);
                   6702:     };
                   6703:     if (!$@) {
                   6704: 	&Reply($client,&escape($update).':'.&escape($comment)."\n",$userinput);
                   6705:     } else {
                   6706: 	&Failure($client,"unknown_cmd\n",$userinput);
                   6707:     }
                   6708:     return 1;
1.317     raeburn  6709: }
                   6710: &register_handler("autophotochoice",\&photo_choice_handler,0,1,0);
                   6711: 
1.265     albertel 6712: #
                   6713: # Gets a student's photo to exist (in the correct image type) in the user's 
                   6714: # directory.
                   6715: # Formal Parameters:
                   6716: #    $cmd     - The command request that got us dispatched.
                   6717: #    $tail    - A colon separated set of words that will be split into:
                   6718: #               $domain - student's domain
                   6719: #               $uname  - student username
                   6720: #               $type   - image type desired
                   6721: #    $client  - The socket open on the client.
                   6722: # Returns:
                   6723: #    1 - continue processing.
1.317     raeburn  6724: 
1.265     albertel 6725: sub student_photo_handler {
                   6726:     my ($cmd, $tail, $client) = @_;
1.317     raeburn  6727:     my ($domain,$uname,$ext,$type) = split(/:/, $tail);
1.265     albertel 6728: 
1.317     raeburn  6729:     my $path=&propath($domain,$uname). '/userfiles/internal/';
                   6730:     my $filename = 'studentphoto.'.$ext;
                   6731:     if ($type eq 'thumbnail') {
                   6732:         $filename = 'studentphoto_tn.'.$ext;
                   6733:     }
                   6734:     if (-e $path.$filename) {
1.265     albertel 6735: 	&Reply($client,"ok\n","$cmd:$tail");
                   6736: 	return 1;
                   6737:     }
                   6738:     &mkpath($path);
1.317     raeburn  6739:     my $file;
                   6740:     if ($type eq 'thumbnail') {
1.320     albertel 6741: 	eval {
                   6742: 	    local($SIG{__DIE__})='DEFAULT';
                   6743: 	    $file=&localstudentphoto::fetch_thumbnail($domain,$uname);
                   6744: 	};
1.317     raeburn  6745:     } else {
                   6746:         $file=&localstudentphoto::fetch($domain,$uname);
                   6747:     }
1.265     albertel 6748:     if (!$file) {
                   6749: 	&Failure($client,"unavailable\n","$cmd:$tail");
                   6750: 	return 1;
                   6751:     }
1.317     raeburn  6752:     if (!-e $path.$filename) { &convert_photo($file,$path.$filename); }
                   6753:     if (-e $path.$filename) {
1.265     albertel 6754: 	&Reply($client,"ok\n","$cmd:$tail");
                   6755: 	return 1;
                   6756:     }
                   6757:     &Failure($client,"unable_to_convert\n","$cmd:$tail");
                   6758:     return 1;
                   6759: }
                   6760: &register_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
1.246     foxr     6761: 
1.361     raeburn  6762: sub inst_usertypes_handler {
                   6763:     my ($cmd, $domain, $client) = @_;
                   6764:     my $res;
                   6765:     my $userinput = $cmd.":".$domain; # For logging purposes.
1.370     albertel 6766:     my (%typeshash,@order,$result);
                   6767:     eval {
                   6768: 	local($SIG{__DIE__})='DEFAULT';
                   6769: 	$result=&localenroll::inst_usertypes($domain,\%typeshash,\@order);
                   6770:     };
                   6771:     if ($result eq 'ok') {
1.361     raeburn  6772:         if (keys(%typeshash) > 0) {
                   6773:             foreach my $key (keys(%typeshash)) {
                   6774:                 $res.=&escape($key).'='.&escape($typeshash{$key}).'&';
                   6775:             }
                   6776:         }
                   6777:         $res=~s/\&$//;
                   6778:         $res .= ':';
                   6779:         if (@order > 0) {
                   6780:             foreach my $item (@order) {
                   6781:                 $res .= &escape($item).'&';
                   6782:             }
                   6783:         }
                   6784:         $res=~s/\&$//;
                   6785:     }
1.387     albertel 6786:     &Reply($client, \$res, $userinput);
1.361     raeburn  6787:     return 1;
                   6788: }
                   6789: &register_handler("inst_usertypes", \&inst_usertypes_handler, 0, 1, 0);
                   6790: 
1.264     albertel 6791: # mkpath makes all directories for a file, expects an absolute path with a
                   6792: # file or a trailing / if just a dir is passed
                   6793: # returns 1 on success 0 on failure
                   6794: sub mkpath {
                   6795:     my ($file)=@_;
                   6796:     my @parts=split(/\//,$file,-1);
                   6797:     my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
                   6798:     for (my $i=3;$i<= ($#parts-1);$i++) {
1.265     albertel 6799: 	$now.='/'.$parts[$i]; 
1.264     albertel 6800: 	if (!-e $now) {
                   6801: 	    if  (!mkdir($now,0770)) { return 0; }
                   6802: 	}
                   6803:     }
                   6804:     return 1;
                   6805: }
                   6806: 
1.207     foxr     6807: #---------------------------------------------------------------
                   6808: #
                   6809: #   Getting, decoding and dispatching requests:
                   6810: #
                   6811: #
                   6812: #   Get a Request:
                   6813: #   Gets a Request message from the client.  The transaction
                   6814: #   is defined as a 'line' of text.  We remove the new line
                   6815: #   from the text line.  
1.226     foxr     6816: #
1.211     albertel 6817: sub get_request {
1.207     foxr     6818:     my $input = <$client>;
                   6819:     chomp($input);
1.226     foxr     6820: 
1.234     foxr     6821:     &Debug("get_request: Request = $input\n");
1.207     foxr     6822: 
                   6823:     &status('Processing '.$clientname.':'.$input);
                   6824: 
                   6825:     return $input;
                   6826: }
1.212     foxr     6827: #---------------------------------------------------------------
                   6828: #
                   6829: #  Process a request.  This sub should shrink as each action
                   6830: #  gets farmed out into a separat sub that is registered 
                   6831: #  with the dispatch hash.  
                   6832: #
                   6833: # Parameters:
                   6834: #    user_input   - The request received from the client (lonc).
1.525     raeburn  6835: #
1.212     foxr     6836: # Returns:
                   6837: #    true to keep processing, false if caller should exit.
                   6838: #
                   6839: sub process_request {
1.525     raeburn  6840:     my ($userinput) = @_; # Easier for now to break style than to
                   6841:                           # fix all the userinput -> user_input.
1.212     foxr     6842:     my $wasenc    = 0;		# True if request was encrypted.
                   6843: # ------------------------------------------------------------ See if encrypted
1.322     albertel 6844:     # for command
                   6845:     # sethost:<server>
                   6846:     # <command>:<args>
                   6847:     #   we just send it to the processor
                   6848:     # for
                   6849:     # sethost:<server>:<command>:<args>
                   6850:     #  we do the implict set host and then do the command
                   6851:     if ($userinput =~ /^sethost:/) {
                   6852: 	(my $cmd,my $newid,$userinput) = split(':',$userinput,3);
                   6853: 	if (defined($userinput)) {
                   6854: 	    &sethost("$cmd:$newid");
                   6855: 	} else {
                   6856: 	    $userinput = "$cmd:$newid";
                   6857: 	}
                   6858:     }
                   6859: 
1.212     foxr     6860:     if ($userinput =~ /^enc/) {
                   6861: 	$userinput = decipher($userinput);
                   6862: 	$wasenc=1;
                   6863: 	if(!$userinput) {	# Cipher not defined.
1.251     foxr     6864: 	    &Failure($client, "error: Encrypted data without negotated key\n");
1.212     foxr     6865: 	    return 0;
                   6866: 	}
                   6867:     }
                   6868:     Debug("process_request: $userinput\n");
                   6869:     
1.213     foxr     6870:     #  
                   6871:     #   The 'correct way' to add a command to lond is now to
                   6872:     #   write a sub to execute it and Add it to the command dispatch
                   6873:     #   hash via a call to register_handler..  The comments to that
                   6874:     #   sub should give you enough to go on to show how to do this
                   6875:     #   along with the examples that are building up as this code
                   6876:     #   is getting refactored.   Until all branches of the
                   6877:     #   if/elseif monster below have been factored out into
                   6878:     #   separate procesor subs, if the dispatch hash is missing
                   6879:     #   the command keyword, we will fall through to the remainder
                   6880:     #   of the if/else chain below in order to keep this thing in 
                   6881:     #   working order throughout the transmogrification.
                   6882: 
                   6883:     my ($command, $tail) = split(/:/, $userinput, 2);
                   6884:     chomp($command);
                   6885:     chomp($tail);
                   6886:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
1.214     foxr     6887:     $command =~ s/(\r)//;	# And this too for parameterless commands.
                   6888:     if(!$tail) {
                   6889: 	$tail ="";		# defined but blank.
                   6890:     }
1.213     foxr     6891: 
                   6892:     &Debug("Command received: $command, encoded = $wasenc");
                   6893: 
                   6894:     if(defined $Dispatcher{$command}) {
                   6895: 
                   6896: 	my $dispatch_info = $Dispatcher{$command};
                   6897: 	my $handler       = $$dispatch_info[0];
                   6898: 	my $need_encode   = $$dispatch_info[1];
                   6899: 	my $client_types  = $$dispatch_info[2];
                   6900: 	Debug("Matched dispatch hash: mustencode: $need_encode "
                   6901: 	      ."ClientType $client_types");
                   6902:       
                   6903: 	#  Validate the request:
                   6904:       
                   6905: 	my $ok = 1;
                   6906: 	my $requesterprivs = 0;
                   6907: 	if(&isClient()) {
                   6908: 	    $requesterprivs |= $CLIENT_OK;
                   6909: 	}
                   6910: 	if(&isManager()) {
                   6911: 	    $requesterprivs |= $MANAGER_OK;
                   6912: 	}
                   6913: 	if($need_encode && (!$wasenc)) {
                   6914: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
                   6915: 	    $ok = 0;
                   6916: 	}
                   6917: 	if(($client_types & $requesterprivs) == 0) {
                   6918: 	    Debug("Client not privileged to do this operation");
                   6919: 	    $ok = 0;
                   6920: 	}
1.525     raeburn  6921:         if ($ok) {
1.535     raeburn  6922:             my $realcommand = $command;
                   6923:             if ($command eq 'querysend') {
                   6924:                 my ($query,$rest)=split(/\:/,$tail,2);
                   6925:                 $query=~s/\n*$//g;
                   6926:                 my @possqueries = 
                   6927:                     qw(userlog courselog fetchenrollment institutionalphotos usersearch instdirsearch getinstuser getmultinstusers);
                   6928:                 if (grep(/^\Q$query\E$/,@possqueries)) {
                   6929:                     $command .= '_'.$query;
                   6930:                 } elsif ($query eq 'prepare activity log') {
                   6931:                     $command .= '_activitylog';
                   6932:                 }
                   6933:             }
1.525     raeburn  6934:             if (ref($trust{$command}) eq 'HASH') {
                   6935:                 my $donechecks;
                   6936:                 if ($trust{$command}{'anywhere'}) {
                   6937:                    $donechecks = 1;
                   6938:                 } elsif ($trust{$command}{'manageronly'}) {
                   6939:                     unless (&isManager()) {
                   6940:                         $ok = 0;
                   6941:                     }
                   6942:                     $donechecks = 1;
                   6943:                 } elsif ($trust{$command}{'institutiononly'}) {
                   6944:                     unless ($clientsameinst) {
                   6945:                         $ok = 0;
                   6946:                     }
                   6947:                     $donechecks = 1;
                   6948:                 } elsif ($clientsameinst) {
                   6949:                     $donechecks = 1;
                   6950:                 }
                   6951:                 unless ($donechecks) {
                   6952:                     foreach my $rule (keys(%{$trust{$command}})) {
                   6953:                         next if ($rule eq 'remote');
                   6954:                         if ($trust{$command}{$rule}) {
                   6955:                             if ($clientprohibited{$rule}) {
                   6956:                                 $ok = 0;
                   6957:                             } else {
                   6958:                                 $ok = 1;
                   6959:                                 $donechecks = 1;
                   6960:                                 last;
                   6961:                             }
                   6962:                         }
                   6963:                     }
                   6964:                 }
                   6965:                 unless ($donechecks) {
                   6966:                     if ($trust{$command}{'remote'}) {
                   6967:                         if ($clientremoteok) {
                   6968:                             $ok = 1;
                   6969:                         } else {
                   6970:                             $ok = 0;
                   6971:                         } 
                   6972:                     }
                   6973:                 }
                   6974:             }
1.535     raeburn  6975:             $command = $realcommand;
1.525     raeburn  6976:         }
1.213     foxr     6977: 
                   6978: 	if($ok) {
                   6979: 	    Debug("Dispatching to handler $command $tail");
                   6980: 	    my $keep_going = &$handler($command, $tail, $client);
                   6981: 	    return $keep_going;
                   6982: 	} else {
                   6983: 	    Debug("Refusing to dispatch because client did not match requirements");
                   6984: 	    Failure($client, "refused\n", $userinput);
                   6985: 	    return 1;
                   6986: 	}
1.525     raeburn  6987:     }
1.213     foxr     6988: 
1.262     foxr     6989:     print $client "unknown_cmd\n";
1.212     foxr     6990: # -------------------------------------------------------------------- complete
                   6991:     Debug("process_request - returning 1");
                   6992:     return 1;
                   6993: }
1.207     foxr     6994: #
                   6995: #   Decipher encoded traffic
                   6996: #  Parameters:
                   6997: #     input      - Encoded data.
                   6998: #  Returns:
                   6999: #     Decoded data or undef if encryption key was not yet negotiated.
                   7000: #  Implicit input:
                   7001: #     cipher  - This global holds the negotiated encryption key.
                   7002: #
1.211     albertel 7003: sub decipher {
1.207     foxr     7004:     my ($input)  = @_;
                   7005:     my $output = '';
1.212     foxr     7006:     
                   7007:     
1.207     foxr     7008:     if($cipher) {
                   7009: 	my($enc, $enclength, $encinput) = split(/:/, $input);
                   7010: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
                   7011: 	    $output .= 
                   7012: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
                   7013: 	}
                   7014: 	return substr($output, 0, $enclength);
                   7015:     } else {
                   7016: 	return undef;
                   7017:     }
                   7018: }
                   7019: 
                   7020: #
                   7021: #   Register a command processor.  This function is invoked to register a sub
                   7022: #   to process a request.  Once registered, the ProcessRequest sub can automatically
                   7023: #   dispatch requests to an appropriate sub, and do the top level validity checking
                   7024: #   as well:
                   7025: #    - Is the keyword recognized.
                   7026: #    - Is the proper client type attempting the request.
                   7027: #    - Is the request encrypted if it has to be.
                   7028: #   Parameters:
                   7029: #    $request_name         - Name of the request being registered.
                   7030: #                           This is the command request that will match
                   7031: #                           against the hash keywords to lookup the information
                   7032: #                           associated with the dispatch information.
                   7033: #    $procedure           - Reference to a sub to call to process the request.
                   7034: #                           All subs get called as follows:
                   7035: #                             Procedure($cmd, $tail, $replyfd, $key)
                   7036: #                             $cmd    - the actual keyword that invoked us.
                   7037: #                             $tail   - the tail of the request that invoked us.
                   7038: #                             $replyfd- File descriptor connected to the client
                   7039: #    $must_encode          - True if the request must be encoded to be good.
                   7040: #    $client_ok            - True if it's ok for a client to request this.
                   7041: #    $manager_ok           - True if it's ok for a manager to request this.
                   7042: # Side effects:
                   7043: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
                   7044: #      - On failure, the program will die as it's a bad internal bug to try to 
                   7045: #        register a duplicate command handler.
                   7046: #
1.211     albertel 7047: sub register_handler {
1.212     foxr     7048:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
1.207     foxr     7049: 
                   7050:     #  Don't allow duplication#
                   7051:    
                   7052:     if (defined $Dispatcher{$request_name}) {
                   7053: 	die "Attempting to define a duplicate request handler for $request_name\n";
                   7054:     }
                   7055:     #   Build the client type mask:
                   7056:     
                   7057:     my $client_type_mask = 0;
                   7058:     if($client_ok) {
                   7059: 	$client_type_mask  |= $CLIENT_OK;
                   7060:     }
                   7061:     if($manager_ok) {
                   7062: 	$client_type_mask  |= $MANAGER_OK;
                   7063:     }
                   7064:    
                   7065:     #  Enter the hash:
                   7066:       
                   7067:     my @entry = ($procedure, $must_encode, $client_type_mask);
                   7068:    
                   7069:     $Dispatcher{$request_name} = \@entry;
                   7070:    
                   7071: }
                   7072: 
                   7073: 
                   7074: #------------------------------------------------------------------
                   7075: 
                   7076: 
                   7077: 
                   7078: 
1.141     foxr     7079: #
1.96      foxr     7080: #  Convert an error return code from lcpasswd to a string value.
                   7081: #
                   7082: sub lcpasswdstrerror {
                   7083:     my $ErrorCode = shift;
1.97      foxr     7084:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96      foxr     7085: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
                   7086:     } else {
1.98      foxr     7087: 	return $passwderrors[$ErrorCode];
1.96      foxr     7088:     }
                   7089: }
                   7090: 
1.23      harris41 7091: # grabs exception and records it to log before exiting
                   7092: sub catchexception {
1.27      albertel 7093:     my ($error)=@_;
1.25      www      7094:     $SIG{'QUIT'}='DEFAULT';
                   7095:     $SIG{__DIE__}='DEFAULT';
1.165     albertel 7096:     &status("Catching exception");
1.190     albertel 7097:     &logthis("<font color='red'>CRITICAL: "
1.373     albertel 7098:      ."ABNORMAL EXIT. Child $$ for server ".$perlvar{'lonHostID'}." died through "
1.27      albertel 7099:      ."a crash with this error msg->[$error]</font>");
1.57      www      7100:     &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27      albertel 7101:     if ($client) { print $client "error: $error\n"; }
1.59      www      7102:     $server->close();
1.27      albertel 7103:     die($error);
1.23      harris41 7104: }
1.63      www      7105: sub timeout {
1.165     albertel 7106:     &status("Handling Timeout");
1.190     albertel 7107:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
1.63      www      7108:     &catchexception('Timeout');
                   7109: }
1.22      harris41 7110: # -------------------------------- Set signal handlers to record abnormal exits
                   7111: 
1.226     foxr     7112: 
1.22      harris41 7113: $SIG{'QUIT'}=\&catchexception;
                   7114: $SIG{__DIE__}=\&catchexception;
                   7115: 
1.81      matthew  7116: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95      harris41 7117: &status("Read loncapa.conf and loncapa_apache.conf");
                   7118: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141     foxr     7119: %perlvar=%{$perlvarref};
1.80      harris41 7120: undef $perlvarref;
1.19      www      7121: 
1.35      harris41 7122: # ----------------------------- Make sure this process is running from user=www
                   7123: my $wwwid=getpwnam('www');
                   7124: if ($wwwid!=$<) {
1.134     albertel 7125:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   7126:    my $subj="LON: $currenthostid User ID mismatch";
1.550     raeburn  7127:    system("echo 'User ID mismatch.  lond must be run as user www.' |".
                   7128:           " mail -s '$subj' $emailto > /dev/null");
1.35      harris41 7129:    exit 1;
                   7130: }
                   7131: 
1.19      www      7132: # --------------------------------------------- Check if other instance running
                   7133: 
                   7134: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
                   7135: 
                   7136: if (-e $pidfile) {
                   7137:    my $lfh=IO::File->new("$pidfile");
                   7138:    my $pide=<$lfh>;
                   7139:    chomp($pide);
1.29      harris41 7140:    if (kill 0 => $pide) { die "already running"; }
1.19      www      7141: }
1.1       albertel 7142: 
                   7143: # ------------------------------------------------------------- Read hosts file
                   7144: 
                   7145: 
                   7146: 
                   7147: # establish SERVER socket, bind and listen.
                   7148: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
                   7149:                                 Type      => SOCK_STREAM,
                   7150:                                 Proto     => 'tcp',
1.469     foxr     7151:                                 ReuseAddr     => 1,
1.1       albertel 7152:                                 Listen    => 10 )
1.29      harris41 7153:   or die "making socket: $@\n";
1.1       albertel 7154: 
                   7155: # --------------------------------------------------------- Do global variables
                   7156: 
                   7157: # global variables
                   7158: 
1.134     albertel 7159: my %children               = ();       # keys are current child process IDs
1.1       albertel 7160: 
                   7161: sub REAPER {                        # takes care of dead children
                   7162:     $SIG{CHLD} = \&REAPER;
1.165     albertel 7163:     &status("Handling child death");
1.178     foxr     7164:     my $pid;
                   7165:     do {
                   7166: 	$pid = waitpid(-1,&WNOHANG());
                   7167: 	if (defined($children{$pid})) {
                   7168: 	    &logthis("Child $pid died");
                   7169: 	    delete($children{$pid});
1.183     albertel 7170: 	} elsif ($pid > 0) {
1.178     foxr     7171: 	    &logthis("Unknown Child $pid died");
                   7172: 	}
                   7173:     } while ( $pid > 0 );
                   7174:     foreach my $child (keys(%children)) {
                   7175: 	$pid = waitpid($child,&WNOHANG());
                   7176: 	if ($pid > 0) {
                   7177: 	    &logthis("Child $child - $pid looks like we missed it's death");
                   7178: 	    delete($children{$pid});
                   7179: 	}
1.176     albertel 7180:     }
1.165     albertel 7181:     &status("Finished Handling child death");
1.1       albertel 7182: }
                   7183: 
                   7184: sub HUNTSMAN {                      # signal handler for SIGINT
1.165     albertel 7185:     &status("Killing children (INT)");
1.1       albertel 7186:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
                   7187:     kill 'INT' => keys %children;
1.59      www      7188:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1       albertel 7189:     my $execdir=$perlvar{'lonDaemons'};
                   7190:     unlink("$execdir/logs/lond.pid");
1.190     albertel 7191:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.165     albertel 7192:     &status("Done killing children");
1.1       albertel 7193:     exit;                           # clean up with dignity
                   7194: }
                   7195: 
                   7196: sub HUPSMAN {                      # signal handler for SIGHUP
                   7197:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
1.165     albertel 7198:     &status("Killing children for restart (HUP)");
1.1       albertel 7199:     kill 'INT' => keys %children;
1.59      www      7200:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.190     albertel 7201:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.134     albertel 7202:     my $execdir=$perlvar{'lonDaemons'};
1.30      harris41 7203:     unlink("$execdir/logs/lond.pid");
1.165     albertel 7204:     &status("Restarting self (HUP)");
1.1       albertel 7205:     exec("$execdir/lond");         # here we go again
                   7206: }
                   7207: 
1.144     foxr     7208: #
1.148     foxr     7209: #  Reload the Apache daemon's state.
1.150     foxr     7210: #  This is done by invoking /home/httpd/perl/apachereload
                   7211: #  a setuid perl script that can be root for us to do this job.
1.148     foxr     7212: #
                   7213: sub ReloadApache {
1.473     raeburn  7214: # --------------------------- Handle case of another apachereload process (locking)
1.474     raeburn  7215:     if (&LONCAPA::try_to_lock('/tmp/lock_apachereload')) {
                   7216:         my $execdir = $perlvar{'lonDaemons'};
                   7217:         my $script  = $execdir."/apachereload";
                   7218:         system($script);
                   7219:         unlink('/tmp/lock_apachereload'); #  Remove the lock file.
                   7220:     }
1.148     foxr     7221: }
                   7222: 
                   7223: #
1.144     foxr     7224: #   Called in response to a USR2 signal.
                   7225: #   - Reread hosts.tab
                   7226: #   - All children connected to hosts that were removed from hosts.tab
                   7227: #     are killed via SIGINT
                   7228: #   - All children connected to previously existing hosts are sent SIGUSR1
                   7229: #   - Our internal hosts hash is updated to reflect the new contents of
                   7230: #     hosts.tab causing connections from hosts added to hosts.tab to
                   7231: #     now be honored.
                   7232: #
                   7233: sub UpdateHosts {
1.165     albertel 7234:     &status("Reload hosts.tab");
1.147     foxr     7235:     logthis('<font color="blue"> Updating connections </font>');
1.148     foxr     7236:     #
                   7237:     #  The %children hash has the set of IP's we currently have children
                   7238:     #  on.  These need to be matched against records in the hosts.tab
                   7239:     #  Any ip's no longer in the table get killed off they correspond to
                   7240:     #  either dropped or changed hosts.  Note that the re-read of the table
                   7241:     #  will take care of new and changed hosts as connections come into being.
                   7242: 
1.371     albertel 7243:     &Apache::lonnet::reset_hosts_info();
1.532     raeburn  7244:     my %active;
1.148     foxr     7245: 
1.368     albertel 7246:     foreach my $child (keys(%children)) {
1.148     foxr     7247: 	my $childip = $children{$child};
1.374     albertel 7248: 	if ($childip ne '127.0.0.1'
                   7249: 	    && !defined(&Apache::lonnet::get_hosts_from_ip($childip))) {
1.149     foxr     7250: 	    logthis('<font color="blue"> UpdateHosts killing child '
                   7251: 		    ." $child for ip $childip </font>");
1.148     foxr     7252: 	    kill('INT', $child);
1.149     foxr     7253: 	} else {
1.532     raeburn  7254:             $active{$child} = $childip;
1.149     foxr     7255: 	    logthis('<font color="green"> keeping child for ip '
                   7256: 		    ." $childip (pid=$child) </font>");
1.148     foxr     7257: 	}
                   7258:     }
1.532     raeburn  7259: 
                   7260:     my %oldconf = %secureconf;
                   7261:     my %connchange;
1.555     raeburn  7262:     if (lonssl::Read_Connect_Config(\%secureconf,\%perlvar,\%crlchecked) eq 'ok') {
1.545     raeburn  7263:         logthis('<font color="blue"> Reloaded SSL connection rules and cleared CRL checking history </font>');
1.532     raeburn  7264:     } else {
1.545     raeburn  7265:         logthis('<font color="yellow"> Failed to reload SSL connection rules and clear CRL checking history </font>');
1.532     raeburn  7266:     }
                   7267:     if ((ref($oldconf{'connfrom'}) eq 'HASH') && (ref($secureconf{'connfrom'}) eq 'HASH')) {
                   7268:         foreach my $type ('dom','intdom','other') {
                   7269:             if ((($oldconf{'connfrom'}{$type} eq 'no') && ($secureconf{'connfrom'}{$type} eq 'req')) ||
                   7270:                 (($oldconf{'connfrom'}{$type} eq 'req') && ($secureconf{'connfrom'}{$type} eq 'no'))) {
                   7271:                 $connchange{$type} = 1;
                   7272:             }
                   7273:         }
                   7274:     }
                   7275:     if (keys(%connchange)) {
                   7276:         foreach my $child (keys(%active)) {
                   7277:             my $childip = $active{$child};
                   7278:             if ($childip ne '127.0.0.1') {
                   7279:                 my $childhostname  = gethostbyaddr(Socket::inet_aton($childip),AF_INET);
                   7280:                 if ($childhostname ne '') {
                   7281:                     my $childlonhost = &Apache::lonnet::get_server_homeID($childhostname);
                   7282:                     my ($samedom,$sameinst) = &set_client_info($childlonhost);
                   7283:                     if ($samedom) {
                   7284:                         if ($connchange{'dom'}) {
                   7285:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7286:                                    ." $child for ip $childip </font>");
                   7287:                             kill('INT', $child);
                   7288:                         }
                   7289:                     } elsif ($sameinst) {
                   7290:                         if ($connchange{'intdom'}) {
                   7291:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7292:                                    ." $child for ip $childip </font>");
                   7293:                            kill('INT', $child);
                   7294:                         }
                   7295:                     } else {
                   7296:                         if ($connchange{'other'}) {
                   7297:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7298:                                    ." $child for ip $childip </font>");
                   7299:                             kill('INT', $child);
                   7300:                         }
                   7301:                     }
                   7302:                 }
                   7303:             }
                   7304:         }
                   7305:     }
1.148     foxr     7306:     ReloadApache;
1.165     albertel 7307:     &status("Finished reloading hosts.tab");
1.144     foxr     7308: }
                   7309: 
1.57      www      7310: sub checkchildren {
1.165     albertel 7311:     &status("Checking on the children (sending signals)");
1.57      www      7312:     &initnewstatus();
                   7313:     &logstatus();
                   7314:     &logthis('Going to check on the children');
1.134     albertel 7315:     my $docdir=$perlvar{'lonDocRoot'};
1.61      harris41 7316:     foreach (sort keys %children) {
1.221     albertel 7317: 	#sleep 1;
1.57      www      7318:         unless (kill 'USR1' => $_) {
                   7319: 	    &logthis ('Child '.$_.' is dead');
                   7320:             &logstatus($$.' is dead');
1.221     albertel 7321: 	    delete($children{$_});
1.57      www      7322:         } 
1.61      harris41 7323:     }
1.63      www      7324:     sleep 5;
1.212     foxr     7325:     $SIG{ALRM} = sub { Debug("timeout"); 
                   7326: 		       die "timeout";  };
1.113     albertel 7327:     $SIG{__DIE__} = 'DEFAULT';
1.165     albertel 7328:     &status("Checking on the children (waiting for reports)");
1.63      www      7329:     foreach (sort keys %children) {
                   7330:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113     albertel 7331:           eval {
                   7332:             alarm(300);
1.63      www      7333: 	    &logthis('Child '.$_.' did not respond');
1.67      albertel 7334: 	    kill 9 => $_;
1.131     albertel 7335: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   7336: 	    #$subj="LON: $currenthostid killed lond process $_";
                   7337: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
                   7338: 	    #$execdir=$perlvar{'lonDaemons'};
                   7339: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.221     albertel 7340: 	    delete($children{$_});
1.113     albertel 7341: 	    alarm(0);
                   7342: 	  }
1.63      www      7343:         }
                   7344:     }
1.113     albertel 7345:     $SIG{ALRM} = 'DEFAULT';
1.155     albertel 7346:     $SIG{__DIE__} = \&catchexception;
1.165     albertel 7347:     &status("Finished checking children");
1.221     albertel 7348:     &logthis('Finished Checking children');
1.57      www      7349: }
                   7350: 
1.1       albertel 7351: # --------------------------------------------------------------------- Logging
                   7352: 
                   7353: sub logthis {
                   7354:     my $message=shift;
                   7355:     my $execdir=$perlvar{'lonDaemons'};
                   7356:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
                   7357:     my $now=time;
                   7358:     my $local=localtime($now);
1.58      www      7359:     $lastlog=$local.': '.$message;
1.1       albertel 7360:     print $fh "$local ($$): $message\n";
                   7361: }
                   7362: 
1.77      foxr     7363: # ------------------------- Conditional log if $DEBUG true.
                   7364: sub Debug {
                   7365:     my $message = shift;
                   7366:     if($DEBUG) {
                   7367: 	&logthis($message);
                   7368:     }
                   7369: }
1.161     foxr     7370: 
                   7371: #
                   7372: #   Sub to do replies to client.. this gives a hook for some
                   7373: #   debug tracing too:
                   7374: #  Parameters:
                   7375: #     fd      - File open on client.
                   7376: #     reply   - Text to send to client.
                   7377: #     request - Original request from client.
                   7378: #
1.490     droeschl 7379: #NOTE $reply must be terminated by exactly *one* \n. If $reply is a reference
                   7380: #this is done automatically ($$reply must not contain any \n in this case). 
                   7381: #If $reply is a string the caller has to ensure this.
1.161     foxr     7382: sub Reply {
1.192     foxr     7383:     my ($fd, $reply, $request) = @_;
1.387     albertel 7384:     if (ref($reply)) {
                   7385: 	print $fd $$reply;
                   7386: 	print $fd "\n";
                   7387: 	if ($DEBUG) { Debug("Request was $request  Reply was $$reply"); }
                   7388:     } else {
                   7389: 	print $fd $reply;
                   7390: 	if ($DEBUG) { Debug("Request was $request  Reply was $reply"); }
                   7391:     }
1.212     foxr     7392:     $Transactions++;
                   7393: }
                   7394: 
                   7395: 
                   7396: #
                   7397: #    Sub to report a failure.
                   7398: #    This function:
                   7399: #     -   Increments the failure statistic counters.
                   7400: #     -   Invokes Reply to send the error message to the client.
                   7401: # Parameters:
                   7402: #    fd       - File descriptor open on the client
                   7403: #    reply    - Reply text to emit.
                   7404: #    request  - The original request message (used by Reply
                   7405: #               to debug if that's enabled.
                   7406: # Implicit outputs:
                   7407: #    $Failures- The number of failures is incremented.
                   7408: #    Reply (invoked here) sends a message to the 
                   7409: #    client:
                   7410: #
                   7411: sub Failure {
                   7412:     my $fd      = shift;
                   7413:     my $reply   = shift;
                   7414:     my $request = shift;
                   7415:    
                   7416:     $Failures++;
                   7417:     Reply($fd, $reply, $request);      # That's simple eh?
1.161     foxr     7418: }
1.57      www      7419: # ------------------------------------------------------------------ Log status
                   7420: 
                   7421: sub logstatus {
1.178     foxr     7422:     &status("Doing logging");
                   7423:     my $docdir=$perlvar{'lonDocRoot'};
                   7424:     {
                   7425: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
1.200     matthew  7426:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
1.178     foxr     7427:         $fh->close();
                   7428:     }
1.221     albertel 7429:     &status("Finished $$.txt");
                   7430:     {
                   7431: 	open(LOG,">>$docdir/lon-status/londstatus.txt");
                   7432: 	flock(LOG,LOCK_EX);
                   7433: 	print LOG $$."\t".$clientname."\t".$currenthostid."\t"
                   7434: 	    .$status."\t".$lastlog."\t $keymode\n";
1.275     albertel 7435: 	flock(LOG,LOCK_UN);
1.221     albertel 7436: 	close(LOG);
                   7437:     }
1.178     foxr     7438:     &status("Finished logging");
1.57      www      7439: }
                   7440: 
                   7441: sub initnewstatus {
                   7442:     my $docdir=$perlvar{'lonDocRoot'};
                   7443:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
1.460     foxr     7444:     my $now=time();
1.57      www      7445:     my $local=localtime($now);
                   7446:     print $fh "LOND status $local - parent $$\n\n";
1.64      www      7447:     opendir(DIR,"$docdir/lon-status/londchld");
1.134     albertel 7448:     while (my $filename=readdir(DIR)) {
1.64      www      7449:         unlink("$docdir/lon-status/londchld/$filename");
                   7450:     }
                   7451:     closedir(DIR);
1.57      www      7452: }
                   7453: 
                   7454: # -------------------------------------------------------------- Status setting
                   7455: 
                   7456: sub status {
                   7457:     my $what=shift;
                   7458:     my $now=time;
                   7459:     my $local=localtime($now);
1.178     foxr     7460:     $status=$local.': '.$what;
                   7461:     $0='lond: '.$what.' '.$local;
1.57      www      7462: }
1.11      www      7463: 
1.13      www      7464: # -------------------------------------------------------------- Talk to lonsql
                   7465: 
1.234     foxr     7466: sub sql_reply {
1.12      harris41 7467:     my ($cmd)=@_;
1.234     foxr     7468:     my $answer=&sub_sql_reply($cmd);
                   7469:     if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
1.12      harris41 7470:     return $answer;
                   7471: }
                   7472: 
1.234     foxr     7473: sub sub_sql_reply {
1.12      harris41 7474:     my ($cmd)=@_;
                   7475:     my $unixsock="mysqlsock";
                   7476:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
                   7477:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                   7478:                                       Type    => SOCK_STREAM,
                   7479:                                       Timeout => 10)
                   7480:        or return "con_lost";
1.319     www      7481:     print $sclient "$cmd:$currentdomainid\n";
1.12      harris41 7482:     my $answer=<$sclient>;
                   7483:     chomp($answer);
                   7484:     if (!$answer) { $answer="con_lost"; }
                   7485:     return $answer;
                   7486: }
                   7487: 
1.1       albertel 7488: # --------------------------------------- Is this the home server of an author?
1.11      www      7489: 
1.1       albertel 7490: sub ishome {
                   7491:     my $author=shift;
                   7492:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   7493:     my ($udom,$uname)=split(/\//,$author);
                   7494:     my $proname=propath($udom,$uname);
                   7495:     if (-e $proname) {
                   7496: 	return 'owner';
                   7497:     } else {
                   7498:         return 'not_owner';
                   7499:     }
                   7500: }
                   7501: 
                   7502: # ======================================================= Continue main program
                   7503: # ---------------------------------------------------- Fork once and dissociate
                   7504: 
1.134     albertel 7505: my $fpid=fork;
1.1       albertel 7506: exit if $fpid;
1.29      harris41 7507: die "Couldn't fork: $!" unless defined ($fpid);
1.1       albertel 7508: 
1.29      harris41 7509: POSIX::setsid() or die "Can't start new session: $!";
1.1       albertel 7510: 
                   7511: # ------------------------------------------------------- Write our PID on disk
                   7512: 
1.134     albertel 7513: my $execdir=$perlvar{'lonDaemons'};
1.1       albertel 7514: open (PIDSAVE,">$execdir/logs/lond.pid");
                   7515: print PIDSAVE "$$\n";
                   7516: close(PIDSAVE);
1.190     albertel 7517: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.57      www      7518: &status('Starting');
1.1       albertel 7519: 
1.106     foxr     7520: 
1.1       albertel 7521: 
                   7522: # ----------------------------------------------------- Install signal handlers
                   7523: 
1.57      www      7524: 
1.1       albertel 7525: $SIG{CHLD} = \&REAPER;
                   7526: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   7527: $SIG{HUP}  = \&HUPSMAN;
1.57      www      7528: $SIG{USR1} = \&checkchildren;
1.144     foxr     7529: $SIG{USR2} = \&UpdateHosts;
1.106     foxr     7530: 
1.148     foxr     7531: #  Read the host hashes:
1.368     albertel 7532: &Apache::lonnet::load_hosts_tab();
1.447     raeburn  7533: my %iphost = &Apache::lonnet::get_iphost(1);
1.106     foxr     7534: 
1.480     raeburn  7535: $dist=`$perlvar{'lonDaemons'}/distprobe`;
1.286     albertel 7536: 
1.471     raeburn  7537: my $arch = `uname -i`;
1.475     raeburn  7538: chomp($arch);
1.471     raeburn  7539: if ($arch eq 'unknown') {
                   7540:     $arch = `uname -m`;
1.475     raeburn  7541:     chomp($arch);
1.471     raeburn  7542: }
                   7543: 
1.555     raeburn  7544: unless (lonssl::Read_Connect_Config(\%secureconf,\%perlvar,\%crlchecked) eq 'ok') {
1.532     raeburn  7545:     &logthis('<font color="blue">No connectionrules table. Will fallback to loncapa.conf</font>');
                   7546: }
                   7547: 
1.106     foxr     7548: # --------------------------------------------------------------
                   7549: #   Accept connections.  When a connection comes in, it is validated
                   7550: #   and if good, a child process is created to process transactions
                   7551: #   along the connection.
                   7552: 
1.1       albertel 7553: while (1) {
1.165     albertel 7554:     &status('Starting accept');
1.106     foxr     7555:     $client = $server->accept() or next;
1.165     albertel 7556:     &status('Accepted '.$client.' off to spawn');
1.386     albertel 7557:     make_new_child($client);
1.165     albertel 7558:     &status('Finished spawning');
1.1       albertel 7559: }
                   7560: 
1.212     foxr     7561: sub make_new_child {
                   7562:     my $pid;
                   7563: #    my $cipher;     # Now global
                   7564:     my $sigset;
1.178     foxr     7565: 
1.212     foxr     7566:     $client = shift;
                   7567:     &status('Starting new child '.$client);
                   7568:     &logthis('<font color="green"> Attempting to start child ('.$client.
                   7569: 	     ")</font>");    
                   7570:     # block signal for fork
                   7571:     $sigset = POSIX::SigSet->new(SIGINT);
                   7572:     sigprocmask(SIG_BLOCK, $sigset)
                   7573:         or die "Can't block SIGINT for fork: $!\n";
1.178     foxr     7574: 
1.212     foxr     7575:     die "fork: $!" unless defined ($pid = fork);
1.178     foxr     7576: 
1.212     foxr     7577:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
                   7578: 	                               # connection liveness.
1.178     foxr     7579: 
1.212     foxr     7580:     #
                   7581:     #  Figure out who we're talking to so we can record the peer in 
                   7582:     #  the pid hash.
                   7583:     #
                   7584:     my $caller = getpeername($client);
                   7585:     my ($port,$iaddr);
                   7586:     if (defined($caller) && length($caller) > 0) {
                   7587: 	($port,$iaddr)=unpack_sockaddr_in($caller);
                   7588:     } else {
                   7589: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
                   7590:     }
                   7591:     if (defined($iaddr)) {
                   7592: 	$clientip  = inet_ntoa($iaddr);
                   7593: 	Debug("Connected with $clientip");
                   7594:     } else {
                   7595: 	&logthis("Unable to determine clientip");
                   7596: 	$clientip='Unavailable';
                   7597:     }
                   7598:     
                   7599:     if ($pid) {
                   7600:         # Parent records the child's birth and returns.
                   7601:         sigprocmask(SIG_UNBLOCK, $sigset)
                   7602:             or die "Can't unblock SIGINT for fork: $!\n";
                   7603:         $children{$pid} = $clientip;
                   7604:         &status('Started child '.$pid);
1.462     foxr     7605: 	close($client);
1.212     foxr     7606:         return;
                   7607:     } else {
                   7608:         # Child can *not* return from this subroutine.
                   7609:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
                   7610:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
                   7611:                                 #don't get intercepted
                   7612:         $SIG{USR1}= \&logstatus;
                   7613:         $SIG{ALRM}= \&timeout;
1.468     foxr     7614: 	#
                   7615: 	# Block sigpipe as it gets thrownon socket disconnect and we want to 
                   7616: 	# deal with that as a read faiure instead.
                   7617: 	#
                   7618: 	my $blockset = POSIX::SigSet->new(SIGPIPE);
                   7619: 	sigprocmask(SIG_BLOCK, $blockset);
                   7620: 
1.212     foxr     7621:         $lastlog='Forked ';
                   7622:         $status='Forked';
1.178     foxr     7623: 
1.212     foxr     7624:         # unblock signals
                   7625:         sigprocmask(SIG_UNBLOCK, $sigset)
                   7626:             or die "Can't unblock SIGINT for fork: $!\n";
1.178     foxr     7627: 
1.212     foxr     7628: #        my $tmpsnum=0;            # Now global
                   7629: #---------------------------------------------------- kerberos 5 initialization
                   7630:         &Authen::Krb5::init_context();
1.511     raeburn  7631: 
                   7632:         my $no_ets;
1.559     raeburn  7633:         if ($dist =~ /^(?:centos|rhes|scientific|oracle)(\d+)$/) {
1.511     raeburn  7634:             if ($1 >= 7) {
                   7635:                 $no_ets = 1;
                   7636:             }
                   7637:         } elsif ($dist =~ /^suse(\d+\.\d+)$/) {
                   7638:             if (($1 eq '9.3') || ($1 >= 12.2)) {
                   7639:                 $no_ets = 1; 
                   7640:             }
1.514     raeburn  7641:         } elsif ($dist =~ /^sles(\d+)$/) {
                   7642:             if ($1 > 11) {
                   7643:                 $no_ets = 1;
                   7644:             }
1.511     raeburn  7645:         } elsif ($dist =~ /^fedora(\d+)$/) {
                   7646:             if ($1 < 7) {
                   7647:                 $no_ets = 1;
                   7648:             }
                   7649:         }
                   7650:         unless ($no_ets) {
1.286     albertel 7651: 	    &Authen::Krb5::init_ets();
                   7652: 	}
1.209     albertel 7653: 
1.212     foxr     7654: 	&status('Accepted connection');
                   7655: # =============================================================================
                   7656:             # do something with the connection
                   7657: # -----------------------------------------------------------------------------
                   7658: 	# see if we know client and 'check' for spoof IP by ineffective challenge
1.178     foxr     7659: 
1.278     albertel 7660: 	my $outsideip=$clientip;
                   7661: 	if ($clientip eq '127.0.0.1') {
1.368     albertel 7662: 	    $outsideip=&Apache::lonnet::get_host_ip($perlvar{'lonHostID'});
1.278     albertel 7663: 	}
1.412     foxr     7664: 	&ReadManagerTable();
1.368     albertel 7665: 	my $clientrec=defined(&Apache::lonnet::get_hosts_from_ip($outsideip));
1.278     albertel 7666: 	my $ismanager=($managers{$outsideip}    ne undef);
1.432     raeburn  7667: 	$clientname  = "[unknown]";
1.212     foxr     7668: 	if($clientrec) {	# Establish client type.
                   7669: 	    $ConnectionType = "client";
1.368     albertel 7670: 	    $clientname = (&Apache::lonnet::get_hosts_from_ip($outsideip))[-1];
1.212     foxr     7671: 	    if($ismanager) {
                   7672: 		$ConnectionType = "both";
                   7673: 	    }
                   7674: 	} else {
                   7675: 	    $ConnectionType = "manager";
1.278     albertel 7676: 	    $clientname = $managers{$outsideip};
1.212     foxr     7677: 	}
1.556     raeburn  7678: 	my $clientok;
1.178     foxr     7679: 
1.212     foxr     7680: 	if ($clientrec || $ismanager) {
                   7681: 	    &status("Waiting for init from $clientip $clientname");
                   7682: 	    &logthis('<font color="yellow">INFO: Connection, '.
                   7683: 		     $clientip.
                   7684: 		  " ($clientname) connection type = $ConnectionType </font>" );
                   7685: 	    &status("Connecting $clientip  ($clientname))"); 
                   7686: 	    my $remotereq=<$client>;
                   7687: 	    chomp($remotereq);
                   7688: 	    Debug("Got init: $remotereq");
1.337     albertel 7689: 
1.212     foxr     7690: 	    if ($remotereq =~ /^init/) {
                   7691: 		&sethost("sethost:$perlvar{'lonHostID'}");
                   7692: 		#
                   7693: 		#  If the remote is attempting a local init... give that a try:
                   7694: 		#
1.432     raeburn  7695: 		(my $i, my $inittype, $clientversion) = split(/:/, $remotereq);
1.492     droeschl 7696:         # For LON-CAPA 2.9, the  client session will have sent its LON-CAPA
                   7697:         # version when initiating the connection. For LON-CAPA 2.8 and older,
                   7698:         # the version is retrieved from the global %loncaparevs in lonnet.pm.            
1.494     droeschl 7699:         # $clientversion contains path to keyfile if $inittype eq 'local'
                   7700:         # it's overridden below in this case
1.492     droeschl 7701:         $clientversion ||= $Apache::lonnet::loncaparevs{$clientname};
1.209     albertel 7702: 
1.212     foxr     7703: 		# If the connection type is ssl, but I didn't get my
                   7704: 		# certificate files yet, then I'll drop  back to 
                   7705: 		# insecure (if allowed).
1.532     raeburn  7706: 
                   7707:                 if ($inittype eq "ssl") {
                   7708:                     my $context;
                   7709:                     if ($clientsamedom) {
                   7710:                         $context = 'dom';
                   7711:                         if ($secureconf{'connfrom'}{'dom'} eq 'no') {
                   7712:                             $inittype = "";
                   7713:                         }
                   7714:                     } elsif ($clientsameinst) {
                   7715:                         $context = 'intdom';
                   7716:                         if ($secureconf{'connfrom'}{'intdom'} eq 'no') {
                   7717:                             $inittype = "";
                   7718:                         }
                   7719:                     } else {
                   7720:                         $context = 'other';
                   7721:                         if ($secureconf{'connfrom'}{'other'} eq 'no') {
                   7722:                             $inittype = "";
                   7723:                         }
                   7724:                     }
                   7725:                     if ($inittype eq '') {
                   7726:                         &logthis("<font color=\"blue\"> Domain config set "
                   7727:                                 ."to no ssl for $clientname (context: $context)"
                   7728:                                 ." -- trying insecure auth</font>");
                   7729:                     }
                   7730:                 }
                   7731: 
1.212     foxr     7732: 		if($inittype eq "ssl") {
                   7733: 		    my ($ca, $cert) = lonssl::CertificateFile;
                   7734: 		    my $kfile       = lonssl::KeyFile;
                   7735: 		    if((!$ca)   || 
                   7736: 		       (!$cert) || 
                   7737: 		       (!$kfile)) {
                   7738: 			$inittype = ""; # This forces insecure attempt.
                   7739: 			&logthis("<font color=\"blue\"> Certificates not "
                   7740: 				 ."installed -- trying insecure auth</font>");
1.224     foxr     7741: 		    } else {	# SSL certificates are in place so
1.212     foxr     7742: 		    }		# Leave the inittype alone.
                   7743: 		}
                   7744: 
                   7745: 		if($inittype eq "local") {
1.432     raeburn  7746:                     $clientversion = $perlvar{'lonVersion'};
1.212     foxr     7747: 		    my $key = LocalConnection($client, $remotereq);
                   7748: 		    if($key) {
                   7749: 			Debug("Got local key $key");
                   7750: 			$clientok     = 1;
                   7751: 			my $cipherkey = pack("H32", $key);
                   7752: 			$cipher       = new IDEA($cipherkey);
                   7753: 			print $client "ok:local\n";
1.442     www      7754: 			&logthis('<font color="green">'
1.212     foxr     7755: 				 . "Successful local authentication </font>");
                   7756: 			$keymode = "local"
1.178     foxr     7757: 		    } else {
1.212     foxr     7758: 			Debug("Failed to get local key");
                   7759: 			$clientok = 0;
                   7760: 			shutdown($client, 3);
                   7761: 			close $client;
1.178     foxr     7762: 		    }
1.212     foxr     7763: 		} elsif ($inittype eq "ssl") {
1.532     raeburn  7764: 		    my $key = SSLConnection($client,$clientname);
1.212     foxr     7765: 		    if ($key) {
                   7766: 			$clientok = 1;
                   7767: 			my $cipherkey = pack("H32", $key);
                   7768: 			$cipher       = new IDEA($cipherkey);
                   7769: 			&logthis('<font color="green">'
                   7770: 				 ."Successfull ssl authentication with $clientname </font>");
                   7771: 			$keymode = "ssl";
                   7772: 	     
1.178     foxr     7773: 		    } else {
1.212     foxr     7774: 			$clientok = 0;
                   7775: 			close $client;
1.178     foxr     7776: 		    }
1.212     foxr     7777: 	   
                   7778: 		} else {
                   7779: 		    my $ok = InsecureConnection($client);
                   7780: 		    if($ok) {
                   7781: 			$clientok = 1;
                   7782: 			&logthis('<font color="green">'
                   7783: 				 ."Successful insecure authentication with $clientname </font>");
                   7784: 			print $client "ok\n";
                   7785: 			$keymode = "insecure";
1.178     foxr     7786: 		    } else {
1.212     foxr     7787: 			&logthis('<font color="yellow">'
                   7788: 				  ."Attempted insecure connection disallowed </font>");
                   7789: 			close $client;
                   7790: 			$clientok = 0;
1.178     foxr     7791: 		    }
                   7792: 		}
1.212     foxr     7793: 	    } else {
                   7794: 		&logthis(
                   7795: 			 "<font color='blue'>WARNING: "
                   7796: 			 ."$clientip failed to initialize: >$remotereq< </font>");
                   7797: 		&status('No init '.$clientip);
                   7798: 	    }
                   7799: 	} else {
                   7800: 	    &logthis(
                   7801: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
                   7802: 	    &status('Hung up on '.$clientip);
                   7803: 	}
                   7804:  
                   7805: 	if ($clientok) {
                   7806: # ---------------- New known client connecting, could mean machine online again
1.368     albertel 7807: 	    if (&Apache::lonnet::get_host_ip($currenthostid) ne $clientip 
1.367     albertel 7808: 		&& $clientip ne '127.0.0.1') {
1.375     albertel 7809: 		&Apache::lonnet::reconlonc($clientname);
1.212     foxr     7810: 	    }
                   7811: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
                   7812: 	    &status('Will listen to '.$clientname);
                   7813: # ------------------------------------------------------------ Process requests
                   7814: 	    my $keep_going = 1;
                   7815: 	    my $user_input;
1.556     raeburn  7816: 
1.212     foxr     7817: 	    while(($user_input = get_request) && $keep_going) {
                   7818: 		alarm(120);
                   7819: 		Debug("Main: Got $user_input\n");
                   7820: 		$keep_going = &process_request($user_input);
1.178     foxr     7821: 		alarm(0);
1.212     foxr     7822: 		&status('Listening to '.$clientname." ($keymode)");	   
1.161     foxr     7823: 	    }
1.212     foxr     7824: 
1.59      www      7825: # --------------------------------------------- client unknown or fishy, refuse
1.212     foxr     7826: 	}  else {
1.161     foxr     7827: 	    print $client "refused\n";
                   7828: 	    $client->close();
1.190     albertel 7829: 	    &logthis("<font color='blue'>WARNING: "
1.161     foxr     7830: 		     ."Rejected client $clientip, closing connection</font>");
                   7831: 	}
1.525     raeburn  7832:     }
1.161     foxr     7833:     
1.1       albertel 7834: # =============================================================================
1.161     foxr     7835:     
1.190     albertel 7836:     &logthis("<font color='red'>CRITICAL: "
1.161     foxr     7837: 	     ."Disconnect from $clientip ($clientname)</font>");    
                   7838:     
                   7839:     
                   7840:     # this exit is VERY important, otherwise the child will become
                   7841:     # a producer of more and more children, forking yourself into
                   7842:     # process death.
                   7843:     exit;
1.106     foxr     7844:     
1.78      foxr     7845: }
1.532     raeburn  7846: 
                   7847: #
                   7848: #  Used to determine if a particular client is from the same domain
1.556     raeburn  7849: #  as the current server, or from the same internet domain, and
                   7850: #  also if the client can host sessions for the domain's users.
                   7851: #  A hash is populated with keys set to commands sent by the client
                   7852: #  which may not be executed for this domain.
1.532     raeburn  7853: #
                   7854: #  Optional input -- the client to check for domain and internet domain.
                   7855: #  If not specified, defaults to the package variable: $clientname
                   7856: #
                   7857: #  If called in array context will not set package variables, but will
                   7858: #  instead return an array of two values - (a) true if client is in the
1.556     raeburn  7859: #  same domain as the server, and (b) true if client is in the same 
                   7860: #  internet domain.
1.532     raeburn  7861: #
                   7862: #  If called in scalar context, sets package variables for current client:
                   7863: #
1.556     raeburn  7864: #  $clienthomedom    - LonCAPA domain of homeID for client.
                   7865: #  $clientsamedom    - LonCAPA domain same for this host and client.
                   7866: #  $clientintdom     - LonCAPA "internet domain" for client.
                   7867: #  $clientsameinst   - LonCAPA "internet domain" same for this host & client.
                   7868: #  $clientremoteok   - If current domain permits hosting on this client: 1
                   7869: #  %clientprohibited - Commands prohibited for domain's users for this client.
                   7870: #
                   7871: #  if the host and client have the same "internet domain", then the value
                   7872: #  of $clientremoteok is not used, and no commands are prohibited.
1.532     raeburn  7873: #
                   7874: #  returns 1 to indicate package variables have been set for current client.
                   7875: #
                   7876: 
                   7877: sub set_client_info {
                   7878:     my ($lonhost) = @_;
                   7879:     $lonhost ||= $clientname;
                   7880:     my $clienthost = &Apache::lonnet::hostname($lonhost);
                   7881:     my $clientserverhomeID = &Apache::lonnet::get_server_homeID($clienthost);
                   7882:     my $homedom = &Apache::lonnet::host_domain($clientserverhomeID);
                   7883:     my $samedom = 0;
1.557     raeburn  7884:     if ($perlvar{'lonDefDomain'} eq $homedom) {
1.532     raeburn  7885:         $samedom = 1;
                   7886:     }
                   7887:     my $intdom = &Apache::lonnet::internet_dom($clientserverhomeID);
                   7888:     my $sameinst = 0;
                   7889:     if ($intdom ne '') {
                   7890:         my $internet_names = &Apache::lonnet::get_internet_names($currenthostid);
                   7891:         if (ref($internet_names) eq 'ARRAY') {
                   7892:             if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   7893:                 $sameinst = 1;
                   7894:             }
                   7895:         }
                   7896:     }
                   7897:     if (wantarray) {
                   7898:         return ($samedom,$sameinst);
                   7899:     } else {
                   7900:         $clienthomedom = $homedom;
                   7901:         $clientsamedom = $samedom;
                   7902:         $clientintdom = $intdom;
                   7903:         $clientsameinst = $sameinst;
1.556     raeburn  7904:         if ($clientsameinst) {
                   7905:             undef($clientremoteok);
                   7906:             undef(%clientprohibited);
                   7907:         } else {
                   7908:             $clientremoteok = &get_remote_hostable($currentdomainid);
                   7909:             %clientprohibited = &get_prohibited($currentdomainid);
                   7910:         }
1.532     raeburn  7911:         return 1;
                   7912:     }
                   7913: }
                   7914: 
1.261     foxr     7915: #
                   7916: #   Determine if a user is an author for the indicated domain.
                   7917: #
                   7918: # Parameters:
                   7919: #    domain          - domain to check in .
                   7920: #    user            - Name of user to check.
                   7921: #
                   7922: # Return:
                   7923: #     1             - User is an author for domain.
                   7924: #     0             - User is not an author for domain.
                   7925: sub is_author {
                   7926:     my ($domain, $user) = @_;
                   7927: 
                   7928:     &Debug("is_author: $user @ $domain");
                   7929: 
                   7930:     my $hashref = &tie_user_hash($domain, $user, "roles",
                   7931: 				 &GDBM_READER());
                   7932: 
                   7933:     #  Author role should show up as a key /domain/_au
1.78      foxr     7934: 
1.321     albertel 7935:     my $value;
1.487     foxr     7936:     if ($hashref) {
1.78      foxr     7937: 
1.487     foxr     7938: 	my $key    = "/$domain/_au";
                   7939: 	if (defined($hashref)) {
                   7940: 	    $value = $hashref->{$key};
                   7941: 	    if(!untie_user_hash($hashref)) {
                   7942: 		return 'error: ' .  ($!+0)." untie (GDBM) Failed";
                   7943: 	    }
                   7944: 	}
                   7945: 	
                   7946: 	if(defined($value)) {
                   7947: 	    &Debug("$user @ $domain is an author");
                   7948: 	}
                   7949:     } else {
                   7950: 	return 'error: '.($!+0)." tie (GDBM) Failed";
1.261     foxr     7951:     }
                   7952: 
                   7953:     return defined($value);
                   7954: }
1.78      foxr     7955: #
                   7956: #   Checks to see if the input roleput request was to set
1.482     www      7957: # an author role.  If so, creates construction space 
1.78      foxr     7958: # Parameters:
                   7959: #    request   - The request sent to the rolesput subchunk.
                   7960: #                We're looking for  /domain/_au
                   7961: #    domain    - The domain in which the user is having roles doctored.
                   7962: #    user      - Name of the user for which the role is being put.
                   7963: #    authtype  - The authentication type associated with the user.
                   7964: #
1.289     albertel 7965: sub manage_permissions {
1.192     foxr     7966:     my ($request, $domain, $user, $authtype) = @_;
1.78      foxr     7967:     # See if the request is of the form /$domain/_au
1.289     albertel 7968:     if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
1.484     raeburn  7969:         my $path=$perlvar{'lonDocRoot'}."/priv/$domain";
1.482     www      7970:         unless (-e $path) {        
                   7971:            mkdir($path);
                   7972:         }
                   7973:         unless (-e $path.'/'.$user) {
                   7974:            mkdir($path.'/'.$user);
                   7975:         }
1.78      foxr     7976:     }
                   7977: }
1.222     foxr     7978: 
                   7979: 
                   7980: #
                   7981: #  Return the full path of a user password file, whether it exists or not.
                   7982: # Parameters:
                   7983: #   domain     - Domain in which the password file lives.
                   7984: #   user       - name of the user.
                   7985: # Returns:
                   7986: #    Full passwd path:
                   7987: #
                   7988: sub password_path {
                   7989:     my ($domain, $user) = @_;
1.264     albertel 7990:     return &propath($domain, $user).'/passwd';
1.222     foxr     7991: }
                   7992: 
                   7993: #   Password Filename
                   7994: #   Returns the path to a passwd file given domain and user... only if
                   7995: #  it exists.
                   7996: # Parameters:
                   7997: #   domain    - Domain in which to search.
                   7998: #   user      - username.
                   7999: # Returns:
                   8000: #   - If the password file exists returns its path.
                   8001: #   - If the password file does not exist, returns undefined.
                   8002: #
                   8003: sub password_filename {
                   8004:     my ($domain, $user) = @_;
                   8005: 
                   8006:     Debug ("PasswordFilename called: dom = $domain user = $user");
                   8007: 
                   8008:     my $path  = &password_path($domain, $user);
                   8009:     Debug("PasswordFilename got path: $path");
                   8010:     if(-e $path) {
                   8011: 	return $path;
                   8012:     } else {
                   8013: 	return undef;
                   8014:     }
                   8015: }
                   8016: 
                   8017: #
                   8018: #   Rewrite the contents of the user's passwd file.
                   8019: #  Parameters:
                   8020: #    domain    - domain of the user.
                   8021: #    name      - User's name.
                   8022: #    contents  - New contents of the file.
1.533     raeburn  8023: #    saveold   - (optional). If true save old file in a passwd.bak file.
1.222     foxr     8024: # Returns:
                   8025: #   0    - Failed.
                   8026: #   1    - Success.
                   8027: #
                   8028: sub rewrite_password_file {
1.533     raeburn  8029:     my ($domain, $user, $contents, $saveold) = @_;
1.222     foxr     8030: 
                   8031:     my $file = &password_filename($domain, $user);
                   8032:     if (defined $file) {
1.533     raeburn  8033:         if ($saveold) {
                   8034:             my $bakfile = $file.'.bak';
                   8035:             if (CopyFile($file,$bakfile)) {
                   8036:                 chmod(0400,$bakfile);
                   8037:                 &logthis("Old password saved in passwd.bak for internally authenticated user: $user:$domain");
                   8038:             } else {
                   8039:                 &logthis("Failed to save old password in passwd.bak for internally authenticated user: $user:$domain");
                   8040:             }
                   8041:         }
1.222     foxr     8042: 	my $pf = IO::File->new(">$file");
                   8043: 	if($pf) {
                   8044: 	    print $pf "$contents\n";
                   8045: 	    return 1;
                   8046: 	} else {
                   8047: 	    return 0;
                   8048: 	}
                   8049:     } else {
                   8050: 	return 0;
                   8051:     }
                   8052: 
                   8053: }
                   8054: 
1.78      foxr     8055: #
1.222     foxr     8056: #   get_auth_type - Determines the authorization type of a user in a domain.
1.78      foxr     8057: 
                   8058: #     Returns the authorization type or nouser if there is no such user.
                   8059: #
1.436     raeburn  8060: sub get_auth_type {
1.192     foxr     8061:     my ($domain, $user)  = @_;
1.78      foxr     8062: 
1.222     foxr     8063:     Debug("get_auth_type( $domain, $user ) \n");
1.78      foxr     8064:     my $proname    = &propath($domain, $user); 
                   8065:     my $passwdfile = "$proname/passwd";
                   8066:     if( -e $passwdfile ) {
                   8067: 	my $pf = IO::File->new($passwdfile);
                   8068: 	my $realpassword = <$pf>;
                   8069: 	chomp($realpassword);
1.79      foxr     8070: 	Debug("Password info = $realpassword\n");
1.78      foxr     8071: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79      foxr     8072: 	Debug("Authtype = $authtype, content = $contentpwd\n");
1.259     raeburn  8073: 	return "$authtype:$contentpwd";     
1.224     foxr     8074:     } else {
1.79      foxr     8075: 	Debug("Returning nouser");
1.78      foxr     8076: 	return "nouser";
                   8077:     }
1.1       albertel 8078: }
                   8079: 
1.220     foxr     8080: #
                   8081: #  Validate a user given their domain, name and password.  This utility
                   8082: #  function is used by both  AuthenticateHandler and ChangePasswordHandler
                   8083: #  to validate the login credentials of a user.
                   8084: # Parameters:
                   8085: #    $domain    - The domain being logged into (this is required due to
                   8086: #                 the capability for multihomed systems.
                   8087: #    $user      - The name of the user being validated.
                   8088: #    $password  - The user's propoposed password.
                   8089: #
                   8090: # Returns:
                   8091: #     1        - The domain,user,pasword triplet corresponds to a valid
                   8092: #                user.
                   8093: #     0        - The domain,user,password triplet is not a valid user.
                   8094: #
                   8095: sub validate_user {
1.396     raeburn  8096:     my ($domain, $user, $password, $checkdefauth) = @_;
1.220     foxr     8097: 
                   8098:     # Why negative ~pi you may well ask?  Well this function is about
                   8099:     # authentication, and therefore very important to get right.
                   8100:     # I've initialized the flag that determines whether or not I've 
                   8101:     # validated correctly to a value it's not supposed to get.
                   8102:     # At the end of this function. I'll ensure that it's not still that
                   8103:     # value so we don't just wind up returning some accidental value
                   8104:     # as a result of executing an unforseen code path that
1.249     foxr     8105:     # did not set $validated.  At the end of valid execution paths,
                   8106:     # validated shoule be 1 for success or 0 for failuer.
1.220     foxr     8107: 
                   8108:     my $validated = -3.14159;
                   8109: 
                   8110:     #  How we authenticate is determined by the type of authentication
                   8111:     #  the user has been assigned.  If the authentication type is
                   8112:     #  "nouser", the user does not exist so we will return 0.
                   8113: 
1.222     foxr     8114:     my $contents = &get_auth_type($domain, $user);
1.220     foxr     8115:     my ($howpwd, $contentpwd) = split(/:/, $contents);
                   8116: 
                   8117:     my $null = pack("C",0);	# Used by kerberos auth types.
                   8118: 
1.395     raeburn  8119:     if ($howpwd eq 'nouser') {
1.396     raeburn  8120:         if ($checkdefauth) {
                   8121:             my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   8122:             if ($domdefaults{'auth_def'} eq 'localauth') {
                   8123:                 $howpwd = $domdefaults{'auth_def'};
                   8124:                 $contentpwd = $domdefaults{'auth_arg_def'};
                   8125:             } elsif ((($domdefaults{'auth_def'} eq 'krb4') || 
                   8126:                       ($domdefaults{'auth_def'} eq 'krb5')) &&
                   8127:                      ($domdefaults{'auth_arg_def'} ne '')) {
                   8128:                 $howpwd = $domdefaults{'auth_def'};
                   8129:                 $contentpwd = $domdefaults{'auth_arg_def'}; 
                   8130:             }
1.395     raeburn  8131:         }
1.533     raeburn  8132:     }
1.220     foxr     8133:     if ($howpwd ne 'nouser') {
                   8134: 	if($howpwd eq "internal") { # Encrypted is in local password file.
1.518     raeburn  8135:             if (length($contentpwd) == 13) {
                   8136:                 $validated = (crypt($password,$contentpwd) eq $contentpwd);
                   8137:                 if ($validated) {
1.533     raeburn  8138:                     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   8139:                     if ($domdefaults{'intauth_switch'}) {
                   8140:                         my $ncpass = &hash_passwd($domain,$password);
                   8141:                         my $saveold;
                   8142:                         if ($domdefaults{'intauth_switch'} == 2) {
                   8143:                             $saveold = 1;
                   8144:                         }
                   8145:                         if (&rewrite_password_file($domain,$user,"$howpwd:$ncpass",$saveold)) {
                   8146:                             &update_passwd_history($user,$domain,$howpwd,'conversion');
                   8147:                             &logthis("Validated password hashed with bcrypt for $user:$domain");
                   8148:                         }
1.518     raeburn  8149:                     }
                   8150:                 }
                   8151:             } else {
1.533     raeburn  8152:                 $validated = &check_internal_passwd($password,$contentpwd,$domain,$user);
1.518     raeburn  8153:             }
1.220     foxr     8154: 	}
                   8155: 	elsif ($howpwd eq "unix") { # User is a normal unix user.
                   8156: 	    $contentpwd = (getpwnam($user))[1];
                   8157: 	    if($contentpwd) {
                   8158: 		if($contentpwd eq 'x') { # Shadow password file...
                   8159: 		    my $pwauth_path = "/usr/local/sbin/pwauth";
                   8160: 		    open PWAUTH,  "|$pwauth_path" or
                   8161: 			die "Cannot invoke authentication";
                   8162: 		    print PWAUTH "$user\n$password\n";
                   8163: 		    close PWAUTH;
                   8164: 		    $validated = ! $?;
                   8165: 
                   8166: 		} else { 	         # Passwords in /etc/passwd. 
                   8167: 		    $validated = (crypt($password,
                   8168: 					$contentpwd) eq $contentpwd);
                   8169: 		}
                   8170: 	    } else {
                   8171: 		$validated = 0;
                   8172: 	    }
1.439     raeburn  8173: 	} elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
                   8174:             my $checkwithkrb5 = 0;
                   8175:             if ($dist =~/^fedora(\d+)$/) {
                   8176:                 if ($1 > 11) {
                   8177:                     $checkwithkrb5 = 1;
                   8178:                 }
                   8179:             } elsif ($dist =~ /^suse([\d.]+)$/) {
                   8180:                 if ($1 > 11.1) {
                   8181:                     $checkwithkrb5 = 1; 
                   8182:                 }
                   8183:             }
                   8184:             if ($checkwithkrb5) {
                   8185:                 $validated = &krb5_authen($password,$null,$user,$contentpwd);
                   8186:             } else {
                   8187:                 $validated = &krb4_authen($password,$null,$user,$contentpwd);
                   8188:             }
1.224     foxr     8189: 	} elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
1.439     raeburn  8190:             $validated = &krb5_authen($password,$null,$user,$contentpwd);
1.224     foxr     8191: 	} elsif ($howpwd eq "localauth") { 
1.220     foxr     8192: 	    #  Authenticate via installation specific authentcation method:
                   8193: 	    $validated = &localauth::localauth($user, 
                   8194: 					       $password, 
1.353     albertel 8195: 					       $contentpwd,
                   8196: 					       $domain);
1.358     albertel 8197: 	    if ($validated < 0) {
1.357     albertel 8198: 		&logthis("localauth for $contentpwd $user:$domain returned a $validated");
                   8199: 		$validated = 0;
                   8200: 	    }
1.224     foxr     8201: 	} else {			# Unrecognized auth is also bad.
1.220     foxr     8202: 	    $validated = 0;
                   8203: 	}
                   8204:     } else {
                   8205: 	$validated = 0;
                   8206:     }
                   8207:     #
                   8208:     #  $validated has the correct stat of the authentication:
                   8209:     #
                   8210: 
                   8211:     unless ($validated != -3.14159) {
1.249     foxr     8212: 	#  I >really really< want to know if this happens.
                   8213: 	#  since it indicates that user authentication is badly
                   8214: 	#  broken in some code path.
                   8215:         #
                   8216: 	die "ValidateUser - failed to set the value of validated $domain, $user $password";
1.220     foxr     8217:     }
                   8218:     return $validated;
                   8219: }
                   8220: 
1.518     raeburn  8221: sub check_internal_passwd {
1.533     raeburn  8222:     my ($plainpass,$stored,$domain,$user) = @_;
1.518     raeburn  8223:     my (undef,$method,@rest) = split(/!/,$stored);
1.533     raeburn  8224:     if ($method eq 'bcrypt') {
1.518     raeburn  8225:         my $result = &hash_passwd($domain,$plainpass,@rest);
                   8226:         if ($result ne $stored) {
                   8227:             return 0;
                   8228:         }
1.533     raeburn  8229:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   8230:         if ($domdefaults{'intauth_check'}) {
                   8231:             # Upgrade to a larger number of rounds if necessary
                   8232:             my $defaultcost = $domdefaults{'intauth_cost'};
                   8233:             if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
                   8234:                 $defaultcost = 10;
                   8235:             }
                   8236:             if (int($rest[0])<int($defaultcost)) {
                   8237:                 if ($domdefaults{'intauth_check'} == 1) { 
                   8238:                     my $ncpass = &hash_passwd($domain,$plainpass);
                   8239:                     if (&rewrite_password_file($domain,$user,"internal:$ncpass")) {
                   8240:                         &update_passwd_history($user,$domain,'internal','update cost');
                   8241:                         &logthis("Validated password hashed with bcrypt for $user:$domain");
                   8242:                     }
                   8243:                     return 1;
                   8244:                 } elsif ($domdefaults{'intauth_check'} == 2) {
                   8245:                     return 0;
                   8246:                 }
                   8247:             }
                   8248:         } else {
                   8249:             return 1;
1.518     raeburn  8250:         }
                   8251:     }
                   8252:     return 0;
                   8253: }
                   8254: 
                   8255: sub get_last_authchg {
                   8256:     my ($domain,$user) = @_;
                   8257:     my $lastmod;
                   8258:     my $logname = &propath($domain,$user).'/passwd.log';
                   8259:     if (-e "$logname") {
                   8260:         $lastmod = (stat("$logname"))[9];
                   8261:     }
                   8262:     return $lastmod;
                   8263: }
                   8264: 
1.439     raeburn  8265: sub krb4_authen {
                   8266:     my ($password,$null,$user,$contentpwd) = @_;
                   8267:     my $validated = 0;
                   8268:     if (!($password =~ /$null/) ) {  # Null password not allowed.
                   8269:         eval {
                   8270:             require Authen::Krb4;
                   8271:         };
                   8272:         if (!$@) {
                   8273:             my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
                   8274:                                                        "",
                   8275:                                                        $contentpwd,,
                   8276:                                                        'krbtgt',
                   8277:                                                        $contentpwd,
                   8278:                                                        1,
                   8279:                                                        $password);
                   8280:             if(!$k4error) {
                   8281:                 $validated = 1;
                   8282:             } else {
                   8283:                 $validated = 0;
                   8284:                 &logthis('krb4: '.$user.', '.$contentpwd.', '.
                   8285:                           &Authen::Krb4::get_err_txt($Authen::Krb4::error));
                   8286:             }
                   8287:         } else {
                   8288:             $validated = krb5_authen($password,$null,$user,$contentpwd);
                   8289:         }
                   8290:     }
                   8291:     return $validated;
                   8292: }
                   8293: 
                   8294: sub krb5_authen {
                   8295:     my ($password,$null,$user,$contentpwd) = @_;
                   8296:     my $validated = 0;
                   8297:     if(!($password =~ /$null/)) { # Null password not allowed.
                   8298:         my $krbclient = &Authen::Krb5::parse_name($user.'@'
                   8299:                                                   .$contentpwd);
                   8300:         my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
                   8301:         my $krbserver  = &Authen::Krb5::parse_name($krbservice);
                   8302:         my $credentials= &Authen::Krb5::cc_default();
                   8303:         $credentials->initialize(&Authen::Krb5::parse_name($user.'@'
                   8304:                                                             .$contentpwd));
                   8305:         my $krbreturn;
                   8306:         if (exists(&Authen::Krb5::get_init_creds_password)) {
                   8307:             $krbreturn =
                   8308:                 &Authen::Krb5::get_init_creds_password($krbclient,$password,
                   8309:                                                           $krbservice);
                   8310:             $validated = (ref($krbreturn) eq 'Authen::Krb5::Creds');
                   8311:         } else {
                   8312:             $krbreturn  =
                   8313:                 &Authen::Krb5::get_in_tkt_with_password($krbclient,$krbserver,
                   8314:                                                          $password,$credentials);
                   8315:             $validated = ($krbreturn == 1);
                   8316:         }
                   8317:         if (!$validated) {
                   8318:             &logthis('krb5: '.$user.', '.$contentpwd.', '.
                   8319:                      &Authen::Krb5::error());
                   8320:         }
                   8321:     }
                   8322:     return $validated;
                   8323: }
1.220     foxr     8324: 
1.84      albertel 8325: sub addline {
                   8326:     my ($fname,$hostid,$ip,$newline)=@_;
                   8327:     my $contents;
                   8328:     my $found=0;
1.355     albertel 8329:     my $expr='^'.quotemeta($hostid).':'.quotemeta($ip).':';
1.134     albertel 8330:     my $sh;
1.84      albertel 8331:     if ($sh=IO::File->new("$fname.subscription")) {
                   8332: 	while (my $subline=<$sh>) {
                   8333: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
                   8334: 	}
                   8335: 	$sh->close();
                   8336:     }
                   8337:     $sh=IO::File->new(">$fname.subscription");
                   8338:     if ($contents) { print $sh $contents; }
                   8339:     if ($newline) { print $sh $newline; }
                   8340:     $sh->close();
                   8341:     return $found;
1.86      www      8342: }
                   8343: 
1.234     foxr     8344: sub get_chat {
1.324     raeburn  8345:     my ($cdom,$cname,$udom,$uname,$group)=@_;
1.310     albertel 8346: 
1.87      www      8347:     my @entries=();
1.324     raeburn  8348:     my $namespace = 'nohist_chatroom';
                   8349:     my $namespace_inroom = 'nohist_inchatroom';
1.335     albertel 8350:     if ($group ne '') {
1.324     raeburn  8351:         $namespace .= '_'.$group;
                   8352:         $namespace_inroom .= '_'.$group;
                   8353:     }
                   8354:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 8355: 				 &GDBM_READER());
                   8356:     if ($hashref) {
                   8357: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.311     albertel 8358: 	&untie_user_hash($hashref);
1.123     www      8359:     }
1.124     www      8360:     my @participants=();
1.134     albertel 8361:     my $cutoff=time-60;
1.324     raeburn  8362:     $hashref = &tie_user_hash($cdom, $cname, $namespace_inroom,
1.310     albertel 8363: 			      &GDBM_WRCREAT());
                   8364:     if ($hashref) {
                   8365:         $hashref->{$uname.':'.$udom}=time;
                   8366:         foreach my $user (sort(keys(%$hashref))) {
                   8367: 	    if ($hashref->{$user}>$cutoff) {
                   8368: 		push(@participants, 'active_participant:'.$user);
1.123     www      8369:             }
                   8370:         }
1.311     albertel 8371:         &untie_user_hash($hashref);
1.86      www      8372:     }
1.124     www      8373:     return (@participants,@entries);
1.86      www      8374: }
                   8375: 
1.234     foxr     8376: sub chat_add {
1.324     raeburn  8377:     my ($cdom,$cname,$newchat,$group)=@_;
1.88      albertel 8378:     my @entries=();
1.142     www      8379:     my $time=time;
1.324     raeburn  8380:     my $namespace = 'nohist_chatroom';
                   8381:     my $logfile = 'chatroom.log';
1.335     albertel 8382:     if ($group ne '') {
1.324     raeburn  8383:         $namespace .= '_'.$group;
                   8384:         $logfile = 'chatroom_'.$group.'.log';
                   8385:     }
                   8386:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 8387: 				 &GDBM_WRCREAT());
                   8388:     if ($hashref) {
                   8389: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.88      albertel 8390: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
                   8391: 	my ($thentime,$idnum)=split(/\_/,$lastid);
                   8392: 	my $newid=$time.'_000000';
                   8393: 	if ($thentime==$time) {
                   8394: 	    $idnum=~s/^0+//;
                   8395: 	    $idnum++;
                   8396: 	    $idnum=substr('000000'.$idnum,-6,6);
                   8397: 	    $newid=$time.'_'.$idnum;
                   8398: 	}
1.310     albertel 8399: 	$hashref->{$newid}=$newchat;
1.88      albertel 8400: 	my $expired=$time-3600;
1.310     albertel 8401: 	foreach my $comment (keys(%$hashref)) {
                   8402: 	    my ($thistime) = ($comment=~/(\d+)\_/);
1.88      albertel 8403: 	    if ($thistime<$expired) {
1.310     albertel 8404: 		delete $hashref->{$comment};
1.88      albertel 8405: 	    }
                   8406: 	}
1.310     albertel 8407: 	{
                   8408: 	    my $proname=&propath($cdom,$cname);
1.324     raeburn  8409: 	    if (open(CHATLOG,">>$proname/$logfile")) { 
1.310     albertel 8410: 		print CHATLOG ("$time:".&unescape($newchat)."\n");
                   8411: 	    }
                   8412: 	    close(CHATLOG);
1.142     www      8413: 	}
1.311     albertel 8414: 	&untie_user_hash($hashref);
1.86      www      8415:     }
1.84      albertel 8416: }
                   8417: 
                   8418: sub unsub {
                   8419:     my ($fname,$clientip)=@_;
                   8420:     my $result;
1.188     foxr     8421:     my $unsubs = 0;		# Number of successful unsubscribes:
                   8422: 
                   8423: 
                   8424:     # An old way subscriptions were handled was to have a 
                   8425:     # subscription marker file:
                   8426: 
                   8427:     Debug("Attempting unlink of $fname.$clientname");
1.161     foxr     8428:     if (unlink("$fname.$clientname")) {
1.188     foxr     8429: 	$unsubs++;		# Successful unsub via marker file.
                   8430:     } 
                   8431: 
                   8432:     # The more modern way to do it is to have a subscription list
                   8433:     # file:
                   8434: 
1.84      albertel 8435:     if (-e "$fname.subscription") {
1.161     foxr     8436: 	my $found=&addline($fname,$clientname,$clientip,'');
1.188     foxr     8437: 	if ($found) { 
                   8438: 	    $unsubs++;
                   8439: 	}
                   8440:     } 
                   8441: 
                   8442:     #  If either or both of these mechanisms succeeded in unsubscribing a 
                   8443:     #  resource we can return ok:
                   8444: 
                   8445:     if($unsubs) {
                   8446: 	$result = "ok\n";
1.84      albertel 8447:     } else {
1.188     foxr     8448: 	$result = "not_subscribed\n";
1.84      albertel 8449:     }
1.188     foxr     8450: 
1.84      albertel 8451:     return $result;
                   8452: }
                   8453: 
1.101     www      8454: sub currentversion {
                   8455:     my $fname=shift;
                   8456:     my $version=-1;
                   8457:     my $ulsdir='';
                   8458:     if ($fname=~/^(.+)\/[^\/]+$/) {
                   8459:        $ulsdir=$1;
                   8460:     }
1.114     albertel 8461:     my ($fnamere1,$fnamere2);
                   8462:     # remove version if already specified
1.101     www      8463:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114     albertel 8464:     # get the bits that go before and after the version number
                   8465:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
                   8466: 	$fnamere1=$1;
                   8467: 	$fnamere2='.'.$2;
                   8468:     }
1.101     www      8469:     if (-e $fname) { $version=1; }
                   8470:     if (-e $ulsdir) {
1.134     albertel 8471: 	if(-d $ulsdir) {
                   8472: 	    if (opendir(LSDIR,$ulsdir)) {
                   8473: 		my $ulsfn;
                   8474: 		while ($ulsfn=readdir(LSDIR)) {
1.101     www      8475: # see if this is a regular file (ignore links produced earlier)
1.134     albertel 8476: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
                   8477: 		    unless (-l $thisfile) {
1.160     www      8478: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134     albertel 8479: 			    if ($1>$version) { $version=$1; }
                   8480: 			}
                   8481: 		    }
                   8482: 		}
                   8483: 		closedir(LSDIR);
                   8484: 		$version++;
                   8485: 	    }
                   8486: 	}
                   8487:     }
                   8488:     return $version;
1.101     www      8489: }
                   8490: 
                   8491: sub thisversion {
                   8492:     my $fname=shift;
                   8493:     my $version=-1;
                   8494:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
                   8495: 	$version=$1;
                   8496:     }
                   8497:     return $version;
                   8498: }
                   8499: 
1.84      albertel 8500: sub subscribe {
                   8501:     my ($userinput,$clientip)=@_;
                   8502:     my $result;
1.293     albertel 8503:     my ($cmd,$fname)=split(/:/,$userinput,2);
1.84      albertel 8504:     my $ownership=&ishome($fname);
                   8505:     if ($ownership eq 'owner') {
1.101     www      8506: # explitly asking for the current version?
                   8507:         unless (-e $fname) {
                   8508:             my $currentversion=&currentversion($fname);
                   8509: 	    if (&thisversion($fname)==$currentversion) {
                   8510:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
                   8511: 		    my $root=$1;
                   8512:                     my $extension=$2;
                   8513:                     symlink($root.'.'.$extension,
                   8514:                             $root.'.'.$currentversion.'.'.$extension);
1.102     www      8515:                     unless ($extension=~/\.meta$/) {
                   8516:                        symlink($root.'.'.$extension.'.meta',
                   8517:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
                   8518: 		    }
1.101     www      8519:                 }
                   8520:             }
                   8521:         }
1.84      albertel 8522: 	if (-e $fname) {
                   8523: 	    if (-d $fname) {
                   8524: 		$result="directory\n";
                   8525: 	    } else {
1.161     foxr     8526: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134     albertel 8527: 		my $now=time;
1.161     foxr     8528: 		my $found=&addline($fname,$clientname,$clientip,
                   8529: 				   "$clientname:$clientip:$now\n");
1.84      albertel 8530: 		if ($found) { $result="$fname\n"; }
                   8531: 		# if they were subscribed to only meta data, delete that
                   8532:                 # subscription, when you subscribe to a file you also get
                   8533:                 # the metadata
                   8534: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
                   8535: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
1.476     raeburn  8536:                 my $protocol = $Apache::lonnet::protocol{$perlvar{'lonHostID'}};
                   8537:                 $protocol = 'http' if ($protocol ne 'https');
                   8538: 		$fname=$protocol.'://'.&Apache::lonnet::hostname($perlvar{'lonHostID'})."/".$fname;
1.84      albertel 8539: 		$result="$fname\n";
                   8540: 	    }
                   8541: 	} else {
                   8542: 	    $result="not_found\n";
                   8543: 	}
                   8544:     } else {
                   8545: 	$result="rejected\n";
                   8546:     }
                   8547:     return $result;
                   8548: }
1.287     foxr     8549: #  Change the passwd of a unix user.  The caller must have
                   8550: #  first verified that the user is a loncapa user.
                   8551: #
                   8552: # Parameters:
                   8553: #    user      - Unix user name to change.
                   8554: #    pass      - New password for the user.
                   8555: # Returns:
                   8556: #    ok    - if success
                   8557: #    other - Some meaningfule error message string.
                   8558: # NOTE:
                   8559: #    invokes a setuid script to change the passwd.
                   8560: sub change_unix_password {
                   8561:     my ($user, $pass) = @_;
                   8562: 
                   8563:     &Debug("change_unix_password");
                   8564:     my $execdir=$perlvar{'lonDaemons'};
                   8565:     &Debug("Opening lcpasswd pipeline");
                   8566:     my $pf = IO::File->new("|$execdir/lcpasswd > "
                   8567: 			   ."$perlvar{'lonDaemons'}"
                   8568: 			   ."/logs/lcpasswd.log");
                   8569:     print $pf "$user\n$pass\n$pass\n";
                   8570:     close $pf;
                   8571:     my $err = $?;
                   8572:     return ($err < @passwderrors) ? $passwderrors[$err] : 
                   8573: 	"pwchange_falure - unknown error";
                   8574: 
                   8575:     
                   8576: }
                   8577: 
1.91      albertel 8578: 
                   8579: sub make_passwd_file {
1.518     raeburn  8580:     my ($uname,$udom,$umode,$npass,$passfilename,$action)=@_;
1.390     raeburn  8581:     my $result="ok";
1.91      albertel 8582:     if ($umode eq 'krb4' or $umode eq 'krb5') {
                   8583: 	{
                   8584: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8585: 	    if ($pf) {
                   8586: 		print $pf "$umode:$npass\n";
1.518     raeburn  8587:                 &update_passwd_history($uname,$udom,$umode,$action);
1.261     foxr     8588: 	    } else {
                   8589: 		$result = "pass_file_failed_error";
                   8590: 	    }
1.91      albertel 8591: 	}
                   8592:     } elsif ($umode eq 'internal') {
1.518     raeburn  8593:         my $ncpass = &hash_passwd($udom,$npass);
1.91      albertel 8594: 	{
                   8595: 	    &Debug("Creating internal auth");
                   8596: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8597: 	    if($pf) {
1.518     raeburn  8598: 		print $pf "internal:$ncpass\n";
                   8599:                 &update_passwd_history($uname,$udom,$umode,$action); 
1.261     foxr     8600: 	    } else {
                   8601: 		$result = "pass_file_failed_error";
                   8602: 	    }
1.91      albertel 8603: 	}
                   8604:     } elsif ($umode eq 'localauth') {
                   8605: 	{
                   8606: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8607: 	    if($pf) {
                   8608: 		print $pf "localauth:$npass\n";
1.524     raeburn  8609:                 &update_passwd_history($uname,$udom,$umode,$action);
1.261     foxr     8610: 	    } else {
                   8611: 		$result = "pass_file_failed_error";
                   8612: 	    }
1.91      albertel 8613: 	}
                   8614:     } elsif ($umode eq 'unix') {
1.502     raeburn  8615: 	&logthis(">>>Attempt to create unix account blocked -- unix auth not available for new users.");
                   8616: 	$result="no_new_unix_accounts";
1.91      albertel 8617:     } elsif ($umode eq 'none') {
                   8618: 	{
1.223     foxr     8619: 	    my $pf = IO::File->new("> $passfilename");
1.261     foxr     8620: 	    if($pf) {
                   8621: 		print $pf "none:\n";
                   8622: 	    } else {
                   8623: 		$result = "pass_file_failed_error";
                   8624: 	    }
1.91      albertel 8625: 	}
1.543     raeburn  8626:     } elsif ($umode eq 'lti') {
                   8627:         my $pf = IO::File->new(">$passfilename");
                   8628:         if($pf) {
                   8629:             print $pf "lti:\n";
                   8630:             &update_passwd_history($uname,$udom,$umode,$action);
                   8631:         } else {
                   8632:             $result = "pass_file_failed_error";
                   8633:         }
1.91      albertel 8634:     } else {
1.390     raeburn  8635: 	$result="auth_mode_error";
1.91      albertel 8636:     }
                   8637:     return $result;
1.121     albertel 8638: }
                   8639: 
1.265     albertel 8640: sub convert_photo {
                   8641:     my ($start,$dest)=@_;
                   8642:     system("convert $start $dest");
                   8643: }
                   8644: 
1.121     albertel 8645: sub sethost {
                   8646:     my ($remotereq) = @_;
                   8647:     my (undef,$hostid)=split(/:/,$remotereq);
1.322     albertel 8648:     # ignore sethost if we are already correct
                   8649:     if ($hostid eq $currenthostid) {
                   8650: 	return 'ok';
                   8651:     }
                   8652: 
1.121     albertel 8653:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
1.368     albertel 8654:     if (&Apache::lonnet::get_host_ip($perlvar{'lonHostID'}) 
                   8655: 	eq &Apache::lonnet::get_host_ip($hostid)) {
1.200     matthew  8656: 	$currenthostid  =$hostid;
1.369     albertel 8657: 	$currentdomainid=&Apache::lonnet::host_domain($hostid);
1.556     raeburn  8658:         &set_client_info();
1.443     www      8659: #	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
1.121     albertel 8660:     } else {
                   8661: 	&logthis("Requested host id $hostid not an alias of ".
                   8662: 		 $perlvar{'lonHostID'}." refusing connection");
                   8663: 	return 'unable_to_set';
                   8664:     }
                   8665:     return 'ok';
                   8666: }
                   8667: 
                   8668: sub version {
                   8669:     my ($userinput)=@_;
                   8670:     $remoteVERSION=(split(/:/,$userinput))[1];
                   8671:     return "version:$VERSION";
1.127     albertel 8672: }
1.178     foxr     8673: 
1.447     raeburn  8674: sub get_usersession_config {
                   8675:     my ($dom,$name) = @_;
                   8676:     my ($usersessionconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8677:     if (defined($cached)) {
                   8678:         return $usersessionconf;
                   8679:     } else {
                   8680:         my %domconfig = &Apache::lonnet::get_dom('configuration',['usersessions'],$dom);
1.525     raeburn  8681:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'usersessions'},3600);
                   8682:         return $domconfig{'usersessions'};
1.447     raeburn  8683:     }
                   8684:     return;
                   8685: }
1.200     matthew  8686: 
1.534     raeburn  8687: sub get_usersearch_config {
                   8688:     my ($dom,$name) = @_;
                   8689:     my ($usersearchconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8690:     if (defined($cached)) {
                   8691:         return $usersearchconf;
                   8692:     } else {
                   8693:         my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$dom);
                   8694:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'directorysrch'},600);
                   8695:         return $domconfig{'directorysrch'};
                   8696:     }
                   8697:     return;
                   8698: }
                   8699: 
1.525     raeburn  8700: sub get_prohibited {
                   8701:     my ($dom) = @_;
                   8702:     my $name = 'trust';
                   8703:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8704:     unless (defined($cached)) {
                   8705:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$dom);
                   8706:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'trust'},3600);
                   8707:         $trustconfig = $domconfig{'trust'};
                   8708:     }
                   8709:     my %prohibited;
                   8710:     if (ref($trustconfig)) {
                   8711:         foreach my $prefix (keys(%{$trustconfig})) {
                   8712:             if (ref($trustconfig->{$prefix}) eq 'HASH') {
                   8713:                 my $reject;
                   8714:                 if (ref($trustconfig->{$prefix}->{'exc'}) eq 'ARRAY') {
                   8715:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'exc'}})) {
                   8716:                         $reject = 1;
                   8717:                     }
                   8718:                 }
                   8719:                 if (ref($trustconfig->{$prefix}->{'inc'}) eq 'ARRAY') {
                   8720:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'inc'}})) {
                   8721:                         $reject = 0;
                   8722:                     } else {
                   8723:                         $reject = 1;
                   8724:                     }
                   8725:                 }
                   8726:                 if ($reject) {
                   8727:                     $prohibited{$prefix} = 1;
                   8728:                 }
                   8729:             }
                   8730:         }
                   8731:     }
                   8732:     return %prohibited;
                   8733: }
1.450     raeburn  8734: 
1.556     raeburn  8735: sub get_remote_hostable {
                   8736:     my ($dom) = @_;
                   8737:     my $result;
                   8738:     if ($clientintdom) {
                   8739:         $result = 1;
                   8740:         my $remsessconf = &get_usersession_config($dom,'remotesession');
                   8741:         if (ref($remsessconf) eq 'HASH') {
                   8742:             if (ref($remsessconf->{'remote'}) eq 'HASH') {
                   8743:                 if (ref($remsessconf->{'remote'}->{'excludedomain'}) eq 'ARRAY') {
                   8744:                     if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'excludedomain'}})) {
                   8745:                         $result = 0;
                   8746:                     }
                   8747:                 }
                   8748:                 if (ref($remsessconf->{'remote'}->{'includedomain'}) eq 'ARRAY') {
                   8749:                     if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'includedomain'}})) {
                   8750:                         $result = 1;
                   8751:                     } else {
                   8752:                         $result = 0;
                   8753:                     }
                   8754:                 }
                   8755:             }
                   8756:         }
                   8757:     }
                   8758:     return $result;
                   8759: }
                   8760: 
1.471     raeburn  8761: sub distro_and_arch {
                   8762:     return $dist.':'.$arch;
                   8763: }
                   8764: 
1.61      harris41 8765: # ----------------------------------- POD (plain old documentation, CPAN style)
                   8766: 
                   8767: =head1 NAME
                   8768: 
                   8769: lond - "LON Daemon" Server (port "LOND" 5663)
                   8770: 
                   8771: =head1 SYNOPSIS
                   8772: 
1.74      harris41 8773: Usage: B<lond>
                   8774: 
                   8775: Should only be run as user=www.  This is a command-line script which
                   8776: is invoked by B<loncron>.  There is no expectation that a typical user
                   8777: will manually start B<lond> from the command-line.  (In other words,
                   8778: DO NOT START B<lond> YOURSELF.)
1.61      harris41 8779: 
                   8780: =head1 DESCRIPTION
                   8781: 
1.74      harris41 8782: There are two characteristics associated with the running of B<lond>,
                   8783: PROCESS MANAGEMENT (starting, stopping, handling child processes)
                   8784: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
                   8785: subscriptions, etc).  These are described in two large
                   8786: sections below.
                   8787: 
                   8788: B<PROCESS MANAGEMENT>
                   8789: 
1.61      harris41 8790: Preforker - server who forks first. Runs as a daemon. HUPs.
                   8791: Uses IDEA encryption
                   8792: 
1.74      harris41 8793: B<lond> forks off children processes that correspond to the other servers
                   8794: in the network.  Management of these processes can be done at the
                   8795: parent process level or the child process level.
                   8796: 
                   8797: B<logs/lond.log> is the location of log messages.
                   8798: 
                   8799: The process management is now explained in terms of linux shell commands,
                   8800: subroutines internal to this code, and signal assignments:
                   8801: 
                   8802: =over 4
                   8803: 
                   8804: =item *
                   8805: 
                   8806: PID is stored in B<logs/lond.pid>
                   8807: 
                   8808: This is the process id number of the parent B<lond> process.
                   8809: 
                   8810: =item *
                   8811: 
                   8812: SIGTERM and SIGINT
                   8813: 
                   8814: Parent signal assignment:
                   8815:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   8816: 
                   8817: Child signal assignment:
                   8818:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
                   8819: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
                   8820:  to restart a new child.)
                   8821: 
                   8822: Command-line invocations:
                   8823:  B<kill> B<-s> SIGTERM I<PID>
                   8824:  B<kill> B<-s> SIGINT I<PID>
                   8825: 
                   8826: Subroutine B<HUNTSMAN>:
                   8827:  This is only invoked for the B<lond> parent I<PID>.
                   8828: This kills all the children, and then the parent.
                   8829: The B<lonc.pid> file is cleared.
                   8830: 
                   8831: =item *
                   8832: 
                   8833: SIGHUP
                   8834: 
                   8835: Current bug:
                   8836:  This signal can only be processed the first time
                   8837: on the parent process.  Subsequent SIGHUP signals
                   8838: have no effect.
                   8839: 
                   8840: Parent signal assignment:
                   8841:  $SIG{HUP}  = \&HUPSMAN;
                   8842: 
                   8843: Child signal assignment:
                   8844:  none (nothing happens)
                   8845: 
                   8846: Command-line invocations:
                   8847:  B<kill> B<-s> SIGHUP I<PID>
                   8848: 
                   8849: Subroutine B<HUPSMAN>:
                   8850:  This is only invoked for the B<lond> parent I<PID>,
                   8851: This kills all the children, and then the parent.
                   8852: The B<lond.pid> file is cleared.
                   8853: 
                   8854: =item *
                   8855: 
                   8856: SIGUSR1
                   8857: 
                   8858: Parent signal assignment:
                   8859:  $SIG{USR1} = \&USRMAN;
                   8860: 
                   8861: Child signal assignment:
                   8862:  $SIG{USR1}= \&logstatus;
                   8863: 
                   8864: Command-line invocations:
                   8865:  B<kill> B<-s> SIGUSR1 I<PID>
                   8866: 
                   8867: Subroutine B<USRMAN>:
                   8868:  When invoked for the B<lond> parent I<PID>,
                   8869: SIGUSR1 is sent to all the children, and the status of
                   8870: each connection is logged.
1.144     foxr     8871: 
                   8872: =item *
                   8873: 
                   8874: SIGUSR2
                   8875: 
                   8876: Parent Signal assignment:
                   8877:     $SIG{USR2} = \&UpdateHosts
                   8878: 
                   8879: Child signal assignment:
                   8880:     NONE
                   8881: 
1.74      harris41 8882: 
                   8883: =item *
                   8884: 
                   8885: SIGCHLD
                   8886: 
                   8887: Parent signal assignment:
                   8888:  $SIG{CHLD} = \&REAPER;
                   8889: 
                   8890: Child signal assignment:
                   8891:  none
                   8892: 
                   8893: Command-line invocations:
                   8894:  B<kill> B<-s> SIGCHLD I<PID>
                   8895: 
                   8896: Subroutine B<REAPER>:
                   8897:  This is only invoked for the B<lond> parent I<PID>.
                   8898: Information pertaining to the child is removed.
                   8899: The socket port is cleaned up.
                   8900: 
                   8901: =back
                   8902: 
                   8903: B<SERVER-SIDE ACTIVITIES>
                   8904: 
                   8905: Server-side information can be accepted in an encrypted or non-encrypted
                   8906: method.
                   8907: 
                   8908: =over 4
                   8909: 
                   8910: =item ping
                   8911: 
                   8912: Query a client in the hosts.tab table; "Are you there?"
                   8913: 
                   8914: =item pong
                   8915: 
                   8916: Respond to a ping query.
                   8917: 
                   8918: =item ekey
                   8919: 
                   8920: Read in encrypted key, make cipher.  Respond with a buildkey.
                   8921: 
                   8922: =item load
                   8923: 
                   8924: Respond with CPU load based on a computation upon /proc/loadavg.
                   8925: 
                   8926: =item currentauth
                   8927: 
                   8928: Reply with current authentication information (only over an
                   8929: encrypted channel).
                   8930: 
                   8931: =item auth
                   8932: 
                   8933: Only over an encrypted channel, reply as to whether a user's
                   8934: authentication information can be validated.
                   8935: 
                   8936: =item passwd
                   8937: 
                   8938: Allow for a password to be set.
                   8939: 
                   8940: =item makeuser
                   8941: 
                   8942: Make a user.
                   8943: 
1.517     raeburn  8944: =item changeuserauth
1.74      harris41 8945: 
                   8946: Allow for authentication mechanism and password to be changed.
                   8947: 
                   8948: =item home
1.61      harris41 8949: 
1.74      harris41 8950: Respond to a question "are you the home for a given user?"
                   8951: 
                   8952: =item update
                   8953: 
                   8954: Update contents of a subscribed resource.
                   8955: 
                   8956: =item unsubscribe
                   8957: 
                   8958: The server is unsubscribing from a resource.
                   8959: 
                   8960: =item subscribe
                   8961: 
                   8962: The server is subscribing to a resource.
                   8963: 
                   8964: =item log
                   8965: 
                   8966: Place in B<logs/lond.log>
                   8967: 
                   8968: =item put
                   8969: 
                   8970: stores hash in namespace
                   8971: 
1.496     raeburn  8972: =item rolesput
1.74      harris41 8973: 
                   8974: put a role into a user's environment
                   8975: 
                   8976: =item get
                   8977: 
                   8978: returns hash with keys from array
                   8979: reference filled in from namespace
                   8980: 
                   8981: =item eget
                   8982: 
                   8983: returns hash with keys from array
                   8984: reference filled in from namesp (encrypts the return communication)
                   8985: 
                   8986: =item rolesget
                   8987: 
                   8988: get a role from a user's environment
                   8989: 
                   8990: =item del
                   8991: 
                   8992: deletes keys out of array from namespace
                   8993: 
                   8994: =item keys
                   8995: 
                   8996: returns namespace keys
                   8997: 
                   8998: =item dump
                   8999: 
                   9000: dumps the complete (or key matching regexp) namespace into a hash
                   9001: 
                   9002: =item store
                   9003: 
                   9004: stores hash permanently
                   9005: for this url; hashref needs to be given and should be a \%hashname; the
                   9006: remaining args aren't required and if they aren't passed or are '' they will
                   9007: be derived from the ENV
                   9008: 
                   9009: =item restore
                   9010: 
                   9011: returns a hash for a given url
                   9012: 
                   9013: =item querysend
                   9014: 
                   9015: Tells client about the lonsql process that has been launched in response
                   9016: to a sent query.
                   9017: 
                   9018: =item queryreply
                   9019: 
                   9020: Accept information from lonsql and make appropriate storage in temporary
                   9021: file space.
                   9022: 
                   9023: =item idput
                   9024: 
                   9025: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
                   9026: for each student, defined perhaps by the institutional Registrar.)
                   9027: 
                   9028: =item idget
                   9029: 
                   9030: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
                   9031: for each student, defined perhaps by the institutional Registrar.)
                   9032: 
1.517     raeburn  9033: =item iddel
                   9034: 
                   9035: Deletes one or more ids in a domain's id database.
                   9036: 
1.74      harris41 9037: =item tmpput
                   9038: 
                   9039: Accept and store information in temporary space.
                   9040: 
                   9041: =item tmpget
                   9042: 
                   9043: Send along temporarily stored information.
                   9044: 
                   9045: =item ls
                   9046: 
                   9047: List part of a user's directory.
                   9048: 
1.135     foxr     9049: =item pushtable
                   9050: 
                   9051: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
                   9052: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
                   9053: must be restored manually in case of a problem with the new table file.
                   9054: pushtable requires that the request be encrypted and validated via
                   9055: ValidateManager.  The form of the command is:
                   9056: enc:pushtable tablename <tablecontents> \n
                   9057: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
                   9058: cleartext newline.
                   9059: 
1.74      harris41 9060: =item Hanging up (exit or init)
                   9061: 
                   9062: What to do when a client tells the server that they (the client)
                   9063: are leaving the network.
                   9064: 
                   9065: =item unknown command
                   9066: 
                   9067: If B<lond> is sent an unknown command (not in the list above),
                   9068: it replys to the client "unknown_cmd".
1.135     foxr     9069: 
1.74      harris41 9070: 
                   9071: =item UNKNOWN CLIENT
                   9072: 
                   9073: If the anti-spoofing algorithm cannot verify the client,
                   9074: the client is rejected (with a "refused" message sent
                   9075: to the client, and the connection is closed.
                   9076: 
                   9077: =back
1.61      harris41 9078: 
                   9079: =head1 PREREQUISITES
                   9080: 
                   9081: IO::Socket
                   9082: IO::File
                   9083: Apache::File
                   9084: POSIX
                   9085: Crypt::IDEA
                   9086: GDBM_File
                   9087: Authen::Krb4
1.91      albertel 9088: Authen::Krb5
1.61      harris41 9089: 
                   9090: =head1 COREQUISITES
                   9091: 
1.490     droeschl 9092: none
                   9093: 
1.61      harris41 9094: =head1 OSNAMES
                   9095: 
                   9096: linux
                   9097: 
                   9098: =head1 SCRIPT CATEGORIES
                   9099: 
                   9100: Server/Process
                   9101: 
                   9102: =cut
1.409     foxr     9103: 
                   9104: 
                   9105: =pod
                   9106: 
                   9107: =head1 LOG MESSAGES
                   9108: 
                   9109: The messages below can be emitted in the lond log.  This log is located
                   9110: in ~httpd/perl/logs/lond.log  Many log messages have HTML encapsulation
                   9111: to provide coloring if examined from inside a web page. Some do not.
                   9112: Where color is used, the colors are; Red for sometihhng to get excited
                   9113: about and to follow up on. Yellow for something to keep an eye on to
                   9114: be sure it does not get worse, Green,and Blue for informational items.
                   9115: 
                   9116: In the discussions below, sometimes reference is made to ~httpd
                   9117: when describing file locations.  There isn't really an httpd 
                   9118: user, however there is an httpd directory that gets installed in the
                   9119: place that user home directories go.  On linux, this is usually
                   9120: (always?) /home/httpd.
                   9121: 
                   9122: 
                   9123: Some messages are colorless.  These are usually (not always)
                   9124: Green/Blue color level messages.
                   9125: 
                   9126: =over 2
                   9127: 
                   9128: =item (Red)  LocalConnection rejecting non local: <ip> ne 127.0.0.1
                   9129: 
                   9130: A local connection negotiation was attempted by
                   9131: a host whose IP address was not 127.0.0.1.
                   9132: The socket is closed and the child will exit.
                   9133: lond has three ways to establish an encyrption
                   9134: key with a client:
                   9135: 
                   9136: =over 2
                   9137: 
                   9138: =item local 
                   9139: 
                   9140: The key is written and read from a file.
                   9141: This is only valid for connections from localhost.
                   9142: 
                   9143: =item insecure 
                   9144: 
                   9145: The key is generated by the server and
                   9146: transmitted to the client.
                   9147: 
                   9148: =item  ssl (secure)
                   9149: 
                   9150: An ssl connection is negotiated with the client,
                   9151: the key is generated by the server and sent to the 
                   9152: client across this ssl connection before the
                   9153: ssl connectionis terminated and clear text
                   9154: transmission resumes.
                   9155: 
                   9156: =back
                   9157: 
                   9158: =item (Red) LocalConnection: caller is insane! init = <init> and type = <type>
                   9159: 
                   9160: The client is local but has not sent an initialization
                   9161: string that is the literal "init:local"  The connection
                   9162: is closed and the child exits.
                   9163: 
                   9164: =item Red CRITICAL Can't get key file <error>        
                   9165: 
                   9166: SSL key negotiation is being attempted but the call to
1.549     raeburn  9167: lonssl::KeyFile failed.  This usually means that the
1.409     foxr     9168: configuration file is not correctly defining or protecting
                   9169: the directories/files lonCertificateDirectory or
                   9170: lonnetPrivateKey
                   9171: <error> is a string that describes the reason that
                   9172: the key file could not be located.
                   9173: 
                   9174: =item (Red) CRITICAL  Can't get certificates <error>  
                   9175: 
                   9176: SSL key negotiation failed because we were not able to retrives our certificate
                   9177: or the CA's certificate in the call to lonssl::CertificateFile
                   9178: <error> is the textual reason this failed.  Usual reasons:
                   9179: 
                   9180: =over 2
1.490     droeschl 9181: 
1.409     foxr     9182: =item Apache config file for loncapa  incorrect:
1.490     droeschl 9183: 
1.409     foxr     9184: one of the variables 
                   9185: lonCertificateDirectory, lonnetCertificateAuthority, or lonnetCertificate
                   9186: undefined or incorrect
                   9187: 
                   9188: =item Permission error:
                   9189: 
                   9190: The directory pointed to by lonCertificateDirectory is not readable by lond
                   9191: 
                   9192: =item Permission error:
                   9193: 
                   9194: Files in the directory pointed to by lonCertificateDirectory are not readable by lond.
                   9195: 
                   9196: =item Installation error:                         
                   9197: 
                   9198: Either the certificate authority file or the certificate have not
                   9199: been installed in lonCertificateDirectory.
                   9200: 
                   9201: =item (Red) CRITICAL SSL Socket promotion failed:  <err> 
                   9202: 
                   9203: The promotion of the connection from plaintext to SSL failed
                   9204: <err> is the reason for the failure.  There are two
                   9205: system calls involved in the promotion (one of which failed), 
                   9206: a dup to produce
                   9207: a second fd on the raw socket over which the encrypted data
                   9208: will flow and IO::SOcket::SSL->new_from_fd which creates
                   9209: the SSL connection on the duped fd.
                   9210: 
                   9211: =item (Blue)   WARNING client did not respond to challenge 
                   9212: 
                   9213: This occurs on an insecure (non SSL) connection negotiation request.
                   9214: lond generates some number from the time, the PID and sends it to
                   9215: the client.  The client must respond by echoing this information back.
                   9216: If the client does not do so, that's a violation of the challenge
                   9217: protocols and the connection will be failed.
                   9218: 
                   9219: =item (Red) No manager table. Nobody can manage!!    
                   9220: 
                   9221: lond has the concept of privileged hosts that
                   9222: can perform remote management function such
                   9223: as update the hosts.tab.   The manager hosts
                   9224: are described in the 
                   9225: ~httpd/lonTabs/managers.tab file.
                   9226: this message is logged if this file is missing.
                   9227: 
                   9228: 
                   9229: =item (Green) Registering manager <dnsname> as <cluster_name> with <ipaddress>
                   9230: 
                   9231: Reports the successful parse and registration
                   9232: of a specific manager. 
                   9233: 
                   9234: =item Green existing host <clustername:dnsname>  
                   9235: 
                   9236: The manager host is already defined in the hosts.tab
                   9237: the information in that table, rather than the info in the
                   9238: manager table will be used to determine the manager's ip.
                   9239: 
                   9240: =item (Red) Unable to craete <filename>                 
                   9241: 
                   9242: lond has been asked to create new versions of an administrative
                   9243: file (by a manager).  When this is done, the new file is created
                   9244: in a temp file and then renamed into place so that there are always
                   9245: usable administrative files, even if the update fails.  This failure
                   9246: message means that the temp file could not be created.
                   9247: The update is abandoned, and the old file is available for use.
                   9248: 
                   9249: =item (Green) CopyFile from <oldname> to <newname> failed
                   9250: 
                   9251: In an update of administrative files, the copy of the existing file to a
                   9252: backup file failed.  The installation of the new file may still succeed,
                   9253: but there will not be a back up file to rever to (this should probably
                   9254: be yellow).
                   9255: 
                   9256: =item (Green) Pushfile: backed up <oldname> to <newname>
                   9257: 
                   9258: See above, the backup of the old administrative file succeeded.
                   9259: 
                   9260: =item (Red)  Pushfile: Unable to install <filename> <reason>
                   9261: 
                   9262: The new administrative file could not be installed.  In this case,
                   9263: the old administrative file is still in use.
                   9264: 
                   9265: =item (Green) Installed new < filename>.                      
                   9266: 
                   9267: The new administrative file was successfullly installed.                                               
                   9268: 
                   9269: =item (Red) Reinitializing lond pid=<pid>                    
                   9270: 
                   9271: The lonc child process <pid> will be sent a USR2 
                   9272: signal.
                   9273: 
                   9274: =item (Red) Reinitializing self                                    
                   9275: 
                   9276: We've been asked to re-read our administrative files,and
                   9277: are doing so.
                   9278: 
                   9279: =item (Yellow) error:Invalid process identifier <ident>  
                   9280: 
                   9281: A reinit command was received, but the target part of the 
                   9282: command was not valid.  It must be either
                   9283: 'lond' or 'lonc' but was <ident>
                   9284: 
                   9285: =item (Green) isValideditCommand checking: Command = <command> Key = <key> newline = <newline>
                   9286: 
                   9287: Checking to see if lond has been handed a valid edit
                   9288: command.  It is possible the edit command is not valid
                   9289: in that case there are no log messages to indicate that.
                   9290: 
                   9291: =item Result of password change for  <username> pwchange_success
                   9292: 
                   9293: The password for <username> was
                   9294: successfully changed.
                   9295: 
                   9296: =item Unable to open <user> passwd to change password
                   9297: 
                   9298: Could not rewrite the 
                   9299: internal password file for a user
                   9300: 
                   9301: =item Result of password change for <user> : <result>
1.490     droeschl 9302: 
1.409     foxr     9303: A unix password change for <user> was attempted 
                   9304: and the pipe returned <result>  
                   9305: 
                   9306: =item LWP GET: <message> for <fname> (<remoteurl>)
                   9307: 
                   9308: The lightweight process fetch for a resource failed
                   9309: with <message> the local filename that should
                   9310: have existed/been created was  <fname> the
                   9311: corresponding URI: <remoteurl>  This is emitted in several
                   9312: places.
                   9313: 
                   9314: =item Unable to move <transname> to <destname>     
                   9315: 
                   9316: From fetch_user_file_handler - the user file was replicated but could not
                   9317: be mv'd to its final location.
                   9318: 
                   9319: =item Looking for <domain> <username>              
                   9320: 
                   9321: From user_has_session_handler - This should be a Debug call instead
                   9322: it indicates lond is about to check whether the specified user has a 
                   9323: session active on the specified domain on the local host.
                   9324: 
                   9325: =item Client <ip> (<name>) hanging up: <input>     
                   9326: 
                   9327: lond has been asked to exit by its client.  The <ip> and <name> identify the
                   9328: client systemand <input> is the full exit command sent to the server.
                   9329: 
                   9330: =item Red CRITICAL: ABNORMAL EXIT. child <pid> for server <hostname> died through a crass with this error->[<message>].
1.490     droeschl 9331: 
1.409     foxr     9332: A lond child terminated.  NOte that this termination can also occur when the
                   9333: child receives the QUIT or DIE signals.  <pid> is the process id of the child,
                   9334: <hostname> the host lond is working for, and <message> the reason the child died
                   9335: to the best of our ability to get it (I would guess that any numeric value
                   9336: represents and errno value).  This is immediately followed by
                   9337: 
                   9338: =item  Famous last words: Catching exception - <log> 
                   9339: 
                   9340: Where log is some recent information about the state of the child.
                   9341: 
                   9342: =item Red CRITICAL: TIME OUT <pid>                     
                   9343: 
                   9344: Some timeout occured for server <pid>.  THis is normally a timeout on an LWP
                   9345: doing an HTTP::GET.
                   9346: 
                   9347: =item child <pid> died                              
                   9348: 
                   9349: The reaper caught a SIGCHILD for the lond child process <pid>
                   9350: This should be modified to also display the IP of the dying child
                   9351: $children{$pid}
                   9352: 
                   9353: =item Unknown child 0 died                           
                   9354: A child died but the wait for it returned a pid of zero which really should not
                   9355: ever happen. 
                   9356: 
                   9357: =item Child <which> - <pid> looks like we missed it's death 
                   9358: 
                   9359: When a sigchild is received, the reaper process checks all children to see if they are
                   9360: alive.  If children are dying quite quickly, the lack of signal queuing can mean
                   9361: that a signal hearalds the death of more than one child.  If so this message indicates
                   9362: which other one died. <which> is the ip of a dead child
                   9363: 
                   9364: =item Free socket: <shutdownretval>                
                   9365: 
                   9366: The HUNTSMAN sub was called due to a SIGINT in a child process.  The socket is being shutdown.
                   9367: for whatever reason, <shutdownretval> is printed but in fact shutdown() is not documented
                   9368: to return anything. This is followed by: 
                   9369: 
                   9370: =item Red CRITICAL: Shutting down                       
                   9371: 
                   9372: Just prior to exit.
                   9373: 
                   9374: =item Free socket: <shutdownretval>                 
                   9375: 
                   9376: The HUPSMAN sub was called due to a SIGHUP.  all children get killsed, and lond execs itself.
                   9377: This is followed by:
                   9378: 
                   9379: =item (Red) CRITICAL: Restarting                         
                   9380: 
                   9381: lond is about to exec itself to restart.
                   9382: 
                   9383: =item (Blue) Updating connections                        
                   9384: 
                   9385: (In response to a USR2).  All the children (except the one for localhost)
                   9386: are about to be killed, the hosts tab reread, and Apache reloaded via apachereload.
                   9387: 
                   9388: =item (Blue) UpdateHosts killing child <pid> for ip <ip>   
                   9389: 
                   9390: Due to USR2 as above.
                   9391: 
                   9392: =item (Green) keeping child for ip <ip> (pid = <pid>)    
                   9393: 
                   9394: In response to USR2 as above, the child indicated is not being restarted because
                   9395: it's assumed that we'll always need a child for the localhost.
                   9396: 
                   9397: 
                   9398: =item Going to check on the children                
                   9399: 
                   9400: Parent is about to check on the health of the child processes.
                   9401: Note that this is in response to a USR1 sent to the parent lond.
                   9402: there may be one or more of the next two messages:
                   9403: 
                   9404: =item <pid> is dead                                 
                   9405: 
                   9406: A child that we have in our child hash as alive has evidently died.
                   9407: 
                   9408: =item  Child <pid> did not respond                   
                   9409: 
                   9410: In the health check the child <pid> did not update/produce a pid_.txt
                   9411: file when sent it's USR1 signal.  That process is killed with a 9 signal, as it's
                   9412: assumed to be hung in some un-fixable way.
                   9413: 
                   9414: =item Finished checking children                   
1.490     droeschl 9415: 
1.409     foxr     9416: Master processs's USR1 processing is cojmplete.
                   9417: 
                   9418: =item (Red) CRITICAL: ------- Starting ------            
                   9419: 
                   9420: (There are more '-'s on either side).  Lond has forked itself off to 
                   9421: form a new session and is about to start actual initialization.
                   9422: 
                   9423: =item (Green) Attempting to start child (<client>)       
                   9424: 
                   9425: Started a new child process for <client>.  Client is IO::Socket object
                   9426: connected to the child.  This was as a result of a TCP/IP connection from a client.
                   9427: 
                   9428: =item Unable to determine who caller was, getpeername returned nothing
1.490     droeschl 9429: 
1.409     foxr     9430: In child process initialization.  either getpeername returned undef or
                   9431: a zero sized object was returned.  Processing continues, but in my opinion,
                   9432: this should be cause for the child to exit.
                   9433: 
                   9434: =item Unable to determine clientip                  
                   9435: 
                   9436: In child process initialization.  The peer address from getpeername was not defined.
                   9437: The client address is stored as "Unavailable" and processing continues.
                   9438: 
                   9439: =item (Yellow) INFO: Connection <ip> <name> connection type = <type>
1.490     droeschl 9440: 
1.409     foxr     9441: In child initialization.  A good connectionw as received from <ip>.
                   9442: 
                   9443: =over 2
                   9444: 
                   9445: =item <name> 
                   9446: 
                   9447: is the name of the client from hosts.tab.
                   9448: 
                   9449: =item <type> 
                   9450: 
                   9451: Is the connection type which is either 
                   9452: 
                   9453: =over 2
                   9454: 
                   9455: =item manager 
                   9456: 
                   9457: The connection is from a manager node, not in hosts.tab
                   9458: 
                   9459: =item client  
                   9460: 
                   9461: the connection is from a non-manager in the hosts.tab
                   9462: 
                   9463: =item both
                   9464: 
                   9465: The connection is from a manager in the hosts.tab.
                   9466: 
                   9467: =back
                   9468: 
                   9469: =back
                   9470: 
                   9471: =item (Blue) Certificates not installed -- trying insecure auth
                   9472: 
                   9473: One of the certificate file, key file or
                   9474: certificate authority file could not be found for a client attempting
                   9475: SSL connection intiation.  COnnection will be attemptied in in-secure mode.
                   9476: (this would be a system with an up to date lond that has not gotten a 
                   9477: certificate from us).
                   9478: 
                   9479: =item (Green)  Successful local authentication            
                   9480: 
                   9481: A local connection successfully negotiated the encryption key. 
                   9482: In this case the IDEA key is in a file (that is hopefully well protected).
                   9483: 
                   9484: =item (Green) Successful ssl authentication with <client>  
                   9485: 
                   9486: The client (<client> is the peer's name in hosts.tab), has successfully
                   9487: negotiated an SSL connection with this child process.
                   9488: 
                   9489: =item (Green) Successful insecure authentication with <client>
1.490     droeschl 9490: 
1.409     foxr     9491: 
                   9492: The client has successfully negotiated an  insecure connection withthe child process.
                   9493: 
                   9494: =item (Yellow) Attempted insecure connection disallowed    
                   9495: 
                   9496: The client attempted and failed to successfully negotiate a successful insecure
                   9497: connection.  This can happen either because the variable londAllowInsecure is false
                   9498: or undefined, or becuse the child did not successfully echo back the challenge
                   9499: string.
                   9500: 
                   9501: 
                   9502: =back
                   9503: 
1.441     raeburn  9504: =back
                   9505: 
1.409     foxr     9506: 
                   9507: =cut

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