Annotation of loncom/lond, revision 1.564

1.1       albertel    1: #!/usr/bin/perl
                      2: # The LearningOnline Network
                      3: # lond "LON Daemon" Server (port "LOND" 5663)
1.60      www         4: #
1.564   ! raeburn     5: # $Id: lond,v 1.563 2020/05/05 20:24:41 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.564   ! raeburn    68: my $VERSION='$Revision: 1.563 $'; #' 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},
1.564   ! raeburn   313:                updatebalcookie => {institutiononly => 1},
1.525     raeburn   314:                updateclickers => {remote => 1},
                    315:                userhassession => {anywhere => 1},
                    316:                userload => {anywhere => 1},
                    317:                version => {anywhere => 1}, #not used
                    318:             );
                    319: 
                    320: #
1.207     foxr      321: #   Statistics that are maintained and dislayed in the status line.
                    322: #
1.212     foxr      323: my $Transactions = 0;		# Number of attempted transactions.
                    324: my $Failures     = 0;		# Number of transcations failed.
1.207     foxr      325: 
                    326: #   ResetStatistics: 
                    327: #      Resets the statistics counters:
                    328: #
                    329: sub ResetStatistics {
                    330:     $Transactions = 0;
                    331:     $Failures     = 0;
                    332: }
                    333: 
1.200     matthew   334: #------------------------------------------------------------------------
                    335: #
                    336: #   LocalConnection
                    337: #     Completes the formation of a locally authenticated connection.
                    338: #     This function will ensure that the 'remote' client is really the
                    339: #     local host.  If not, the connection is closed, and the function fails.
                    340: #     If so, initcmd is parsed for the name of a file containing the
                    341: #     IDEA session key.  The fie is opened, read, deleted and the session
                    342: #     key returned to the caller.
                    343: #
                    344: # Parameters:
                    345: #   $Socket      - Socket open on client.
                    346: #   $initcmd     - The full text of the init command.
                    347: #
                    348: # Returns:
                    349: #     IDEA session key on success.
                    350: #     undef on failure.
                    351: #
                    352: sub LocalConnection {
                    353:     my ($Socket, $initcmd) = @_;
1.373     albertel  354:     Debug("Attempting local connection: $initcmd client: $clientip");
1.277     albertel  355:     if($clientip ne "127.0.0.1") {
1.200     matthew   356: 	&logthis('<font color="red"> LocalConnection rejecting non local: '
1.373     albertel  357: 		 ."$clientip ne 127.0.0.1 </font>");
1.200     matthew   358: 	close $Socket;
                    359: 	return undef;
1.224     foxr      360:     }  else {
1.200     matthew   361: 	chomp($initcmd);	# Get rid of \n in filename.
                    362: 	my ($init, $type, $name) = split(/:/, $initcmd);
                    363: 	Debug(" Init command: $init $type $name ");
                    364: 
                    365: 	# Require that $init = init, and $type = local:  Otherwise
                    366: 	# the caller is insane:
                    367: 
                    368: 	if(($init ne "init") && ($type ne "local")) {
                    369: 	    &logthis('<font color = "red"> LocalConnection: caller is insane! '
                    370: 		     ."init = $init, and type = $type </font>");
                    371: 	    close($Socket);;
                    372: 	    return undef;
                    373: 		
                    374: 	}
                    375: 	#  Now get the key filename:
                    376: 
                    377: 	my $IDEAKey = lonlocal::ReadKeyFile($name);
                    378: 	return $IDEAKey;
                    379:     }
                    380: }
                    381: #------------------------------------------------------------------------------
                    382: #
                    383: #  SSLConnection
                    384: #   Completes the formation of an ssh authenticated connection. The
                    385: #   socket is promoted to an ssl socket.  If this promotion and the associated
                    386: #   certificate exchange are successful, the IDEA key is generated and sent
                    387: #   to the remote peer via the SSL tunnel. The IDEA key is also returned to
                    388: #   the caller after the SSL tunnel is torn down.
                    389: #
                    390: # Parameters:
                    391: #   Name              Type             Purpose
                    392: #   $Socket          IO::Socket::INET  Plaintext socket.
                    393: #
                    394: # Returns:
                    395: #    IDEA key on success.
                    396: #    undef on failure.
                    397: #
                    398: sub SSLConnection {
                    399:     my $Socket   = shift;
                    400: 
                    401:     Debug("SSLConnection: ");
                    402:     my $KeyFile         = lonssl::KeyFile();
                    403:     if(!$KeyFile) {
                    404: 	my $err = lonssl::LastError();
                    405: 	&logthis("<font color=\"red\"> CRITICAL"
                    406: 		 ."Can't get key file $err </font>");
                    407: 	return undef;
                    408:     }
                    409:     my ($CACertificate,
                    410: 	$Certificate) = lonssl::CertificateFile();
                    411: 
                    412: 
                    413:     # If any of the key, certificate or certificate authority 
                    414:     # certificate filenames are not defined, this can't work.
                    415: 
                    416:     if((!$Certificate) || (!$CACertificate)) {
                    417: 	my $err = lonssl::LastError();
                    418: 	&logthis("<font color=\"red\"> CRITICAL"
                    419: 		 ."Can't get certificates: $err </font>");
                    420: 
                    421: 	return undef;
                    422:     }
                    423:     Debug("Key: $KeyFile CA: $CACertificate Cert: $Certificate");
                    424: 
                    425:     # Indicate to our peer that we can procede with
                    426:     # a transition to ssl authentication:
                    427: 
                    428:     print $Socket "ok:ssl\n";
                    429: 
                    430:     Debug("Approving promotion -> ssl");
                    431:     #  And do so:
                    432: 
1.545     raeburn   433:     my $CRLFile;
                    434:     unless ($crlchecked{$clientname}) {
                    435:         $CRLFile = lonssl::CRLFile();
                    436:         $crlchecked{$clientname} = 1;
                    437:     }
                    438: 
1.200     matthew   439:     my $SSLSocket = lonssl::PromoteServerSocket($Socket,
                    440: 						$CACertificate,
                    441: 						$Certificate,
1.544     raeburn   442: 						$KeyFile,
1.545     raeburn   443: 						$clientname,
1.546     raeburn   444:                                                 $CRLFile,
                    445:                                                 $clientversion);
1.200     matthew   446:     if(! ($SSLSocket) ) {	# SSL socket promotion failed.
                    447: 	my $err = lonssl::LastError();
                    448: 	&logthis("<font color=\"red\"> CRITICAL "
                    449: 		 ."SSL Socket promotion failed: $err </font>");
                    450: 	return undef;
                    451:     }
                    452:     Debug("SSL Promotion successful");
                    453: 
                    454:     # 
                    455:     #  The only thing we'll use the socket for is to send the IDEA key
                    456:     #  to the peer:
                    457: 
                    458:     my $Key = lonlocal::CreateCipherKey();
                    459:     print $SSLSocket "$Key\n";
                    460: 
                    461:     lonssl::Close($SSLSocket); 
                    462: 
                    463:     Debug("Key exchange complete: $Key");
                    464: 
                    465:     return $Key;
                    466: }
                    467: #
                    468: #     InsecureConnection: 
                    469: #        If insecure connections are allowd,
                    470: #        exchange a challenge with the client to 'validate' the
                    471: #        client (not really, but that's the protocol):
                    472: #        We produce a challenge string that's sent to the client.
                    473: #        The client must then echo the challenge verbatim to us.
                    474: #
                    475: #  Parameter:
                    476: #      Socket      - Socket open on the client.
                    477: #  Returns:
                    478: #      1           - success.
                    479: #      0           - failure (e.g.mismatch or insecure not allowed).
                    480: #
                    481: sub InsecureConnection {
                    482:     my $Socket  =  shift;
                    483: 
                    484:     #   Don't even start if insecure connections are not allowed.
1.532     raeburn   485:     #   return 0 if Insecure connections not allowed.
                    486:     #
                    487:     if (ref($secureconf{'connfrom'}) eq 'HASH') {
                    488:         if ($clientsamedom) {
                    489:             if ($secureconf{'connfrom'}{'dom'} eq 'req') {
                    490:                 return 0;
                    491:             } 
                    492:         } elsif ($clientsameinst) {
                    493:             if ($secureconf{'connfrom'}{'intdom'} eq 'req') {
                    494:                 return 0;
                    495:             }
                    496:         } else {
                    497:             if ($secureconf{'connfrom'}{'other'} eq 'req') {
                    498:                 return 0;
                    499:             }
                    500:         }
                    501:     } elsif (!$perlvar{londAllowInsecure}) {
1.200     matthew   502: 	return 0;
                    503:     }
                    504: 
                    505:     #   Fabricate a challenge string and send it..
                    506: 
                    507:     my $challenge = "$$".time;	# pid + time.
                    508:     print $Socket "$challenge\n";
                    509:     &status("Waiting for challenge reply");
                    510: 
                    511:     my $answer = <$Socket>;
                    512:     $answer    =~s/\W//g;
                    513:     if($challenge eq $answer) {
                    514: 	return 1;
1.224     foxr      515:     } else {
1.200     matthew   516: 	logthis("<font color='blue'>WARNING client did not respond to challenge</font>");
                    517: 	&status("No challenge reqply");
                    518: 	return 0;
                    519:     }
                    520:     
                    521: 
                    522: }
1.251     foxr      523: #
                    524: #   Safely execute a command (as long as it's not a shel command and doesn
                    525: #   not require/rely on shell escapes.   The function operates by doing a
                    526: #   a pipe based fork and capturing stdout and stderr  from the pipe.
                    527: #
                    528: # Formal Parameters:
                    529: #     $line                    - A line of text to be executed as a command.
                    530: # Returns:
                    531: #     The output from that command.  If the output is multiline the caller
                    532: #     must know how to split up the output.
                    533: #
                    534: #
                    535: sub execute_command {
                    536:     my ($line)    = @_;
                    537:     my @words     = split(/\s/, $line);	# Bust the command up into words.
                    538:     my $output    = "";
                    539: 
                    540:     my $pid = open(CHILD, "-|");
                    541:     
                    542:     if($pid) {			# Parent process
                    543: 	Debug("In parent process for execute_command");
                    544: 	my @data = <CHILD>;	# Read the child's outupt...
                    545: 	close CHILD;
                    546: 	foreach my $output_line (@data) {
                    547: 	    Debug("Adding $output_line");
                    548: 	    $output .= $output_line; # Presumably has a \n on it.
                    549: 	}
                    550: 
                    551:     } else {			# Child process
                    552: 	close (STDERR);
                    553: 	open  (STDERR, ">&STDOUT");# Combine stderr, and stdout...
                    554: 	exec(@words);		# won't return.
                    555:     }
                    556:     return $output;
                    557: }
                    558: 
1.200     matthew   559: 
1.140     foxr      560: #   GetCertificate: Given a transaction that requires a certificate,
                    561: #   this function will extract the certificate from the transaction
                    562: #   request.  Note that at this point, the only concept of a certificate
                    563: #   is the hostname to which we are connected.
                    564: #
                    565: #   Parameter:
                    566: #      request   - The request sent by our client (this parameterization may
                    567: #                  need to change when we really use a certificate granting
                    568: #                  authority.
                    569: #
                    570: sub GetCertificate {
                    571:     my $request = shift;
                    572: 
                    573:     return $clientip;
                    574: }
1.161     foxr      575: 
1.178     foxr      576: #
                    577: #   Return true if client is a manager.
                    578: #
                    579: sub isManager {
                    580:     return (($ConnectionType eq "manager") || ($ConnectionType eq "both"));
                    581: }
                    582: #
                    583: #   Return tru if client can do client functions
                    584: #
                    585: sub isClient {
                    586:     return (($ConnectionType eq "client") || ($ConnectionType eq "both"));
                    587: }
1.161     foxr      588: 
                    589: 
1.156     foxr      590: #
                    591: #   ReadManagerTable: Reads in the current manager table. For now this is
                    592: #                     done on each manager authentication because:
                    593: #                     - These authentications are not frequent
                    594: #                     - This allows dynamic changes to the manager table
                    595: #                       without the need to signal to the lond.
                    596: #
                    597: sub ReadManagerTable {
                    598: 
1.412     foxr      599:     &Debug("Reading manager table");
1.156     foxr      600:     #   Clean out the old table first..
                    601: 
1.166     foxr      602:    foreach my $key (keys %managers) {
                    603:       delete $managers{$key};
                    604:    }
                    605: 
                    606:    my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
                    607:    if (!open (MANAGERS, $tablename)) {
1.473     raeburn   608:        my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
                    609:        if (&Apache::lonnet::is_LC_dns($hostname)) {
1.472     raeburn   610:            &logthis('<font color="red">No manager table.  Nobody can manage!!</font>');
                    611:        }
                    612:        return;
1.166     foxr      613:    }
                    614:    while(my $host = <MANAGERS>) {
                    615:       chomp($host);
                    616:       if ($host =~ "^#") {                  # Comment line.
                    617:          next;
                    618:       }
1.368     albertel  619:       if (!defined &Apache::lonnet::get_host_ip($host)) { # This is a non cluster member
1.161     foxr      620: 	    #  The entry is of the form:
                    621: 	    #    cluname:hostname
                    622: 	    #  cluname - A 'cluster hostname' is needed in order to negotiate
                    623: 	    #            the host key.
                    624: 	    #  hostname- The dns name of the host.
                    625: 	    #
1.166     foxr      626:           my($cluname, $dnsname) = split(/:/, $host);
                    627:           
                    628:           my $ip = gethostbyname($dnsname);
                    629:           if(defined($ip)) {                 # bad names don't deserve entry.
                    630:             my $hostip = inet_ntoa($ip);
                    631:             $managers{$hostip} = $cluname;
                    632:             logthis('<font color="green"> registering manager '.
                    633:                     "$dnsname as $cluname with $hostip </font>\n");
                    634:          }
                    635:       } else {
                    636:          logthis('<font color="green"> existing host'." $host</font>\n");
1.472     raeburn   637:          $managers{&Apache::lonnet::get_host_ip($host)} = $host;  # Use info from cluster tab if cluster memeber
1.166     foxr      638:       }
                    639:    }
1.156     foxr      640: }
1.140     foxr      641: 
                    642: #
                    643: #  ValidManager: Determines if a given certificate represents a valid manager.
                    644: #                in this primitive implementation, the 'certificate' is
                    645: #                just the connecting loncapa client name.  This is checked
                    646: #                against a valid client list in the configuration.
                    647: #
                    648: #                  
                    649: sub ValidManager {
                    650:     my $certificate = shift; 
                    651: 
1.163     foxr      652:     return isManager;
1.140     foxr      653: }
                    654: #
1.143     foxr      655: #  CopyFile:  Called as part of the process of installing a 
                    656: #             new configuration file.  This function copies an existing
                    657: #             file to a backup file.
                    658: # Parameters:
                    659: #     oldfile  - Name of the file to backup.
                    660: #     newfile  - Name of the backup file.
                    661: # Return:
                    662: #     0   - Failure (errno has failure reason).
                    663: #     1   - Success.
                    664: #
                    665: sub CopyFile {
1.192     foxr      666: 
                    667:     my ($oldfile, $newfile) = @_;
1.143     foxr      668: 
1.281     matthew   669:     if (! copy($oldfile,$newfile)) {
                    670:         return 0;
1.143     foxr      671:     }
1.281     matthew   672:     chmod(0660, $newfile);
                    673:     return 1;
1.143     foxr      674: }
1.157     foxr      675: #
                    676: #  Host files are passed out with externally visible host IPs.
                    677: #  If, for example, we are behind a fire-wall or NAT host, our 
                    678: #  internally visible IP may be different than the externally
                    679: #  visible IP.  Therefore, we always adjust the contents of the
                    680: #  host file so that the entry for ME is the IP that we believe
                    681: #  we have.  At present, this is defined as the entry that
                    682: #  DNS has for us.  If by some chance we are not able to get a
                    683: #  DNS translation for us, then we assume that the host.tab file
                    684: #  is correct.  
                    685: #    BUGBUGBUG - in the future, we really should see if we can
                    686: #       easily query the interface(s) instead.
                    687: # Parameter(s):
                    688: #     contents    - The contents of the host.tab to check.
                    689: # Returns:
                    690: #     newcontents - The adjusted contents.
                    691: #
                    692: #
                    693: sub AdjustHostContents {
                    694:     my $contents  = shift;
                    695:     my $adjusted;
                    696:     my $me        = $perlvar{'lonHostID'};
                    697: 
1.354     albertel  698:     foreach my $line (split(/\n/,$contents)) {
1.472     raeburn   699: 	if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/) ||
                    700:              ($line =~ /^\s*\^/))) {
1.157     foxr      701: 	    chomp($line);
                    702: 	    my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
                    703: 	    if ($id eq $me) {
1.354     albertel  704: 		my $ip = gethostbyname($name);
                    705: 		my $ipnew = inet_ntoa($ip);
                    706: 		$ip = $ipnew;
1.157     foxr      707: 		#  Reconstruct the host line and append to adjusted:
                    708: 		
1.354     albertel  709: 		my $newline = "$id:$domain:$role:$name:$ip";
                    710: 		if($maxcon ne "") { # Not all hosts have loncnew tuning params
                    711: 		    $newline .= ":$maxcon:$idleto:$mincon";
                    712: 		}
                    713: 		$adjusted .= $newline."\n";
1.157     foxr      714: 		
1.354     albertel  715: 	    } else {		# Not me, pass unmodified.
                    716: 		$adjusted .= $line."\n";
                    717: 	    }
1.157     foxr      718: 	} else {                  # Blank or comment never re-written.
                    719: 	    $adjusted .= $line."\n";	# Pass blanks and comments as is.
                    720: 	}
1.354     albertel  721:     }
                    722:     return $adjusted;
1.157     foxr      723: }
1.143     foxr      724: #
                    725: #   InstallFile: Called to install an administrative file:
1.412     foxr      726: #       - The file is created int a temp directory called <name>.tmp
                    727: #       - lcinstall file is called to install the file.
                    728: #         since the web app has no direct write access to the table directory
1.143     foxr      729: #
                    730: #  Parameters:
                    731: #       Name of the file
                    732: #       File Contents.
                    733: #  Return:
                    734: #      nonzero - success.
                    735: #      0       - failure and $! has an errno.
1.412     foxr      736: # Assumptions:
                    737: #    File installtion is a relatively infrequent
1.143     foxr      738: #
                    739: sub InstallFile {
1.192     foxr      740: 
                    741:     my ($Filename, $Contents) = @_;
1.412     foxr      742: #     my $TempFile = $Filename.".tmp";
                    743:     my $exedir = $perlvar{'lonDaemons'};
                    744:     my $tmpdir = $exedir.'/tmp/';
                    745:     my $TempFile = $tmpdir."TempTableFile.tmp";
1.143     foxr      746: 
                    747:     #  Open the file for write:
                    748: 
                    749:     my $fh = IO::File->new("> $TempFile"); # Write to temp.
                    750:     if(!(defined $fh)) {
                    751: 	&logthis('<font color="red"> Unable to create '.$TempFile."</font>");
                    752: 	return 0;
                    753:     }
                    754:     #  write the contents of the file:
                    755: 
                    756:     print $fh ($Contents); 
                    757:     $fh->close;			# In case we ever have a filesystem w. locking
                    758: 
1.412     foxr      759:     chmod(0664, $TempFile);	# Everyone can write it.
                    760: 
                    761:     # Use lcinstall file to put the file in the table directory...
                    762: 
                    763:     &Debug("Opening pipe to $exedir/lcinstallfile $TempFile $Filename");
                    764:     my $pf = IO::File->new("| $exedir/lcinstallfile   $TempFile $Filename > $exedir/logs/lcinstallfile.log");
                    765:     close $pf;
                    766:     my $err = $?;
                    767:     &Debug("Status is $err");
                    768:     if ($err != 0) {
                    769: 	my $msg = $err;
                    770: 	if ($err < @installerrors) {
                    771: 	    $msg = $installerrors[$err];
                    772: 	}
                    773: 	&logthis("Install failed for table file $Filename : $msg");
                    774: 	return 0;
                    775:     }
                    776: 
                    777:     # Remove the temp file:
1.143     foxr      778: 
1.412     foxr      779:     unlink($TempFile);
1.143     foxr      780: 
                    781:     return 1;
                    782: }
1.200     matthew   783: 
                    784: 
1.169     foxr      785: #
                    786: #   ConfigFileFromSelector: converts a configuration file selector
1.411     foxr      787: #                 into a configuration file pathname.
1.472     raeburn   788: #                 Supports the following file selectors: 
                    789: #                 hosts, domain, dns_hosts, dns_domain  
1.411     foxr      790: #
1.169     foxr      791: #
                    792: #  Parameters:
                    793: #      selector  - Configuration file selector.
                    794: #  Returns:
                    795: #      Full path to the file or undef if the selector is invalid.
                    796: #
                    797: sub ConfigFileFromSelector {
                    798:     my $selector   = shift;
                    799:     my $tablefile;
                    800: 
1.549     raeburn   801:     if ($selector eq 'loncapaCAcrl') {
                    802:         my $tabledir = $perlvar{'lonCertificateDirectory'};
                    803:         if (-d $tabledir) {
                    804:             $tablefile =  $tabledir.'/'.$selector.'.pem';
                    805:         }
                    806:     } else {
                    807:         my $tabledir = $perlvar{'lonTabDir'}.'/';
                    808:         if (($selector eq "hosts") || ($selector eq "domain") || 
                    809:             ($selector eq "dns_hosts") || ($selector eq "dns_domain")) {
                    810: 	    $tablefile =  $tabledir.$selector.'.tab';
                    811:         }
1.169     foxr      812:     }
                    813:     return $tablefile;
                    814: }
1.143     foxr      815: #
1.141     foxr      816: #   PushFile:  Called to do an administrative push of a file.
                    817: #              - Ensure the file being pushed is one we support.
                    818: #              - Backup the old file to <filename.saved>
                    819: #              - Separate the contents of the new file out from the
                    820: #                rest of the request.
                    821: #              - Write the new file.
                    822: #  Parameter:
                    823: #     Request - The entire user request.  This consists of a : separated
                    824: #               string pushfile:tablename:contents.
                    825: #     NOTE:  The contents may have :'s in it as well making things a bit
                    826: #            more interesting... but not much.
                    827: #  Returns:
                    828: #     String to send to client ("ok" or "refused" if bad file).
                    829: #
                    830: sub PushFile {
1.510     raeburn   831:     my $request = shift;
1.141     foxr      832:     my ($command, $filename, $contents) = split(":", $request, 3);
1.412     foxr      833:     &Debug("PushFile");
1.141     foxr      834:     
1.549     raeburn   835:     #  At this point in time, pushes for only the following tables and
                    836:     #  CRL file are supported:
1.141     foxr      837:     #   hosts.tab  ($filename eq host).
                    838:     #   domain.tab ($filename eq domain).
1.472     raeburn   839:     #   dns_hosts.tab ($filename eq dns_host).
1.554     raeburn   840:     #   dns_domain.tab ($filename eq dns_domain).
                    841:     #   loncapaCAcrl.pem ($filename eq loncapaCAcrl).
1.141     foxr      842:     # Construct the destination filename or reject the request.
                    843:     #
                    844:     # lonManage is supposed to ensure this, however this session could be
                    845:     # part of some elaborate spoof that managed somehow to authenticate.
                    846:     #
                    847: 
1.169     foxr      848: 
                    849:     my $tablefile = ConfigFileFromSelector($filename);
                    850:     if(! (defined $tablefile)) {
1.141     foxr      851: 	return "refused";
                    852:     }
1.412     foxr      853: 
1.157     foxr      854:     #  If the file being pushed is the host file, we adjust the entry for ourself so that the
                    855:     #  IP will be our current IP as looked up in dns.  Note this is only 99% good as it's possible
                    856:     #  to conceive of conditions where we don't have a DNS entry locally.  This is possible in a 
                    857:     #  network sense but it doesn't make much sense in a LonCAPA sense so we ignore (for now)
                    858:     #  that possibilty.
                    859: 
                    860:     if($filename eq "host") {
                    861: 	$contents = AdjustHostContents($contents);
1.549     raeburn   862:     } elsif (($filename eq 'dns_host') || ($filename eq 'dns_domain') ||
                    863:              ($filename eq 'loncapaCAcrl')) {
1.510     raeburn   864:         if ($contents eq '') {
                    865:             &logthis('<font color="red"> Pushfile: unable to install '
                    866:                     .$tablefile." - no data received from push. </font>");
                    867:             return 'error: push had no data';
                    868:         }
                    869:         if (&Apache::lonnet::get_host_ip($clientname)) {
                    870:             my $clienthost = &Apache::lonnet::hostname($clientname);
                    871:             if ($managers{$clientip} eq $clientname) {
                    872:                 my $clientprotocol = $Apache::lonnet::protocol{$clientname};
                    873:                 $clientprotocol = 'http' if ($clientprotocol ne 'https');
1.549     raeburn   874:                 my $url;
                    875:                 if ($filename eq 'loncapaCAcrl') {
                    876:                     $url = '/adm/dns/loncapaCRL';
                    877:                 } else {
                    878:                     $url = '/adm/'.$filename;
                    879:                     $url =~ s{_}{/};
                    880:                 }
1.510     raeburn   881:                 my $request=new HTTP::Request('GET',"$clientprotocol://$clienthost$url");
1.523     raeburn   882:                 my $response = LONCAPA::LWPReq::makerequest($clientname,$request,'',\%perlvar,60,0);
1.510     raeburn   883:                 if ($response->is_error()) {
                    884:                     &logthis('<font color="red"> Pushfile: unable to install '
                    885:                             .$tablefile." - error attempting to pull data. </font>");
                    886:                     return 'error: pull failed';
                    887:                 } else {
                    888:                     my $result = $response->content;
                    889:                     chomp($result);
                    890:                     unless ($result eq $contents) {
                    891:                         &logthis('<font color="red"> Pushfile: unable to install '
                    892:                                 .$tablefile." - pushed data and pulled data differ. </font>");
                    893:                         my $pushleng = length($contents);
                    894:                         my $pullleng = length($result);
                    895:                         if ($pushleng != $pullleng) {
                    896:                             return "error: $pushleng vs $pullleng bytes";
                    897:                         } else {
                    898:                             return "error: mismatch push and pull";
                    899:                         }
                    900:                     }
                    901:                 }
                    902:             }
                    903:         }
1.157     foxr      904:     }
                    905: 
1.141     foxr      906:     #  Install the new file:
                    907: 
1.412     foxr      908:     &logthis("Installing new $tablefile contents:\n$contents");
1.143     foxr      909:     if(!InstallFile($tablefile, $contents)) {
                    910: 	&logthis('<font color="red"> Pushfile: unable to install '
1.145     foxr      911: 	 .$tablefile." $! </font>");
1.143     foxr      912: 	return "error:$!";
1.224     foxr      913:     } else {
1.143     foxr      914: 	&logthis('<font color="green"> Installed new '.$tablefile
1.473     raeburn   915: 		 ." - transaction by: $clientname ($clientip)</font>");
1.472     raeburn   916:         my $adminmail = $perlvar{'lonAdmEMail'};
                    917:         my $admindom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                    918:         if ($admindom ne '') {
                    919:             my %domconfig =
                    920:                 &Apache::lonnet::get_dom('configuration',['contacts'],$admindom);
                    921:             if (ref($domconfig{'contacts'}) eq 'HASH') {
                    922:                 if ($domconfig{'contacts'}{'adminemail'} ne '') {
                    923:                     $adminmail = $domconfig{'contacts'}{'adminemail'};
                    924:                 }
                    925:             }
                    926:         }
                    927:         if ($adminmail =~ /^[^\@]+\@[^\@]+$/) {
                    928:             my $msg = new Mail::Send;
                    929:             $msg->to($adminmail);
                    930:             $msg->subject('LON-CAPA DNS update on '.$perlvar{'lonHostID'});
                    931:             $msg->add('Content-type','text/plain; charset=UTF-8');
                    932:             if (my $fh = $msg->open()) {
                    933:                 print $fh 'Update to '.$tablefile.' from Cluster Manager '.
1.473     raeburn   934:                           "$clientname ($clientip)\n";
1.472     raeburn   935:                 $fh->close;
                    936:             }
                    937:         }
1.143     foxr      938:     }
                    939: 
1.141     foxr      940:     #  Indicate success:
                    941:  
                    942:     return "ok";
                    943: 
                    944: }
1.145     foxr      945: 
                    946: #
                    947: #  Called to re-init either lonc or lond.
                    948: #
                    949: #  Parameters:
                    950: #    request   - The full request by the client.  This is of the form
                    951: #                reinit:<process>  
                    952: #                where <process> is allowed to be either of 
                    953: #                lonc or lond
                    954: #
                    955: #  Returns:
                    956: #     The string to be sent back to the client either:
                    957: #   ok         - Everything worked just fine.
                    958: #   error:why  - There was a failure and why describes the reason.
                    959: #
                    960: #
                    961: sub ReinitProcess {
                    962:     my $request = shift;
                    963: 
1.146     foxr      964: 
                    965:     # separate the request (reinit) from the process identifier and
                    966:     # validate it producing the name of the .pid file for the process.
                    967:     #
                    968:     #
                    969:     my ($junk, $process) = split(":", $request);
1.147     foxr      970:     my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
1.146     foxr      971:     if($process eq 'lonc') {
                    972: 	$processpidfile = $processpidfile."lonc.pid";
1.147     foxr      973: 	if (!open(PIDFILE, "< $processpidfile")) {
                    974: 	    return "error:Open failed for $processpidfile";
                    975: 	}
                    976: 	my $loncpid = <PIDFILE>;
                    977: 	close(PIDFILE);
                    978: 	logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
                    979: 		."</font>");
                    980: 	kill("USR2", $loncpid);
1.146     foxr      981:     } elsif ($process eq 'lond') {
1.147     foxr      982: 	logthis('<font color="red"> Reinitializing self (lond) </font>');
                    983: 	&UpdateHosts;			# Lond is us!!
1.146     foxr      984:     } else {
                    985: 	&logthis('<font color="yellow" Invalid reinit request for '.$process
                    986: 		 ."</font>");
                    987: 	return "error:Invalid process identifier $process";
                    988:     }
1.145     foxr      989:     return 'ok';
                    990: }
1.168     foxr      991: #   Validate a line in a configuration file edit script:
                    992: #   Validation includes:
                    993: #     - Ensuring the command is valid.
                    994: #     - Ensuring the command has sufficient parameters
                    995: #   Parameters:
                    996: #     scriptline - A line to validate (\n has been stripped for what it's worth).
1.167     foxr      997: #
1.168     foxr      998: #   Return:
                    999: #      0     - Invalid scriptline.
                   1000: #      1     - Valid scriptline
                   1001: #  NOTE:
                   1002: #     Only the command syntax is checked, not the executability of the
                   1003: #     command.
                   1004: #
                   1005: sub isValidEditCommand {
                   1006:     my $scriptline = shift;
                   1007: 
                   1008:     #   Line elements are pipe separated:
                   1009: 
                   1010:     my ($command, $key, $newline)  = split(/\|/, $scriptline);
                   1011:     &logthis('<font color="green"> isValideditCommand checking: '.
                   1012: 	     "Command = '$command', Key = '$key', Newline = '$newline' </font>\n");
                   1013:     
                   1014:     if ($command eq "delete") {
                   1015: 	#
                   1016: 	#   key with no newline.
                   1017: 	#
                   1018: 	if( ($key eq "") || ($newline ne "")) {
                   1019: 	    return 0;		# Must have key but no newline.
                   1020: 	} else {
                   1021: 	    return 1;		# Valid syntax.
                   1022: 	}
1.169     foxr     1023:     } elsif ($command eq "replace") {
1.168     foxr     1024: 	#
                   1025: 	#   key and newline:
                   1026: 	#
                   1027: 	if (($key eq "") || ($newline eq "")) {
                   1028: 	    return 0;
                   1029: 	} else {
                   1030: 	    return 1;
                   1031: 	}
1.169     foxr     1032:     } elsif ($command eq "append") {
                   1033: 	if (($key ne "") && ($newline eq "")) {
                   1034: 	    return 1;
                   1035: 	} else {
                   1036: 	    return 0;
                   1037: 	}
1.168     foxr     1038:     } else {
                   1039: 	return 0;		# Invalid command.
                   1040:     }
                   1041:     return 0;			# Should not get here!!!
                   1042: }
1.169     foxr     1043: #
                   1044: #   ApplyEdit - Applies an edit command to a line in a configuration 
                   1045: #               file.  It is the caller's responsiblity to validate the
                   1046: #               edit line.
                   1047: #   Parameters:
                   1048: #      $directive - A single edit directive to apply.  
                   1049: #                   Edit directives are of the form:
                   1050: #                  append|newline      - Appends a new line to the file.
                   1051: #                  replace|key|newline - Replaces the line with key value 'key'
                   1052: #                  delete|key          - Deletes the line with key value 'key'.
                   1053: #      $editor   - A config file editor object that contains the
                   1054: #                  file being edited.
                   1055: #
                   1056: sub ApplyEdit {
1.192     foxr     1057: 
                   1058:     my ($directive, $editor) = @_;
1.169     foxr     1059: 
                   1060:     # Break the directive down into its command and its parameters
                   1061:     # (at most two at this point.  The meaning of the parameters, if in fact
                   1062:     #  they exist depends on the command).
                   1063: 
                   1064:     my ($command, $p1, $p2) = split(/\|/, $directive);
                   1065: 
                   1066:     if($command eq "append") {
                   1067: 	$editor->Append($p1);	          # p1 - key p2 null.
                   1068:     } elsif ($command eq "replace") {
                   1069: 	$editor->ReplaceLine($p1, $p2);   # p1 - key p2 = newline.
                   1070:     } elsif ($command eq "delete") {
                   1071: 	$editor->DeleteLine($p1);         # p1 - key p2 null.
                   1072:     } else {			          # Should not get here!!!
                   1073: 	die "Invalid command given to ApplyEdit $command"
                   1074:     }
                   1075: }
                   1076: #
                   1077: # AdjustOurHost:
                   1078: #           Adjusts a host file stored in a configuration file editor object
                   1079: #           for the true IP address of this host. This is necessary for hosts
                   1080: #           that live behind a firewall.
                   1081: #           Those hosts have a publicly distributed IP of the firewall, but
                   1082: #           internally must use their actual IP.  We assume that a given
                   1083: #           host only has a single IP interface for now.
                   1084: # Formal Parameters:
                   1085: #     editor   - The configuration file editor to adjust.  This
                   1086: #                editor is assumed to contain a hosts.tab file.
                   1087: # Strategy:
                   1088: #    - Figure out our hostname.
                   1089: #    - Lookup the entry for this host.
                   1090: #    - Modify the line to contain our IP
                   1091: #    - Do a replace for this host.
                   1092: sub AdjustOurHost {
                   1093:     my $editor        = shift;
                   1094: 
                   1095:     # figure out who I am.
                   1096: 
                   1097:     my $myHostName    = $perlvar{'lonHostID'}; # LonCAPA hostname.
                   1098: 
                   1099:     #  Get my host file entry.
                   1100: 
                   1101:     my $ConfigLine    = $editor->Find($myHostName);
                   1102:     if(! (defined $ConfigLine)) {
                   1103: 	die "AdjustOurHost - no entry for me in hosts file $myHostName";
                   1104:     }
                   1105:     # figure out my IP:
                   1106:     #   Use the config line to get my hostname.
                   1107:     #   Use gethostbyname to translate that into an IP address.
                   1108:     #
1.338     albertel 1109:     my ($id,$domain,$role,$name,$maxcon,$idleto,$mincon) = split(/:/,$ConfigLine);
1.169     foxr     1110:     #
                   1111:     #  Reassemble the config line from the elements in the list.
                   1112:     #  Note that if the loncnew items were not present before, they will
                   1113:     #  be now even if they would be empty
                   1114:     #
                   1115:     my $newConfigLine = $id;
1.338     albertel 1116:     foreach my $item ($domain, $role, $name, $maxcon, $idleto, $mincon) {
1.169     foxr     1117: 	$newConfigLine .= ":".$item;
                   1118:     }
                   1119:     #  Replace the line:
                   1120: 
                   1121:     $editor->ReplaceLine($id, $newConfigLine);
                   1122:     
                   1123: }
                   1124: #
                   1125: #   ReplaceConfigFile:
                   1126: #              Replaces a configuration file with the contents of a
                   1127: #              configuration file editor object.
                   1128: #              This is done by:
                   1129: #              - Copying the target file to <filename>.old
                   1130: #              - Writing the new file to <filename>.tmp
                   1131: #              - Moving <filename.tmp>  -> <filename>
                   1132: #              This laborious process ensures that the system is never without
                   1133: #              a configuration file that's at least valid (even if the contents
                   1134: #              may be dated).
                   1135: #   Parameters:
                   1136: #        filename   - Name of the file to modify... this is a full path.
                   1137: #        editor     - Editor containing the file.
                   1138: #
                   1139: sub ReplaceConfigFile {
1.192     foxr     1140:     
                   1141:     my ($filename, $editor) = @_;
1.168     foxr     1142: 
1.169     foxr     1143:     CopyFile ($filename, $filename.".old");
                   1144: 
                   1145:     my $contents  = $editor->Get(); # Get the contents of the file.
                   1146: 
                   1147:     InstallFile($filename, $contents);
                   1148: }
1.168     foxr     1149: #   
                   1150: #
                   1151: #   Called to edit a configuration table  file
1.167     foxr     1152: #   Parameters:
                   1153: #      request           - The entire command/request sent by lonc or lonManage
                   1154: #   Return:
                   1155: #      The reply to send to the client.
1.168     foxr     1156: #
1.167     foxr     1157: sub EditFile {
                   1158:     my $request = shift;
                   1159: 
                   1160:     #  Split the command into it's pieces:  edit:filetype:script
                   1161: 
1.339     albertel 1162:     my ($cmd, $filetype, $script) = split(/:/, $request,3);	# : in script
1.167     foxr     1163: 
                   1164:     #  Check the pre-coditions for success:
                   1165: 
1.339     albertel 1166:     if($cmd != "edit") {	# Something is amiss afoot alack.
1.167     foxr     1167: 	return "error:edit request detected, but request != 'edit'\n";
                   1168:     }
                   1169:     if( ($filetype ne "hosts")  &&
                   1170: 	($filetype ne "domain")) {
                   1171: 	return "error:edit requested with invalid file specifier: $filetype \n";
                   1172:     }
                   1173: 
                   1174:     #   Split the edit script and check it's validity.
1.168     foxr     1175: 
                   1176:     my @scriptlines = split(/\n/, $script);  # one line per element.
                   1177:     my $linecount   = scalar(@scriptlines);
                   1178:     for(my $i = 0; $i < $linecount; $i++) {
                   1179: 	chomp($scriptlines[$i]);
                   1180: 	if(!isValidEditCommand($scriptlines[$i])) {
                   1181: 	    return "error:edit with bad script line: '$scriptlines[$i]' \n";
                   1182: 	}
                   1183:     }
1.145     foxr     1184: 
1.167     foxr     1185:     #   Execute the edit operation.
1.169     foxr     1186:     #   - Create a config file editor for the appropriate file and 
                   1187:     #   - execute each command in the script:
                   1188:     #
                   1189:     my $configfile = ConfigFileFromSelector($filetype);
                   1190:     if (!(defined $configfile)) {
                   1191: 	return "refused\n";
                   1192:     }
                   1193:     my $editor = ConfigFileEdit->new($configfile);
1.167     foxr     1194: 
1.169     foxr     1195:     for (my $i = 0; $i < $linecount; $i++) {
                   1196: 	ApplyEdit($scriptlines[$i], $editor);
                   1197:     }
                   1198:     # If the file is the host file, ensure that our host is
                   1199:     # adjusted to have our ip:
                   1200:     #
                   1201:     if($filetype eq "host") {
                   1202: 	AdjustOurHost($editor);
                   1203:     }
                   1204:     #  Finally replace the current file with our file.
                   1205:     #
                   1206:     ReplaceConfigFile($configfile, $editor);
1.167     foxr     1207: 
                   1208:     return "ok\n";
                   1209: }
1.207     foxr     1210: 
1.255     foxr     1211: #   read_profile
                   1212: #
                   1213: #   Returns a set of specific entries from a user's profile file.
                   1214: #   this is a utility function that is used by both get_profile_entry and
                   1215: #   get_profile_entry_encrypted.
                   1216: #
                   1217: # Parameters:
                   1218: #    udom       - Domain in which the user exists.
                   1219: #    uname      - User's account name (loncapa account)
                   1220: #    namespace  - The profile namespace to open.
                   1221: #    what       - A set of & separated queries.
                   1222: # Returns:
                   1223: #    If all ok: - The string that needs to be shipped back to the user.
                   1224: #    If failure - A string that starts with error: followed by the failure
                   1225: #                 reason.. note that this probabyl gets shipped back to the
                   1226: #                 user as well.
                   1227: #
                   1228: sub read_profile {
                   1229:     my ($udom, $uname, $namespace, $what) = @_;
                   1230:     
                   1231:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   1232: 				 &GDBM_READER());
                   1233:     if ($hashref) {
                   1234:         my @queries=split(/\&/,$what);
1.440     raeburn  1235:         if ($namespace eq 'roles') {
                   1236:             @queries = map { &unescape($_); } @queries; 
                   1237:         }
1.255     foxr     1238:         my $qresult='';
                   1239: 	
                   1240: 	for (my $i=0;$i<=$#queries;$i++) {
                   1241: 	    $qresult.="$hashref->{$queries[$i]}&";    # Presumably failure gives empty string.
                   1242: 	}
                   1243: 	$qresult=~s/\&$//;              # Remove trailing & from last lookup.
1.311     albertel 1244: 	if (&untie_user_hash($hashref)) {
1.255     foxr     1245: 	    return $qresult;
                   1246: 	} else {
                   1247: 	    return "error: ".($!+0)." untie (GDBM) Failed";
                   1248: 	}
                   1249:     } else {
                   1250: 	if ($!+0 == 2) {
                   1251: 	    return "error:No such file or GDBM reported bad block error";
                   1252: 	} else {
                   1253: 	    return "error: ".($!+0)." tie (GDBM) Failed";
                   1254: 	}
                   1255:     }
                   1256: 
                   1257: }
1.214     foxr     1258: #--------------------- Request Handlers --------------------------------------------
                   1259: #
1.215     foxr     1260: #   By convention each request handler registers itself prior to the sub 
                   1261: #   declaration:
1.214     foxr     1262: #
                   1263: 
1.216     foxr     1264: #++
                   1265: #
1.214     foxr     1266: #  Handles ping requests.
                   1267: #  Parameters:
                   1268: #      $cmd    - the actual keyword that invoked us.
                   1269: #      $tail   - the tail of the request that invoked us.
                   1270: #      $replyfd- File descriptor connected to the client
                   1271: #  Implicit Inputs:
                   1272: #      $currenthostid - Global variable that carries the name of the host we are
                   1273: #                       known as.
                   1274: #  Returns:
                   1275: #      1       - Ok to continue processing.
                   1276: #      0       - Program should exit.
                   1277: #  Side effects:
                   1278: #      Reply information is sent to the client.
                   1279: sub ping_handler {
                   1280:     my ($cmd, $tail, $client) = @_;
                   1281:     Debug("$cmd $tail $client .. $currenthostid:");
                   1282:    
1.387     albertel 1283:     Reply( $client,\$currenthostid,"$cmd:$tail");
1.214     foxr     1284:    
                   1285:     return 1;
                   1286: }
                   1287: &register_handler("ping", \&ping_handler, 0, 1, 1);       # Ping unencoded, client or manager.
                   1288: 
1.216     foxr     1289: #++
1.215     foxr     1290: #
                   1291: # Handles pong requests.  Pong replies with our current host id, and
                   1292: #                         the results of a ping sent to us via our lonc.
                   1293: #
                   1294: # Parameters:
                   1295: #      $cmd    - the actual keyword that invoked us.
                   1296: #      $tail   - the tail of the request that invoked us.
                   1297: #      $replyfd- File descriptor connected to the client
                   1298: #  Implicit Inputs:
                   1299: #      $currenthostid - Global variable that carries the name of the host we are
                   1300: #                       connected to.
                   1301: #  Returns:
                   1302: #      1       - Ok to continue processing.
                   1303: #      0       - Program should exit.
                   1304: #  Side effects:
                   1305: #      Reply information is sent to the client.
                   1306: sub pong_handler {
                   1307:     my ($cmd, $tail, $replyfd) = @_;
                   1308: 
1.365     albertel 1309:     my $reply=&Apache::lonnet::reply("ping",$clientname);
1.215     foxr     1310:     &Reply( $replyfd, "$currenthostid:$reply\n", "$cmd:$tail"); 
                   1311:     return 1;
                   1312: }
                   1313: &register_handler("pong", \&pong_handler, 0, 1, 1);       # Pong unencoded, client or manager
                   1314: 
1.216     foxr     1315: #++
                   1316: #      Called to establish an encrypted session key with the remote client.
                   1317: #      Note that with secure lond, in most cases this function is never
                   1318: #      invoked.  Instead, the secure session key is established either
                   1319: #      via a local file that's locked down tight and only lives for a short
                   1320: #      time, or via an ssl tunnel...and is generated from a bunch-o-random
                   1321: #      bits from /dev/urandom, rather than the predictable pattern used by
                   1322: #      by this sub.  This sub is only used in the old-style insecure
                   1323: #      key negotiation.
                   1324: # Parameters:
                   1325: #      $cmd    - the actual keyword that invoked us.
                   1326: #      $tail   - the tail of the request that invoked us.
                   1327: #      $replyfd- File descriptor connected to the client
                   1328: #  Implicit Inputs:
                   1329: #      $currenthostid - Global variable that carries the name of the host
                   1330: #                       known as.
1.448     raeburn  1331: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.216     foxr     1332: #  Returns:
                   1333: #      1       - Ok to continue processing.
                   1334: #      0       - Program should exit.
                   1335: #  Implicit Outputs:
                   1336: #      Reply information is sent to the client.
                   1337: #      $cipher is set with a reference to a new IDEA encryption object.
                   1338: #
                   1339: sub establish_key_handler {
                   1340:     my ($cmd, $tail, $replyfd) = @_;
                   1341: 
                   1342:     my $buildkey=time.$$.int(rand 100000);
                   1343:     $buildkey=~tr/1-6/A-F/;
                   1344:     $buildkey=int(rand 100000).$buildkey.int(rand 100000);
                   1345:     my $key=$currenthostid.$clientname;
                   1346:     $key=~tr/a-z/A-Z/;
                   1347:     $key=~tr/G-P/0-9/;
                   1348:     $key=~tr/Q-Z/0-9/;
                   1349:     $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
                   1350:     $key=substr($key,0,32);
                   1351:     my $cipherkey=pack("H32",$key);
                   1352:     $cipher=new IDEA $cipherkey;
1.387     albertel 1353:     &Reply($replyfd, \$buildkey, "$cmd:$tail"); 
1.216     foxr     1354:    
                   1355:     return 1;
                   1356: 
                   1357: }
                   1358: &register_handler("ekey", \&establish_key_handler, 0, 1,1);
                   1359: 
1.217     foxr     1360: #     Handler for the load command.  Returns the current system load average
                   1361: #     to the requestor.
                   1362: #
                   1363: # Parameters:
                   1364: #      $cmd    - the actual keyword that invoked us.
                   1365: #      $tail   - the tail of the request that invoked us.
                   1366: #      $replyfd- File descriptor connected to the client
                   1367: #  Implicit Inputs:
                   1368: #      $currenthostid - Global variable that carries the name of the host
                   1369: #                       known as.
1.448     raeburn  1370: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.217     foxr     1371: #  Returns:
                   1372: #      1       - Ok to continue processing.
                   1373: #      0       - Program should exit.
                   1374: #  Side effects:
                   1375: #      Reply information is sent to the client.
                   1376: sub load_handler {
                   1377:     my ($cmd, $tail, $replyfd) = @_;
                   1378: 
1.463     foxr     1379: 
                   1380: 
1.217     foxr     1381:    # Get the load average from /proc/loadavg and calculate it as a percentage of
                   1382:    # the allowed load limit as set by the perl global variable lonLoadLim
                   1383: 
                   1384:     my $loadavg;
                   1385:     my $loadfile=IO::File->new('/proc/loadavg');
                   1386:    
                   1387:     $loadavg=<$loadfile>;
                   1388:     $loadavg =~ s/\s.*//g;                      # Extract the first field only.
                   1389:    
                   1390:     my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
                   1391: 
1.387     albertel 1392:     &Reply( $replyfd, \$loadpercent, "$cmd:$tail");
1.217     foxr     1393:    
                   1394:     return 1;
                   1395: }
1.263     albertel 1396: &register_handler("load", \&load_handler, 0, 1, 0);
1.217     foxr     1397: 
                   1398: #
                   1399: #   Process the userload request.  This sub returns to the client the current
                   1400: #  user load average.  It can be invoked either by clients or managers.
                   1401: #
                   1402: # Parameters:
                   1403: #      $cmd    - the actual keyword that invoked us.
                   1404: #      $tail   - the tail of the request that invoked us.
                   1405: #      $replyfd- File descriptor connected to the client
                   1406: #  Implicit Inputs:
                   1407: #      $currenthostid - Global variable that carries the name of the host
                   1408: #                       known as.
1.448     raeburn  1409: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.217     foxr     1410: #  Returns:
                   1411: #      1       - Ok to continue processing.
                   1412: #      0       - Program should exit
                   1413: # Implicit inputs:
                   1414: #     whatever the userload() function requires.
                   1415: #  Implicit outputs:
                   1416: #     the reply is written to the client.
                   1417: #
                   1418: sub user_load_handler {
                   1419:     my ($cmd, $tail, $replyfd) = @_;
                   1420: 
1.365     albertel 1421:     my $userloadpercent=&Apache::lonnet::userload();
1.387     albertel 1422:     &Reply($replyfd, \$userloadpercent, "$cmd:$tail");
1.217     foxr     1423:     
                   1424:     return 1;
                   1425: }
1.263     albertel 1426: &register_handler("userload", \&user_load_handler, 0, 1, 0);
1.217     foxr     1427: 
1.218     foxr     1428: #   Process a request for the authorization type of a user:
                   1429: #   (userauth).
                   1430: #
                   1431: # Parameters:
                   1432: #      $cmd    - the actual keyword that invoked us.
                   1433: #      $tail   - the tail of the request that invoked us.
                   1434: #      $replyfd- File descriptor connected to the client
                   1435: #  Returns:
                   1436: #      1       - Ok to continue processing.
                   1437: #      0       - Program should exit
                   1438: # Implicit outputs:
                   1439: #    The user authorization type is written to the client.
                   1440: #
                   1441: sub user_authorization_type {
                   1442:     my ($cmd, $tail, $replyfd) = @_;
                   1443:    
                   1444:     my $userinput = "$cmd:$tail";
                   1445:    
                   1446:     #  Pull the domain and username out of the command tail.
1.222     foxr     1447:     # and call get_auth_type to determine the authentication type.
1.218     foxr     1448:    
                   1449:     my ($udom,$uname)=split(/:/,$tail);
1.222     foxr     1450:     my $result = &get_auth_type($udom, $uname);
1.218     foxr     1451:     if($result eq "nouser") {
                   1452: 	&Failure( $replyfd, "unknown_user\n", $userinput);
                   1453:     } else {
                   1454: 	#
1.222     foxr     1455: 	# We only want to pass the second field from get_auth_type
1.218     foxr     1456: 	# for ^krb.. otherwise we'll be handing out the encrypted
                   1457: 	# password for internals e.g.
                   1458: 	#
                   1459: 	my ($type,$otherinfo) = split(/:/,$result);
                   1460: 	if($type =~ /^krb/) {
                   1461: 	    $type = $result;
1.269     raeburn  1462: 	} else {
                   1463:             $type .= ':';
                   1464:         }
1.387     albertel 1465: 	&Reply( $replyfd, \$type, $userinput);
1.218     foxr     1466:     }
                   1467:   
                   1468:     return 1;
                   1469: }
                   1470: &register_handler("currentauth", \&user_authorization_type, 1, 1, 0);
                   1471: 
                   1472: #   Process a request by a manager to push a hosts or domain table 
                   1473: #   to us.  We pick apart the command and pass it on to the subs
                   1474: #   that already exist to do this.
                   1475: #
                   1476: # Parameters:
                   1477: #      $cmd    - the actual keyword that invoked us.
                   1478: #      $tail   - the tail of the request that invoked us.
                   1479: #      $client - File descriptor connected to the client
                   1480: #  Returns:
                   1481: #      1       - Ok to continue processing.
                   1482: #      0       - Program should exit
                   1483: # Implicit Output:
                   1484: #    a reply is written to the client.
                   1485: sub push_file_handler {
                   1486:     my ($cmd, $tail, $client) = @_;
1.412     foxr     1487:     &Debug("In push file handler");
1.218     foxr     1488:     my $userinput = "$cmd:$tail";
                   1489: 
                   1490:     # At this time we only know that the IP of our partner is a valid manager
                   1491:     # the code below is a hook to do further authentication (e.g. to resolve
                   1492:     # spoofing).
                   1493: 
                   1494:     my $cert = &GetCertificate($userinput);
1.412     foxr     1495:     if(&ValidManager($cert)) {
                   1496: 	&Debug("Valid manager: $client");
1.218     foxr     1497: 
                   1498: 	# Now presumably we have the bona fides of both the peer host and the
                   1499: 	# process making the request.
                   1500:       
                   1501: 	my $reply = &PushFile($userinput);
1.387     albertel 1502: 	&Reply($client, \$reply, $userinput);
1.218     foxr     1503: 
                   1504:     } else {
1.412     foxr     1505: 	&logthis("push_file_handler $client is not valid");
1.218     foxr     1506: 	&Failure( $client, "refused\n", $userinput);
                   1507:     } 
1.219     foxr     1508:     return 1;
1.218     foxr     1509: }
                   1510: &register_handler("pushfile", \&push_file_handler, 1, 0, 1);
                   1511: 
1.399     raeburn  1512: # The du_handler routine should be considered obsolete and is retained
                   1513: # for communication with legacy servers.  Please see the du2_handler.
1.243     banghart 1514: #
1.399     raeburn  1515: #   du  - list the disk usage of a directory recursively. 
1.243     banghart 1516: #    
                   1517: #   note: stolen code from the ls file handler
                   1518: #   under construction by Rick Banghart 
                   1519: #    .
                   1520: # Parameters:
                   1521: #    $cmd        - The command that dispatched us (du).
                   1522: #    $ududir     - The directory path to list... I'm not sure what this
                   1523: #                  is relative as things like ls:. return e.g.
                   1524: #                  no_such_dir.
                   1525: #    $client     - Socket open on the client.
                   1526: # Returns:
                   1527: #     1 - indicating that the daemon should not disconnect.
                   1528: # Side Effects:
                   1529: #   The reply is written to  $client.
                   1530: #
                   1531: sub du_handler {
                   1532:     my ($cmd, $ududir, $client) = @_;
1.339     albertel 1533:     ($ududir) = split(/:/,$ududir); # Make 'telnet' testing easier.
1.251     foxr     1534:     my $userinput = "$cmd:$ududir";
                   1535: 
1.245     albertel 1536:     if ($ududir=~/\.\./ || $ududir!~m|^/home/httpd/|) {
                   1537: 	&Failure($client,"refused\n","$cmd:$ududir");
                   1538: 	return 1;
                   1539:     }
1.249     foxr     1540:     #  Since $ududir could have some nasties in it,
                   1541:     #  we will require that ududir is a valid
                   1542:     #  directory.  Just in case someone tries to
                   1543:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
                   1544:     #  etc.
                   1545:     #
                   1546:     if (-d $ududir) {
1.292     albertel 1547: 	my $total_size=0;
                   1548: 	my $code=sub { 
                   1549: 	    if ($_=~/\.\d+\./) { return;} 
                   1550: 	    if ($_=~/\.meta$/) { return;}
1.362     albertel 1551: 	    if (-d $_)         { return;}
1.292     albertel 1552: 	    $total_size+=(stat($_))[7];
                   1553: 	};
1.295     raeburn  1554: 	chdir($ududir);
1.292     albertel 1555: 	find($code,$ududir);
                   1556: 	$total_size=int($total_size/1024);
1.387     albertel 1557: 	&Reply($client,\$total_size,"$cmd:$ududir");
1.249     foxr     1558:     } else {
1.251     foxr     1559: 	&Failure($client, "bad_directory:$ududir\n","$cmd:$ududir"); 
1.249     foxr     1560:     }
1.243     banghart 1561:     return 1;
                   1562: }
                   1563: &register_handler("du", \&du_handler, 0, 1, 0);
1.218     foxr     1564: 
1.399     raeburn  1565: # Please also see the du_handler, which is obsoleted by du2. 
                   1566: # du2_handler differs from du_handler in that required path to directory
                   1567: # provided by &propath() is prepended in the handler instead of on the 
                   1568: # client side.
1.239     foxr     1569: #
1.399     raeburn  1570: #   du2  - list the disk usage of a directory recursively.
                   1571: #
                   1572: # Parameters:
                   1573: #    $cmd        - The command that dispatched us (du).
                   1574: #    $tail       - The tail of the request that invoked us.
                   1575: #                  $tail is a : separated list of the following:
                   1576: #                   - $ududir - directory path to list (before prepending)
                   1577: #                   - $getpropath = 1 if &propath() should prepend
                   1578: #                   - $uname - username to use for &propath or user dir
                   1579: #                   - $udom - domain to use for &propath or user dir
                   1580: #                   All are escaped.
                   1581: #    $client     - Socket open on the client.
                   1582: # Returns:
                   1583: #     1 - indicating that the daemon should not disconnect.
                   1584: # Side Effects:
                   1585: #   The reply is written to $client.
                   1586: #
                   1587: 
                   1588: sub du2_handler {
                   1589:     my ($cmd, $tail, $client) = @_;
                   1590:     my ($ududir,$getpropath,$uname,$udom) = map { &unescape($_) } (split(/:/, $tail));
                   1591:     my $userinput = "$cmd:$tail";
                   1592:     if (($ududir=~/\.\./) || (($ududir!~m|^/home/httpd/|) && (!$getpropath))) {
                   1593:         &Failure($client,"refused\n","$cmd:$tail");
                   1594:         return 1;
                   1595:     }
                   1596:     if ($getpropath) {
                   1597:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
                   1598:             $ududir = &propath($udom,$uname).'/'.$ududir;
                   1599:         } else {
                   1600:             &Failure($client,"refused\n","$cmd:$tail");
                   1601:             return 1;
                   1602:         }
                   1603:     }
                   1604:     #  Since $ududir could have some nasties in it,
                   1605:     #  we will require that ududir is a valid
                   1606:     #  directory.  Just in case someone tries to
                   1607:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
                   1608:     #  etc.
                   1609:     #
                   1610:     if (-d $ududir) {
                   1611:         my $total_size=0;
                   1612:         my $code=sub {
                   1613:             if ($_=~/\.\d+\./) { return;}
                   1614:             if ($_=~/\.meta$/) { return;}
                   1615:             if (-d $_)         { return;}
                   1616:             $total_size+=(stat($_))[7];
                   1617:         };
                   1618:         chdir($ududir);
                   1619:         find($code,$ududir);
                   1620:         $total_size=int($total_size/1024);
                   1621:         &Reply($client,\$total_size,"$cmd:$ududir");
                   1622:     } else {
                   1623:         &Failure($client, "bad_directory:$ududir\n","$cmd:$tail");
                   1624:     }
                   1625:     return 1;
                   1626: }
                   1627: &register_handler("du2", \&du2_handler, 0, 1, 0);
                   1628: 
                   1629: #
                   1630: # The ls_handler routine should be considered obsolete and is retained
                   1631: # for communication with legacy servers.  Please see the ls3_handler.
1.280     matthew  1632: #
1.239     foxr     1633: #   ls  - list the contents of a directory.  For each file in the
                   1634: #    selected directory the filename followed by the full output of
                   1635: #    the stat function is returned.  The returned info for each
                   1636: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1637: #
                   1638: #    If the requested path contains /../ or is:
                   1639: #
                   1640: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1641: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1642: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1643: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
                   1644: #    or is:
                   1645: #
1.538     raeburn  1646: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1647: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1648: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1649: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
1.529     raeburn  1650: #
                   1651: #    the response will be "refused".
                   1652: #
1.239     foxr     1653: # Parameters:
                   1654: #    $cmd        - The command that dispatched us (ls).
                   1655: #    $ulsdir     - The directory path to list... I'm not sure what this
                   1656: #                  is relative as things like ls:. return e.g.
                   1657: #                  no_such_dir.
                   1658: #    $client     - Socket open on the client.
                   1659: # Returns:
                   1660: #     1 - indicating that the daemon should not disconnect.
                   1661: # Side Effects:
                   1662: #   The reply is written to  $client.
                   1663: #
                   1664: sub ls_handler {
1.280     matthew  1665:     # obsoleted by ls2_handler
1.239     foxr     1666:     my ($cmd, $ulsdir, $client) = @_;
                   1667: 
                   1668:     my $userinput = "$cmd:$ulsdir";
                   1669: 
                   1670:     my $obs;
                   1671:     my $rights;
                   1672:     my $ulsout='';
                   1673:     my $ulsfn;
1.529     raeburn  1674:     if ($ulsdir =~m{/\.\./}) {
                   1675:         &Failure($client,"refused\n",$userinput);
                   1676:         return 1;
                   1677:     }
1.239     foxr     1678:     if (-e $ulsdir) {
                   1679: 	if(-d $ulsdir) {
1.539     raeburn  1680:             unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1681:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
1.529     raeburn  1682:                 &Failure($client,"refused\n",$userinput);
                   1683:                 return 1;
                   1684:             }
1.239     foxr     1685: 	    if (opendir(LSDIR,$ulsdir)) {
                   1686: 		while ($ulsfn=readdir(LSDIR)) {
1.291     albertel 1687: 		    undef($obs);
                   1688: 		    undef($rights); 
1.239     foxr     1689: 		    my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1690: 		    #We do some obsolete checking here
                   1691: 		    if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   1692: 			open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1693: 			my @obsolete=<FILE>;
                   1694: 			foreach my $obsolete (@obsolete) {
1.301     www      1695: 			    if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
1.239     foxr     1696: 			    if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
                   1697: 			}
                   1698: 		    }
                   1699: 		    $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
                   1700: 		    if($obs eq '1') { $ulsout.="&1"; }
                   1701: 		    else { $ulsout.="&0"; }
                   1702: 		    if($rights eq '1') { $ulsout.="&1:"; }
                   1703: 		    else { $ulsout.="&0:"; }
                   1704: 		}
                   1705: 		closedir(LSDIR);
                   1706: 	    }
                   1707: 	} else {
1.539     raeburn  1708:             unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1709:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
1.529     raeburn  1710:                 &Failure($client,"refused\n",$userinput);
                   1711:                 return 1;
                   1712:             }
1.239     foxr     1713: 	    my @ulsstats=stat($ulsdir);
                   1714: 	    $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1715: 	}
                   1716:     } else {
                   1717: 	$ulsout='no_such_dir';
                   1718:     }
                   1719:     if ($ulsout eq '') { $ulsout='empty'; }
1.387     albertel 1720:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1.239     foxr     1721:     
                   1722:     return 1;
                   1723: 
                   1724: }
                   1725: &register_handler("ls", \&ls_handler, 0, 1, 0);
                   1726: 
1.399     raeburn  1727: # The ls2_handler routine should be considered obsolete and is retained
                   1728: # for communication with legacy servers.  Please see the ls3_handler.
                   1729: # Please also see the ls_handler, which was itself obsoleted by ls2.
1.280     matthew  1730: # ls2_handler differs from ls_handler in that it escapes its return 
                   1731: # values before concatenating them together with ':'s.
                   1732: #
                   1733: #   ls2  - list the contents of a directory.  For each file in the
                   1734: #    selected directory the filename followed by the full output of
                   1735: #    the stat function is returned.  The returned info for each
                   1736: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1737: #
                   1738: #    If the requested path contains /../ or is:
                   1739: #
                   1740: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1741: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1742: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1743: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
                   1744: #    or is:
                   1745: #
1.538     raeburn  1746: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1747: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1748: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1749: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
1.529     raeburn  1750: #
                   1751: #    the response will be "refused".
                   1752: #
1.280     matthew  1753: # Parameters:
                   1754: #    $cmd        - The command that dispatched us (ls).
                   1755: #    $ulsdir     - The directory path to list... I'm not sure what this
                   1756: #                  is relative as things like ls:. return e.g.
                   1757: #                  no_such_dir.
                   1758: #    $client     - Socket open on the client.
                   1759: # Returns:
                   1760: #     1 - indicating that the daemon should not disconnect.
                   1761: # Side Effects:
                   1762: #   The reply is written to  $client.
                   1763: #
                   1764: sub ls2_handler {
                   1765:     my ($cmd, $ulsdir, $client) = @_;
                   1766: 
                   1767:     my $userinput = "$cmd:$ulsdir";
                   1768: 
                   1769:     my $obs;
                   1770:     my $rights;
                   1771:     my $ulsout='';
                   1772:     my $ulsfn;
1.529     raeburn  1773:     if ($ulsdir =~m{/\.\./}) {
                   1774:         &Failure($client,"refused\n",$userinput);
                   1775:         return 1;
                   1776:     }
1.280     matthew  1777:     if (-e $ulsdir) {
                   1778:         if(-d $ulsdir) {
1.539     raeburn  1779:             unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1780:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
1.529     raeburn  1781:                 &Failure($client,"refused\n","$userinput");
                   1782:                 return 1;
                   1783:             }
1.280     matthew  1784:             if (opendir(LSDIR,$ulsdir)) {
                   1785:                 while ($ulsfn=readdir(LSDIR)) {
1.291     albertel 1786:                     undef($obs);
                   1787: 		    undef($rights); 
1.280     matthew  1788:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1789:                     #We do some obsolete checking here
                   1790:                     if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   1791:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1792:                         my @obsolete=<FILE>;
                   1793:                         foreach my $obsolete (@obsolete) {
1.301     www      1794:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
1.280     matthew  1795:                             if($obsolete =~ m|(<copyright>)(default)|) {
                   1796:                                 $rights = 1;
                   1797:                             }
                   1798:                         }
                   1799:                     }
                   1800:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
                   1801:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1802:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1803:                     $ulsout.= &escape($tmp).':';
                   1804:                 }
                   1805:                 closedir(LSDIR);
                   1806:             }
                   1807:         } else {
1.539     raeburn  1808:             unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1809:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
1.529     raeburn  1810:                 &Failure($client,"refused\n",$userinput);
                   1811:                 return 1;
                   1812:             }
1.280     matthew  1813:             my @ulsstats=stat($ulsdir);
                   1814:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1815:         }
                   1816:     } else {
                   1817:         $ulsout='no_such_dir';
                   1818:    }
                   1819:    if ($ulsout eq '') { $ulsout='empty'; }
1.387     albertel 1820:    &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1.280     matthew  1821:    return 1;
                   1822: }
                   1823: &register_handler("ls2", \&ls2_handler, 0, 1, 0);
1.399     raeburn  1824: #
                   1825: #   ls3  - list the contents of a directory.  For each file in the
                   1826: #    selected directory the filename followed by the full output of
                   1827: #    the stat function is returned.  The returned info for each
                   1828: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1829: #
                   1830: #    If the requested path (after prepending) contains /../ or is:
                   1831: #
                   1832: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1833: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1834: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1835: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
1.539     raeburn  1836: #        (d) /home/httpd/html/priv/<domain> and client is the homeserver
1.529     raeburn  1837: #
1.530     raeburn  1838: #    or is:
1.529     raeburn  1839: #
1.538     raeburn  1840: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1841: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1842: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1843: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
                   1844: #        (d) /home/httpd/html/priv/<domain>/<username>/ and client is the homeserver
1.529     raeburn  1845: #
                   1846: #    the response will be "refused".
                   1847: #
1.399     raeburn  1848: # Parameters:
                   1849: #    $cmd        - The command that dispatched us (ls).
                   1850: #    $tail       - The tail of the request that invoked us.
                   1851: #                  $tail is a : separated list of the following:
                   1852: #                   - $ulsdir - directory path to list (before prepending)
                   1853: #                   - $getpropath = 1 if &propath() should prepend
                   1854: #                   - $getuserdir = 1 if path to user dir in lonUsers should
                   1855: #                                     prepend
                   1856: #                   - $alternate_root - path to prepend
                   1857: #                   - $uname - username to use for &propath or user dir
                   1858: #                   - $udom - domain to use for &propath or user dir
                   1859: #            All of these except $getpropath and &getuserdir are escaped.    
                   1860: #                  no_such_dir.
                   1861: #    $client     - Socket open on the client.
                   1862: # Returns:
                   1863: #     1 - indicating that the daemon should not disconnect.
                   1864: # Side Effects:
                   1865: #   The reply is written to $client.
                   1866: #
                   1867: 
                   1868: sub ls3_handler {
                   1869:     my ($cmd, $tail, $client) = @_;
                   1870:     my $userinput = "$cmd:$tail";
                   1871:     my ($ulsdir,$getpropath,$getuserdir,$alternate_root,$uname,$udom) =
                   1872:         split(/:/,$tail);
                   1873:     if (defined($ulsdir)) {
                   1874:         $ulsdir = &unescape($ulsdir);
                   1875:     }
                   1876:     if (defined($alternate_root)) {
                   1877:         $alternate_root = &unescape($alternate_root);
                   1878:     }
                   1879:     if (defined($uname)) {
                   1880:         $uname = &unescape($uname);
                   1881:     }
                   1882:     if (defined($udom)) {
                   1883:         $udom = &unescape($udom);
                   1884:     }
                   1885: 
                   1886:     my $dir_root = $perlvar{'lonDocRoot'};
1.529     raeburn  1887:     if (($getpropath) || ($getuserdir)) {
1.399     raeburn  1888:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
                   1889:             $dir_root = &propath($udom,$uname);
                   1890:             $dir_root =~ s/\/$//;
                   1891:         } else {
1.529     raeburn  1892:             &Failure($client,"refused\n",$userinput);
1.399     raeburn  1893:             return 1;
                   1894:         }
1.400     raeburn  1895:     } elsif ($alternate_root ne '') {
1.399     raeburn  1896:         $dir_root = $alternate_root;
                   1897:     }
1.408     raeburn  1898:     if (($dir_root ne '') && ($dir_root ne '/')) {
1.400     raeburn  1899:         if ($ulsdir =~ /^\//) {
                   1900:             $ulsdir = $dir_root.$ulsdir;
                   1901:         } else {
                   1902:             $ulsdir = $dir_root.'/'.$ulsdir;
                   1903:         }
1.399     raeburn  1904:     }
1.529     raeburn  1905:     if ($ulsdir =~m{/\.\./}) {
                   1906:         &Failure($client,"refused\n",$userinput);
                   1907:         return 1;
                   1908:     }
                   1909:     my $islocal;
                   1910:     my @machine_ids = &Apache::lonnet::current_machine_ids();
                   1911:     if (grep(/^\Q$clientname\E$/,@machine_ids)) {
                   1912:         $islocal = 1;
                   1913:     }
1.399     raeburn  1914:     my $obs;
                   1915:     my $rights;
                   1916:     my $ulsout='';
                   1917:     my $ulsfn;
1.547     raeburn  1918: 
                   1919:     my ($crscheck,$toplevel,$currdom,$currnum,$skip);
                   1920:     unless ($islocal) {
                   1921:         my ($major,$minor) = split(/\./,$clientversion);
                   1922:         if (($major < 2) || ($major == 2 && $minor < 12)) {
                   1923:             $crscheck = 1;
                   1924:         }
                   1925:     }
1.399     raeburn  1926:     if (-e $ulsdir) {
                   1927:         if(-d $ulsdir) {
1.529     raeburn  1928:             unless (($getpropath) || ($getuserdir) ||
1.539     raeburn  1929:                     ($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1930:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles}) ||
                   1931:                     (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain}) && ($islocal))) {
1.529     raeburn  1932:                 &Failure($client,"refused\n",$userinput);
                   1933:                 return 1;
                   1934:             }
1.547     raeburn  1935:             if (($crscheck) &&
                   1936:                 ($ulsdir =~ m{^/home/httpd/html/res/($LONCAPA::match_domain)(/?$|/$LONCAPA::match_courseid)})) {
                   1937:                 ($currdom,my $posscnum) = ($1,$2);
                   1938:                 if (($posscnum eq '') || ($posscnum eq '/')) {
                   1939:                     $toplevel = 1;
                   1940:                 } else {
                   1941:                     $posscnum =~ s{^/+}{};
                   1942:                     if (&LONCAPA::Lond::is_course($currdom,$posscnum)) {
                   1943:                         $skip = 1;
                   1944:                     }
                   1945:                 }
                   1946:             }
                   1947:             if ((!$skip) && (opendir(LSDIR,$ulsdir))) {
1.399     raeburn  1948:                 while ($ulsfn=readdir(LSDIR)) {
1.547     raeburn  1949:                     if (($crscheck) && ($toplevel) && ($currdom ne '') &&
                   1950:                         ($ulsfn =~ /^$LONCAPA::match_courseid$/) && (-d "$ulsdir/$ulsfn")) {
                   1951:                         if (&LONCAPA::Lond::is_course($currdom,$ulsfn)) {
                   1952:                             next;
                   1953:                         }
                   1954:                     }
1.399     raeburn  1955:                     undef($obs);
                   1956:                     undef($rights);
                   1957:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1958:                     #We do some obsolete checking here
                   1959:                     if(-e $ulsdir.'/'.$ulsfn.".meta") {
                   1960:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1961:                         my @obsolete=<FILE>;
                   1962:                         foreach my $obsolete (@obsolete) {
                   1963:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; }
                   1964:                             if($obsolete =~ m|(<copyright>)(default)|) {
                   1965:                                 $rights = 1;
                   1966:                             }
                   1967:                         }
                   1968:                     }
                   1969:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
                   1970:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1971:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1972:                     $ulsout.= &escape($tmp).':';
                   1973:                 }
                   1974:                 closedir(LSDIR);
                   1975:             }
                   1976:         } else {
1.529     raeburn  1977:             unless (($getpropath) || ($getuserdir) ||
1.539     raeburn  1978:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1979:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/}) ||
                   1980:                     (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain/$LONCAPA::match_name/}) && ($islocal))) {
1.529     raeburn  1981:                 &Failure($client,"refused\n",$userinput);
                   1982:                 return 1;
                   1983:             }
1.399     raeburn  1984:             my @ulsstats=stat($ulsdir);
                   1985:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1986:         }
                   1987:     } else {
                   1988:         $ulsout='no_such_dir';
1.400     raeburn  1989:     }
                   1990:     if ($ulsout eq '') { $ulsout='empty'; }
                   1991:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
                   1992:     return 1;
1.399     raeburn  1993: }
                   1994: &register_handler("ls3", \&ls3_handler, 0, 1, 0);
1.280     matthew  1995: 
1.477     raeburn  1996: sub read_lonnet_global {
                   1997:     my ($cmd,$tail,$client) = @_;
                   1998:     my $userinput = "$cmd:$tail";
                   1999:     my $requested = &Apache::lonnet::thaw_unescape($tail);
                   2000:     my $result;
1.480     raeburn  2001:     my %packagevars = (
                   2002:                         spareid => \%Apache::lonnet::spareid,
                   2003:                         perlvar => \%Apache::lonnet::perlvar,
                   2004:                       );
                   2005:     my %limit_to = (
                   2006:                     perlvar => {
1.531     raeburn  2007:                                  lonOtherAuthen  => 1,
                   2008:                                  lonBalancer     => 1,
                   2009:                                  lonVersion      => 1,
                   2010:                                  lonAdmEMail     => 1,
                   2011:                                  lonSupportEMail => 1,  
                   2012:                                  lonSysEMail     => 1,
                   2013:                                  lonHostID       => 1,
                   2014:                                  lonRole         => 1,
                   2015:                                  lonDefDomain    => 1,
                   2016:                                  lonLoadLim      => 1,
                   2017:                                  lonUserLoadLim  => 1,
1.480     raeburn  2018:                                }
                   2019:                   );
1.477     raeburn  2020:     if (ref($requested) eq 'HASH') {
                   2021:         foreach my $what (keys(%{$requested})) {
                   2022:             my $response;
1.480     raeburn  2023:             my $items = {};
                   2024:             if (exists($packagevars{$what})) {
                   2025:                 if (ref($limit_to{$what}) eq 'HASH') {
                   2026:                     foreach my $varname (keys(%{$packagevars{$what}})) {
                   2027:                         if ($limit_to{$what}{$varname}) {
                   2028:                             $items->{$varname} = $packagevars{$what}{$varname};
                   2029:                         }
                   2030:                     }
                   2031:                 } else {
                   2032:                     $items = $packagevars{$what};
1.477     raeburn  2033:                 }
1.480     raeburn  2034:                 if ($what eq 'perlvar') {
                   2035:                     if (!exists($packagevars{$what}{'lonBalancer'})) {
1.559     raeburn  2036:                         if ($dist =~ /^(centos|rhes|fedora|scientific|oracle)/) {
1.480     raeburn  2037:                             my $othervarref=LONCAPA::Configuration::read_conf('httpd.conf');
                   2038:                             if (ref($othervarref) eq 'HASH') {
                   2039:                                 $items->{'lonBalancer'} = $othervarref->{'lonBalancer'};
                   2040:                             }
                   2041:                         }
                   2042:                     }
1.477     raeburn  2043:                 }
1.480     raeburn  2044:                 $response = &Apache::lonnet::freeze_escape($items);
1.477     raeburn  2045:             }
1.478     raeburn  2046:             $result .= &escape($what).'='.$response.'&';
1.477     raeburn  2047:         }
                   2048:     }
                   2049:     $result =~ s/\&$//;
                   2050:     &Reply($client,\$result,$userinput);
                   2051:     return 1;
                   2052: }
                   2053: &register_handler("readlonnetglobal", \&read_lonnet_global, 0, 1, 0);
                   2054: 
1.479     raeburn  2055: sub server_devalidatecache_handler {
                   2056:     my ($cmd,$tail,$client) = @_;
                   2057:     my $userinput = "$cmd:$tail";
1.503     raeburn  2058:     my $items = &unescape($tail);
                   2059:     my @cached = split(/\&/,$items);
                   2060:     foreach my $key (@cached) {
                   2061:         if ($key =~ /:/) {
                   2062:             my ($name,$id) = map { &unescape($_); } split(/:/,$key);
                   2063:             &Apache::lonnet::devalidate_cache_new($name,$id);
                   2064:         }
                   2065:     }
1.479     raeburn  2066:     my $result = 'ok';
                   2067:     &Reply($client,\$result,$userinput);
                   2068:     return 1;
                   2069: }
1.481     raeburn  2070: &register_handler("devalidatecache", \&server_devalidatecache_handler, 0, 1, 0);
1.479     raeburn  2071: 
1.410     raeburn  2072: sub server_timezone_handler {
                   2073:     my ($cmd,$tail,$client) = @_;
                   2074:     my $userinput = "$cmd:$tail";
                   2075:     my $timezone;
                   2076:     my $clockfile = '/etc/sysconfig/clock'; # Fedora/CentOS/SuSE
                   2077:     my $tzfile = '/etc/timezone'; # Debian/Ubuntu
                   2078:     if (-e $clockfile) {
                   2079:         if (open(my $fh,"<$clockfile")) {
                   2080:             while (<$fh>) {
                   2081:                 next if (/^[\#\s]/);
                   2082:                 if (/^(?:TIME)?ZONE\s*=\s*['"]?\s*([\w\/]+)/) {
                   2083:                     $timezone = $1;
                   2084:                     last;
                   2085:                 }
                   2086:             }
                   2087:             close($fh);
                   2088:         }
                   2089:     } elsif (-e $tzfile) {
                   2090:         if (open(my $fh,"<$tzfile")) {
                   2091:             $timezone = <$fh>;
                   2092:             close($fh);
                   2093:             chomp($timezone);
                   2094:             if ($timezone =~ m{^Etc/(\w+)$}) {
                   2095:                 $timezone = $1;
                   2096:             }
                   2097:         }
                   2098:     }
                   2099:     &Reply($client,\$timezone,$userinput); # This supports debug logging.
                   2100:     return 1;
                   2101: }
                   2102: &register_handler("servertimezone", \&server_timezone_handler, 0, 1, 0);
                   2103: 
1.413     raeburn  2104: sub server_loncaparev_handler {
                   2105:     my ($cmd,$tail,$client) = @_;
                   2106:     my $userinput = "$cmd:$tail";
                   2107:     &Reply($client,\$perlvar{'lonVersion'},$userinput);
                   2108:     return 1;
                   2109: }
                   2110: &register_handler("serverloncaparev", \&server_loncaparev_handler, 0, 1, 0);
                   2111: 
1.448     raeburn  2112: sub server_homeID_handler {
                   2113:     my ($cmd,$tail,$client) = @_;
                   2114:     my $userinput = "$cmd:$tail";
                   2115:     &Reply($client,\$perlvar{'lonHostID'},$userinput);
                   2116:     return 1;
                   2117: }
                   2118: &register_handler("serverhomeID", \&server_homeID_handler, 0, 1, 0);
                   2119: 
1.471     raeburn  2120: sub server_distarch_handler {
                   2121:     my ($cmd,$tail,$client) = @_;
                   2122:     my $userinput = "$cmd:$tail";
                   2123:     my $reply = &distro_and_arch();
                   2124:     &Reply($client,\$reply,$userinput);
                   2125:     return 1;
                   2126: }
                   2127: &register_handler("serverdistarch", \&server_distarch_handler, 0, 1, 0);
                   2128: 
1.523     raeburn  2129: sub server_certs_handler {
                   2130:     my ($cmd,$tail,$client) = @_;
                   2131:     my $userinput = "$cmd:$tail";
1.548     raeburn  2132:     my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
                   2133:     my $result = &LONCAPA::Lond::server_certs(\%perlvar,$perlvar{'lonHostID'},$hostname);
1.523     raeburn  2134:     &Reply($client,\$result,$userinput);
                   2135:     return;
                   2136: }
                   2137: &register_handler("servercerts", \&server_certs_handler, 0, 1, 0);
                   2138: 
1.218     foxr     2139: #   Process a reinit request.  Reinit requests that either
                   2140: #   lonc or lond be reinitialized so that an updated 
                   2141: #   host.tab or domain.tab can be processed.
                   2142: #
                   2143: # Parameters:
                   2144: #      $cmd    - the actual keyword that invoked us.
                   2145: #      $tail   - the tail of the request that invoked us.
                   2146: #      $client - File descriptor connected to the client
                   2147: #  Returns:
                   2148: #      1       - Ok to continue processing.
                   2149: #      0       - Program should exit
                   2150: #  Implicit output:
                   2151: #     a reply is sent to the client.
                   2152: #
                   2153: sub reinit_process_handler {
                   2154:     my ($cmd, $tail, $client) = @_;
                   2155:    
                   2156:     my $userinput = "$cmd:$tail";
                   2157:    
                   2158:     my $cert = &GetCertificate($userinput);
                   2159:     if(&ValidManager($cert)) {
                   2160: 	chomp($userinput);
                   2161: 	my $reply = &ReinitProcess($userinput);
1.387     albertel 2162: 	&Reply( $client,  \$reply, $userinput);
1.218     foxr     2163:     } else {
                   2164: 	&Failure( $client, "refused\n", $userinput);
                   2165:     }
                   2166:     return 1;
                   2167: }
                   2168: &register_handler("reinit", \&reinit_process_handler, 1, 0, 1);
                   2169: 
                   2170: #  Process the editing script for a table edit operation.
                   2171: #  the editing operation must be encrypted and requested by
                   2172: #  a manager host.
                   2173: #
                   2174: # Parameters:
                   2175: #      $cmd    - the actual keyword that invoked us.
                   2176: #      $tail   - the tail of the request that invoked us.
                   2177: #      $client - File descriptor connected to the client
                   2178: #  Returns:
                   2179: #      1       - Ok to continue processing.
                   2180: #      0       - Program should exit
                   2181: #  Implicit output:
                   2182: #     a reply is sent to the client.
                   2183: #
                   2184: sub edit_table_handler {
                   2185:     my ($command, $tail, $client) = @_;
                   2186:    
                   2187:     my $userinput = "$command:$tail";
                   2188: 
                   2189:     my $cert = &GetCertificate($userinput);
                   2190:     if(&ValidManager($cert)) {
                   2191: 	my($filetype, $script) = split(/:/, $tail);
                   2192: 	if (($filetype eq "hosts") || 
                   2193: 	    ($filetype eq "domain")) {
                   2194: 	    if($script ne "") {
                   2195: 		&Reply($client,              # BUGBUG - EditFile
                   2196: 		      &EditFile($userinput), #   could fail.
                   2197: 		      $userinput);
                   2198: 	    } else {
                   2199: 		&Failure($client,"refused\n",$userinput);
                   2200: 	    }
                   2201: 	} else {
                   2202: 	    &Failure($client,"refused\n",$userinput);
                   2203: 	}
                   2204:     } else {
                   2205: 	&Failure($client,"refused\n",$userinput);
                   2206:     }
                   2207:     return 1;
                   2208: }
1.263     albertel 2209: &register_handler("edit", \&edit_table_handler, 1, 0, 1);
1.218     foxr     2210: 
1.220     foxr     2211: #
                   2212: #   Authenticate a user against the LonCAPA authentication
                   2213: #   database.  Note that there are several authentication
                   2214: #   possibilities:
                   2215: #   - unix     - The user can be authenticated against the unix
                   2216: #                password file.
                   2217: #   - internal - The user can be authenticated against a purely 
                   2218: #                internal per user password file.
                   2219: #   - kerberos - The user can be authenticated against either a kerb4 or kerb5
                   2220: #                ticket granting authority.
                   2221: #   - user     - The person tailoring LonCAPA can supply a user authentication
                   2222: #                mechanism that is per system.
                   2223: #
                   2224: # Parameters:
                   2225: #    $cmd      - The command that got us here.
                   2226: #    $tail     - Tail of the command (remaining parameters).
                   2227: #    $client   - File descriptor connected to client.
                   2228: # Returns
                   2229: #     0        - Requested to exit, caller should shut down.
                   2230: #     1        - Continue processing.
                   2231: # Implicit inputs:
                   2232: #    The authentication systems describe above have their own forms of implicit
                   2233: #    input into the authentication process that are described above.
                   2234: #
                   2235: sub authenticate_handler {
                   2236:     my ($cmd, $tail, $client) = @_;
                   2237: 
                   2238:     
                   2239:     #  Regenerate the full input line 
                   2240:     
                   2241:     my $userinput  = $cmd.":".$tail;
                   2242:     
                   2243:     #  udom    - User's domain.
                   2244:     #  uname   - Username.
                   2245:     #  upass   - User's password.
1.396     raeburn  2246:     #  checkdefauth - Pass to validate_user() to try authentication
                   2247:     #                 with default auth type(s) if no user account.
1.447     raeburn  2248:     #  clientcancheckhost - Passed by clients with functionality in lonauth.pm
                   2249:     #                       to check if session can be hosted.
1.220     foxr     2250:     
1.447     raeburn  2251:     my ($udom, $uname, $upass, $checkdefauth, $clientcancheckhost)=split(/:/,$tail);
1.399     raeburn  2252:     &Debug(" Authenticate domain = $udom, user = $uname, password = $upass,  checkdefauth = $checkdefauth");
1.220     foxr     2253:     chomp($upass);
                   2254:     $upass=&unescape($upass);
                   2255: 
1.396     raeburn  2256:     my $pwdcorrect = &validate_user($udom,$uname,$upass,$checkdefauth);
1.220     foxr     2257:     if($pwdcorrect) {
1.447     raeburn  2258:         my $canhost = 1;
                   2259:         unless ($clientcancheckhost) {
1.448     raeburn  2260:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   2261:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.452     raeburn  2262:             my @intdoms;
                   2263:             my $internet_names = &Apache::lonnet::get_internet_names($clientname);
                   2264:             if (ref($internet_names) eq 'ARRAY') {
                   2265:                 @intdoms = @{$internet_names};
                   2266:             }
1.448     raeburn  2267:             unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
1.447     raeburn  2268:                 my ($remote,$hosted);
                   2269:                 my $remotesession = &get_usersession_config($udom,'remotesession');
                   2270:                 if (ref($remotesession) eq 'HASH') {
1.525     raeburn  2271:                     $remote = $remotesession->{'remote'};
1.447     raeburn  2272:                 }
1.448     raeburn  2273:                 my $hostedsession = &get_usersession_config($clienthomedom,'hostedsession');
1.447     raeburn  2274:                 if (ref($hostedsession) eq 'HASH') {
                   2275:                     $hosted = $hostedsession->{'hosted'};
                   2276:                 }
1.448     raeburn  2277:                 $canhost = &Apache::lonnet::can_host_session($udom,$clientname,
1.492     droeschl 2278:                                                              $clientversion,
1.447     raeburn  2279:                                                              $remote,$hosted);
                   2280:             }
                   2281:         }
                   2282:         if ($canhost) {               
                   2283:             &Reply( $client, "authorized\n", $userinput);
                   2284:         } else {
                   2285:             &Reply( $client, "not_allowed_to_host\n", $userinput);
                   2286:         }
1.220     foxr     2287: 	#
                   2288: 	#  Bad credentials: Failed to authorize
                   2289: 	#
                   2290:     } else {
                   2291: 	&Failure( $client, "non_authorized\n", $userinput);
                   2292:     }
                   2293: 
                   2294:     return 1;
                   2295: }
1.263     albertel 2296: &register_handler("auth", \&authenticate_handler, 1, 1, 0);
1.214     foxr     2297: 
1.222     foxr     2298: #
                   2299: #   Change a user's password.  Note that this function is complicated by
                   2300: #   the fact that a user may be authenticated in more than one way:
                   2301: #   At present, we are not able to change the password for all types of
                   2302: #   authentication methods.  Only for:
                   2303: #      unix    - unix password or shadow passoword style authentication.
                   2304: #      local   - Locally written authentication mechanism.
                   2305: #   For now, kerb4 and kerb5 password changes are not supported and result
                   2306: #   in an error.
                   2307: # FUTURE WORK:
                   2308: #    Support kerberos passwd changes?
                   2309: # Parameters:
                   2310: #    $cmd      - The command that got us here.
                   2311: #    $tail     - Tail of the command (remaining parameters).
                   2312: #    $client   - File descriptor connected to client.
                   2313: # Returns
                   2314: #     0        - Requested to exit, caller should shut down.
                   2315: #     1        - Continue processing.
                   2316: # Implicit inputs:
                   2317: #    The authentication systems describe above have their own forms of implicit
                   2318: #    input into the authentication process that are described above.
                   2319: sub change_password_handler {
                   2320:     my ($cmd, $tail, $client) = @_;
                   2321: 
                   2322:     my $userinput = $cmd.":".$tail;           # Reconstruct client's string.
                   2323: 
                   2324:     #
                   2325:     #  udom  - user's domain.
                   2326:     #  uname - Username.
                   2327:     #  upass - Current password.
                   2328:     #  npass - New password.
1.346     raeburn  2329:     #  context - Context in which this was called 
                   2330:     #            (preferences or reset_by_email).
1.428     raeburn  2331:     #  lonhost - HostID of server where request originated 
1.222     foxr     2332:    
1.428     raeburn  2333:     my ($udom,$uname,$upass,$npass,$context,$lonhost)=split(/:/,$tail);
1.222     foxr     2334: 
                   2335:     $upass=&unescape($upass);
                   2336:     $npass=&unescape($npass);
                   2337:     &Debug("Trying to change password for $uname");
                   2338: 
                   2339:     # First require that the user can be authenticated with their
1.346     raeburn  2340:     # old password unless context was 'reset_by_email':
                   2341:     
1.428     raeburn  2342:     my ($validated,$failure);
1.346     raeburn  2343:     if ($context eq 'reset_by_email') {
1.428     raeburn  2344:         if ($lonhost eq '') {
                   2345:             $failure = 'invalid_client';
                   2346:         } else {
                   2347:             $validated = 1;
                   2348:         }
1.346     raeburn  2349:     } else {
                   2350:         $validated = &validate_user($udom, $uname, $upass);
                   2351:     }
1.222     foxr     2352:     if($validated) {
                   2353: 	my $realpasswd  = &get_auth_type($udom, $uname); # Defined since authd.
                   2354: 	my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
1.558     raeburn  2355:         my $notunique;
1.222     foxr     2356: 	if ($howpwd eq 'internal') {
                   2357: 	    &Debug("internal auth");
1.518     raeburn  2358:             my $ncpass = &hash_passwd($udom,$npass);
1.558     raeburn  2359:             my (undef,$method,@rest) = split(/!/,$contentpwd);
                   2360:             if ($method eq 'bcrypt') {
                   2361:                 my %passwdconf = &Apache::lonnet::get_passwdconf($udom);
                   2362:                 if (($passwdconf{'numsaved'}) && ($passwdconf{'numsaved'} =~ /^\d+$/)) {
                   2363:                     my @oldpasswds;
                   2364:                     my $userpath = &propath($udom,$uname);
                   2365:                     my $fullpath = $userpath.'/oldpasswds';
                   2366:                     if (-d $userpath) {
                   2367:                         my @oldfiles;
                   2368:                         if (-e $fullpath) {
                   2369:                             if (opendir(my $dir,$fullpath)) {
                   2370:                                 (@oldfiles) = grep(/^\d+$/,readdir($dir));
                   2371:                                 closedir($dir);
                   2372:                             }
                   2373:                             if (@oldfiles) {
                   2374:                                 @oldfiles = sort { $b <=> $a } (@oldfiles);
                   2375:                                 my $numremoved = 0;
                   2376:                                 for (my $i=0; $i<@oldfiles; $i++) {
                   2377:                                     if ($i>=$passwdconf{'numsaved'}) {
                   2378:                                         if (-f "$fullpath/$oldfiles[$i]") {
                   2379:                                             if (unlink("$fullpath/$oldfiles[$i]")) {
                   2380:                                                 $numremoved ++;
                   2381:                                             }
                   2382:                                         }
                   2383:                                     } elsif (open(my $fh,'<',"$fullpath/$oldfiles[$i]")) {
                   2384:                                         while (my $line = <$fh>) {
                   2385:                                             push(@oldpasswds,$line);
                   2386:                                         }
                   2387:                                         close($fh);
                   2388:                                     }
                   2389:                                 }
                   2390:                                 if ($numremoved) {
                   2391:                                     &logthis("unlinked $numremoved old password files for $uname:$udom");
                   2392:                                 }
                   2393:                             }
                   2394:                         }
                   2395:                         push(@oldpasswds,$contentpwd);
                   2396:                         foreach my $item (@oldpasswds) {
                   2397:                             my (undef,$method,@rest) = split(/!/,$item);
                   2398:                             if ($method eq 'bcrypt') {
                   2399:                                 my $result = &hash_passwd($udom,$npass,@rest);
                   2400:                                 if ($result eq $item) {
                   2401:                                     $notunique = 1;
                   2402:                                     last;
                   2403:                                 }
                   2404:                             }
                   2405:                         }
                   2406:                         unless ($notunique) {
                   2407:                             unless (-e $fullpath) {
                   2408:                                 if (&mkpath("$fullpath/")) {
                   2409:                                     chmod(0700,$fullpath);
                   2410:                                 }
                   2411:                             }
                   2412:                             if (-d $fullpath) {
                   2413:                                 my $now = time;
                   2414:                                 if (open(my $fh,'>',"$fullpath/$now")) {
                   2415:                                     print $fh $contentpwd;
                   2416:                                     close($fh);
                   2417:                                     chmod(0400,"$fullpath/$now");
                   2418:                                 }
                   2419:                             }
                   2420:                         }
                   2421:                     }
                   2422:                 }
                   2423:             }
                   2424:             if ($notunique) {
                   2425:                 my $msg="Result of password change for $uname:$udom - password matches one used before";
                   2426:                 if ($lonhost) {
                   2427:                     $msg .= " - request originated from: $lonhost";
                   2428:                 }
                   2429:                 &logthis($msg);
                   2430:                 &Reply($client, "prioruse\n", $userinput);
                   2431: 	    } elsif (&rewrite_password_file($udom, $uname, "internal:$ncpass")) {
1.428     raeburn  2432: 		my $msg="Result of password change for $uname: pwchange_success";
                   2433:                 if ($lonhost) {
                   2434:                     $msg .= " - request originated from: $lonhost";
                   2435:                 }
                   2436:                 &logthis($msg);
1.518     raeburn  2437:                 &update_passwd_history($uname,$udom,$howpwd,$context);
1.222     foxr     2438: 		&Reply($client, "ok\n", $userinput);
                   2439: 	    } else {
                   2440: 		&logthis("Unable to open $uname passwd "               
                   2441: 			 ."to change password");
                   2442: 		&Failure( $client, "non_authorized\n",$userinput);
                   2443: 	    }
1.346     raeburn  2444: 	} elsif ($howpwd eq 'unix' && $context ne 'reset_by_email') {
1.287     foxr     2445: 	    my $result = &change_unix_password($uname, $npass);
1.518     raeburn  2446:             if ($result eq 'ok') {
                   2447:                 &update_passwd_history($uname,$udom,$howpwd,$context);
1.561     raeburn  2448:             }
1.222     foxr     2449: 	    &logthis("Result of password change for $uname: ".
1.287     foxr     2450: 		     $result);
1.387     albertel 2451: 	    &Reply($client, \$result, $userinput);
1.222     foxr     2452: 	} else {
                   2453: 	    # this just means that the current password mode is not
                   2454: 	    # one we know how to change (e.g the kerberos auth modes or
                   2455: 	    # locally written auth handler).
                   2456: 	    #
                   2457: 	    &Failure( $client, "auth_mode_error\n", $userinput);
                   2458: 	}  
1.224     foxr     2459:     } else {
1.428     raeburn  2460: 	if ($failure eq '') {
                   2461: 	    $failure = 'non_authorized';
                   2462: 	}
                   2463: 	&Failure( $client, "$failure\n", $userinput);
1.222     foxr     2464:     }
                   2465: 
                   2466:     return 1;
                   2467: }
1.263     albertel 2468: &register_handler("passwd", \&change_password_handler, 1, 1, 0);
1.222     foxr     2469: 
1.518     raeburn  2470: sub hash_passwd {
                   2471:     my ($domain,$plainpass,@rest) = @_;
                   2472:     my ($salt,$cost);
                   2473:     if (@rest) {
                   2474:         $cost = $rest[0];
                   2475:         # salt is first 22 characters, base-64 encoded by bcrypt
                   2476:         my $plainsalt = substr($rest[1],0,22);
                   2477:         $salt = Crypt::Eksblowfish::Bcrypt::de_base64($plainsalt);
                   2478:     } else {
1.533     raeburn  2479:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   2480:         my $defaultcost = $domdefaults{'intauth_cost'};
1.518     raeburn  2481:         if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
                   2482:             $cost = 10;
                   2483:         } else {
                   2484:             $cost = $defaultcost;
                   2485:         }
                   2486:         # Generate random 16-octet base64 salt
                   2487:         $salt = "";
                   2488:         $salt .= pack("C", int rand(256)) for 1..16;
                   2489:     }
                   2490:     my $hash = &Crypt::Eksblowfish::Bcrypt::bcrypt_hash({
                   2491:         key_nul => 1,
                   2492:         cost    => $cost,
                   2493:         salt    => $salt,
                   2494:     }, Digest::SHA::sha512(Encode::encode('UTF-8',$plainpass)));
                   2495: 
                   2496:     my $result = join("!", "", "bcrypt", sprintf("%02d",$cost),
                   2497:                 &Crypt::Eksblowfish::Bcrypt::en_base64($salt).
                   2498:                 &Crypt::Eksblowfish::Bcrypt::en_base64($hash));
                   2499:     return $result;
                   2500: }
                   2501: 
1.225     foxr     2502: #
                   2503: #   Create a new user.  User in this case means a lon-capa user.
                   2504: #   The user must either already exist in some authentication realm
                   2505: #   like kerberos or the /etc/passwd.  If not, a user completely local to
                   2506: #   this loncapa system is created.
                   2507: #
                   2508: # Parameters:
                   2509: #    $cmd      - The command that got us here.
                   2510: #    $tail     - Tail of the command (remaining parameters).
                   2511: #    $client   - File descriptor connected to client.
                   2512: # Returns
                   2513: #     0        - Requested to exit, caller should shut down.
                   2514: #     1        - Continue processing.
                   2515: # Implicit inputs:
                   2516: #    The authentication systems describe above have their own forms of implicit
                   2517: #    input into the authentication process that are described above.
                   2518: sub add_user_handler {
                   2519: 
                   2520:     my ($cmd, $tail, $client) = @_;
                   2521: 
                   2522: 
                   2523:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   2524:     my $userinput = $cmd.":".$tail; # Reconstruct the full request line.
                   2525: 
                   2526:     &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
                   2527: 
                   2528: 
                   2529:     if($udom eq $currentdomainid) { # Reject new users for other domains...
                   2530: 	
                   2531: 	my $oldumask=umask(0077);
                   2532: 	chomp($npass);
                   2533: 	$npass=&unescape($npass);
                   2534: 	my $passfilename  = &password_path($udom, $uname);
                   2535: 	&Debug("Password file created will be:".$passfilename);
                   2536: 	if (-e $passfilename) {
                   2537: 	    &Failure( $client, "already_exists\n", $userinput);
                   2538: 	} else {
                   2539: 	    my $fperror='';
1.264     albertel 2540: 	    if (!&mkpath($passfilename)) {
                   2541: 		$fperror="error: ".($!+0)." mkdir failed while attempting "
                   2542: 		    ."makeuser";
1.225     foxr     2543: 	    }
                   2544: 	    unless ($fperror) {
1.518     raeburn  2545: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
                   2546:                                              $passfilename,'makeuser');
1.390     raeburn  2547: 		&Reply($client,\$result, $userinput);     #BUGBUG - could be fail
1.225     foxr     2548: 	    } else {
1.387     albertel 2549: 		&Failure($client, \$fperror, $userinput);
1.225     foxr     2550: 	    }
                   2551: 	}
                   2552: 	umask($oldumask);
                   2553:     }  else {
                   2554: 	&Failure($client, "not_right_domain\n",
                   2555: 		$userinput);	# Even if we are multihomed.
                   2556:     
                   2557:     }
                   2558:     return 1;
                   2559: 
                   2560: }
                   2561: &register_handler("makeuser", \&add_user_handler, 1, 1, 0);
                   2562: 
                   2563: #
                   2564: #   Change the authentication method of a user.  Note that this may
                   2565: #   also implicitly change the user's password if, for example, the user is
                   2566: #   joining an existing authentication realm.  Known authentication realms at
                   2567: #   this time are:
                   2568: #    internal   - Purely internal password file (only loncapa knows this user)
                   2569: #    local      - Institutionally written authentication module.
                   2570: #    unix       - Unix user (/etc/passwd with or without /etc/shadow).
                   2571: #    kerb4      - kerberos version 4
                   2572: #    kerb5      - kerberos version 5
                   2573: #
                   2574: # Parameters:
                   2575: #    $cmd      - The command that got us here.
                   2576: #    $tail     - Tail of the command (remaining parameters).
                   2577: #    $client   - File descriptor connected to client.
                   2578: # Returns
                   2579: #     0        - Requested to exit, caller should shut down.
                   2580: #     1        - Continue processing.
                   2581: # Implicit inputs:
                   2582: #    The authentication systems describe above have their own forms of implicit
                   2583: #    input into the authentication process that are described above.
1.287     foxr     2584: # NOTE:
                   2585: #   This is also used to change the authentication credential values (e.g. passwd).
                   2586: #   
1.225     foxr     2587: #
                   2588: sub change_authentication_handler {
                   2589: 
                   2590:     my ($cmd, $tail, $client) = @_;
                   2591:    
                   2592:     my $userinput  = "$cmd:$tail";              # Reconstruct user input.
                   2593: 
                   2594:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   2595:     &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
                   2596:     if ($udom ne $currentdomainid) {
                   2597: 	&Failure( $client, "not_right_domain\n", $client);
                   2598:     } else {
                   2599: 	
                   2600: 	chomp($npass);
                   2601: 	
                   2602: 	$npass=&unescape($npass);
1.261     foxr     2603: 	my $oldauth = &get_auth_type($udom, $uname); # Get old auth info.
1.225     foxr     2604: 	my $passfilename = &password_path($udom, $uname);
                   2605: 	if ($passfilename) {	# Not allowed to create a new user!!
1.287     foxr     2606: 	    # If just changing the unix passwd. need to arrange to run
1.502     raeburn  2607: 	    # passwd since otherwise make_passwd_file will fail as 
                   2608: 	    # creation of unix authenticated users is no longer supported
                   2609:             # except from the command line, when running make_domain_coordinator.pl
1.287     foxr     2610: 
                   2611: 	    if(($oldauth =~/^unix/) && ($umode eq "unix")) {
                   2612: 		my $result = &change_unix_password($uname, $npass);
                   2613: 		&logthis("Result of password change for $uname: ".$result);
                   2614: 		if ($result eq "ok") {
1.518     raeburn  2615:                     &update_passwd_history($uname,$udom,$umode,'changeuserauth'); 
1.390     raeburn  2616: 		    &Reply($client, \$result);
1.288     albertel 2617: 		} else {
1.387     albertel 2618: 		    &Failure($client, \$result);
1.287     foxr     2619: 		}
1.288     albertel 2620: 	    } else {
1.518     raeburn  2621: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
                   2622:                                              $passfilename,'changeuserauth');
1.287     foxr     2623: 		#
                   2624: 		#  If the current auth mode is internal, and the old auth mode was
                   2625: 		#  unix, or krb*,  and the user is an author for this domain,
                   2626: 		#  re-run manage_permissions for that role in order to be able
                   2627: 		#  to take ownership of the construction space back to www:www
                   2628: 		#
1.502     raeburn  2629: 
                   2630: 
1.387     albertel 2631: 		&Reply($client, \$result, $userinput);
1.261     foxr     2632: 	    }
                   2633: 	       
                   2634: 
1.225     foxr     2635: 	} else {	       
1.251     foxr     2636: 	    &Failure($client, "non_authorized\n", $userinput); # Fail the user now.
1.225     foxr     2637: 	}
                   2638:     }
                   2639:     return 1;
                   2640: }
                   2641: &register_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
                   2642: 
1.518     raeburn  2643: sub update_passwd_history {
                   2644:     my ($uname,$udom,$umode,$context) = @_;
                   2645:     my $proname=&propath($udom,$uname);
                   2646:     my $now = time;
                   2647:     if (open(my $fh,">>$proname/passwd.log")) {
                   2648:         print $fh "$now:$umode:$context\n";
                   2649:         close($fh);
                   2650:     }
                   2651:     return;
                   2652: }
                   2653: 
1.225     foxr     2654: #
                   2655: #   Determines if this is the home server for a user.  The home server
                   2656: #   for a user will have his/her lon-capa passwd file.  Therefore all we need
                   2657: #   to do is determine if this file exists.
                   2658: #
                   2659: # Parameters:
                   2660: #    $cmd      - The command that got us here.
                   2661: #    $tail     - Tail of the command (remaining parameters).
                   2662: #    $client   - File descriptor connected to client.
                   2663: # Returns
                   2664: #     0        - Requested to exit, caller should shut down.
                   2665: #     1        - Continue processing.
                   2666: # Implicit inputs:
                   2667: #    The authentication systems describe above have their own forms of implicit
                   2668: #    input into the authentication process that are described above.
                   2669: #
                   2670: sub is_home_handler {
                   2671:     my ($cmd, $tail, $client) = @_;
                   2672:    
                   2673:     my $userinput  = "$cmd:$tail";
                   2674:    
                   2675:     my ($udom,$uname)=split(/:/,$tail);
                   2676:     chomp($uname);
                   2677:     my $passfile = &password_filename($udom, $uname);
                   2678:     if($passfile) {
                   2679: 	&Reply( $client, "found\n", $userinput);
                   2680:     } else {
                   2681: 	&Failure($client, "not_found\n", $userinput);
                   2682:     }
                   2683:     return 1;
                   2684: }
                   2685: &register_handler("home", \&is_home_handler, 0,1,0);
                   2686: 
                   2687: #
1.434     www      2688: #   Process an update request for a resource.
                   2689: #   A resource has been modified that we hold a subscription to.
1.225     foxr     2690: #   If the resource is not local, then we must update, or at least invalidate our
                   2691: #   cached copy of the resource. 
                   2692: # Parameters:
                   2693: #    $cmd      - The command that got us here.
                   2694: #    $tail     - Tail of the command (remaining parameters).
                   2695: #    $client   - File descriptor connected to client.
                   2696: # Returns
                   2697: #     0        - Requested to exit, caller should shut down.
                   2698: #     1        - Continue processing.
                   2699: # Implicit inputs:
                   2700: #    The authentication systems describe above have their own forms of implicit
                   2701: #    input into the authentication process that are described above.
                   2702: #
                   2703: sub update_resource_handler {
                   2704: 
                   2705:     my ($cmd, $tail, $client) = @_;
                   2706:    
                   2707:     my $userinput = "$cmd:$tail";
                   2708:    
                   2709:     my $fname= $tail;		# This allows interactive testing
                   2710: 
                   2711: 
                   2712:     my $ownership=ishome($fname);
                   2713:     if ($ownership eq 'not_owner') {
                   2714: 	if (-e $fname) {
1.434     www      2715:             # Delete preview file, if exists
                   2716:             unlink("$fname.tmp");
                   2717:             # Get usage stats
1.225     foxr     2718: 	    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
                   2719: 		$atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
                   2720: 	    my $now=time;
                   2721: 	    my $since=$now-$atime;
1.434     www      2722:             # If the file has not been used within lonExpire seconds,
                   2723:             # unsubscribe from it and delete local copy
1.225     foxr     2724: 	    if ($since>$perlvar{'lonExpire'}) {
1.365     albertel 2725: 		my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
1.308     albertel 2726: 		&devalidate_meta_cache($fname);
1.225     foxr     2727: 		unlink("$fname");
1.334     albertel 2728: 		unlink("$fname.meta");
1.225     foxr     2729: 	    } else {
1.434     www      2730:             # Yes, this is in active use. Get a fresh copy. Since it might be in
                   2731:             # very active use and huge (like a movie), copy it to "in.transfer" filename first.
1.225     foxr     2732: 		my $transname="$fname.in.transfer";
1.365     albertel 2733: 		my $remoteurl=&Apache::lonnet::reply("sub:$fname","$clientname");
1.225     foxr     2734: 		my $response;
1.537     raeburn  2735: # FIXME: cannot replicate files that take more than two minutes to transfer -- needs checking now 1200s timeout used
                   2736: # for LWP request.
                   2737: 		my $request=new HTTP::Request('GET',"$remoteurl");
                   2738:                 $response=&LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,0,1);
1.225     foxr     2739: 		if ($response->is_error()) {
1.541     raeburn  2740:                     my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
                   2741:                     &devalidate_meta_cache($fname);
                   2742:                     if (-e $transname) {
                   2743:                         unlink($transname);
                   2744:                     }
                   2745:                     unlink($fname);
1.225     foxr     2746: 		    my $message=$response->status_line;
                   2747: 		    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   2748: 		} else {
                   2749: 		    if ($remoteurl!~/\.meta$/) {
1.537     raeburn  2750: 			my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2751:                         my $mresponse = &LONCAPA::LWPReq::makerequest($clientname,$mrequest,$fname.'.meta',\%perlvar,120,0,1);
                   2752: 			if ($mresponse->is_error()) {
                   2753: 			    unlink($fname.'.meta');
1.225     foxr     2754: 			}
                   2755: 		    }
1.434     www      2756:                     # we successfully transfered, copy file over to real name
1.225     foxr     2757: 		    rename($transname,$fname);
1.308     albertel 2758: 		    &devalidate_meta_cache($fname);
1.225     foxr     2759: 		}
                   2760: 	    }
                   2761: 	    &Reply( $client, "ok\n", $userinput);
                   2762: 	} else {
                   2763: 	    &Failure($client, "not_found\n", $userinput);
                   2764: 	}
                   2765:     } else {
                   2766: 	&Failure($client, "rejected\n", $userinput);
                   2767:     }
                   2768:     return 1;
                   2769: }
                   2770: &register_handler("update", \&update_resource_handler, 0 ,1, 0);
                   2771: 
1.308     albertel 2772: sub devalidate_meta_cache {
                   2773:     my ($url) = @_;
                   2774:     use Cache::Memcached;
                   2775:     my $memcache = new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.365     albertel 2776:     $url = &Apache::lonnet::declutter($url);
1.308     albertel 2777:     $url =~ s-\.meta$--;
                   2778:     my $id = &escape('meta:'.$url);
                   2779:     $memcache->delete($id);
                   2780: }
                   2781: 
1.225     foxr     2782: #
1.226     foxr     2783: #   Fetch a user file from a remote server to the user's home directory
                   2784: #   userfiles subdir.
1.225     foxr     2785: # Parameters:
                   2786: #    $cmd      - The command that got us here.
                   2787: #    $tail     - Tail of the command (remaining parameters).
                   2788: #    $client   - File descriptor connected to client.
                   2789: # Returns
                   2790: #     0        - Requested to exit, caller should shut down.
                   2791: #     1        - Continue processing.
                   2792: #
                   2793: sub fetch_user_file_handler {
                   2794: 
                   2795:     my ($cmd, $tail, $client) = @_;
                   2796: 
                   2797:     my $userinput = "$cmd:$tail";
                   2798:     my $fname           = $tail;
1.232     foxr     2799:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
1.225     foxr     2800:     my $udir=&propath($udom,$uname).'/userfiles';
                   2801:     unless (-e $udir) {
                   2802: 	mkdir($udir,0770); 
                   2803:     }
1.232     foxr     2804:     Debug("fetch user file for $fname");
1.225     foxr     2805:     if (-e $udir) {
                   2806: 	$ufile=~s/^[\.\~]+//;
1.232     foxr     2807: 
                   2808: 	# IF necessary, create the path right down to the file.
                   2809: 	# Note that any regular files in the way of this path are
                   2810: 	# wiped out to deal with some earlier folly of mine.
                   2811: 
1.267     raeburn  2812: 	if (!&mkpath($udir.'/'.$ufile)) {
1.264     albertel 2813: 	    &Failure($client, "unable_to_create\n", $userinput);	    
1.232     foxr     2814: 	}
                   2815: 
1.225     foxr     2816: 	my $destname=$udir.'/'.$ufile;
                   2817: 	my $transname=$udir.'/'.$ufile.'.in.transit';
1.476     raeburn  2818:         my $clientprotocol=$Apache::lonnet::protocol{$clientname};
                   2819:         $clientprotocol = 'http' if ($clientprotocol ne 'https');
1.486     raeburn  2820: 	my $clienthost = &Apache::lonnet::hostname($clientname);
                   2821: 	my $remoteurl=$clientprotocol.'://'.$clienthost.'/userfiles/'.$fname;
1.225     foxr     2822: 	my $response;
1.232     foxr     2823: 	Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
1.537     raeburn  2824: 	my $request=new HTTP::Request('GET',"$remoteurl");
                   2825:         my $verifycert = 1;
                   2826:         my @machine_ids = &Apache::lonnet::current_machine_ids();
                   2827:         if (grep(/^\Q$clientname\E$/,@machine_ids)) {
                   2828:             $verifycert = 0;
                   2829:         }
                   2830:         $response = &LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,$verifycert);
1.225     foxr     2831: 	if ($response->is_error()) {
                   2832: 	    unlink($transname);
                   2833: 	    my $message=$response->status_line;
                   2834: 	    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   2835: 	    &Failure($client, "failed\n", $userinput);
                   2836: 	} else {
1.232     foxr     2837: 	    Debug("Renaming $transname to $destname");
1.225     foxr     2838: 	    if (!rename($transname,$destname)) {
                   2839: 		&logthis("Unable to move $transname to $destname");
                   2840: 		unlink($transname);
                   2841: 		&Failure($client, "failed\n", $userinput);
                   2842: 	    } else {
1.495     raeburn  2843:                 if ($fname =~ /^default.+\.(page|sequence)$/) {
                   2844:                     my ($major,$minor) = split(/\./,$clientversion);
                   2845:                     if (($major < 2) || ($major == 2 && $minor < 11)) {
                   2846:                         my $now = time;
                   2847:                         &Apache::lonnet::do_cache_new('crschange',$udom.'_'.$uname,$now,600);
                   2848:                         my $key = &escape('internal.contentchange');
                   2849:                         my $what = "$key=$now";
                   2850:                         my $hashref = &tie_user_hash($udom,$uname,'environment',
                   2851:                                                      &GDBM_WRCREAT(),"P",$what);
                   2852:                         if ($hashref) {
                   2853:                             $hashref->{$key}=$now;
                   2854:                             if (!&untie_user_hash($hashref)) {
                   2855:                                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
                   2856:                                          "when updating internal.contentchange");
                   2857:                             }
                   2858:                         }
                   2859:                     }
                   2860:                 }
1.225     foxr     2861: 		&Reply($client, "ok\n", $userinput);
                   2862: 	    }
                   2863: 	}   
                   2864:     } else {
                   2865: 	&Failure($client, "not_home\n", $userinput);
                   2866:     }
                   2867:     return 1;
                   2868: }
                   2869: &register_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
                   2870: 
1.226     foxr     2871: #
                   2872: #   Remove a file from a user's home directory userfiles subdirectory.
                   2873: # Parameters:
                   2874: #    cmd   - the Lond request keyword that got us here.
                   2875: #    tail  - the part of the command past the keyword.
                   2876: #    client- File descriptor connected with the client.
                   2877: #
                   2878: # Returns:
                   2879: #    1    - Continue processing.
                   2880: sub remove_user_file_handler {
                   2881:     my ($cmd, $tail, $client) = @_;
                   2882: 
                   2883:     my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2884: 
                   2885:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2886:     if ($ufile =~m|/\.\./|) {
                   2887: 	# any files paths with /../ in them refuse 
                   2888: 	# to deal with
                   2889: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2890:     } else {
                   2891: 	my $udir = &propath($udom,$uname);
                   2892: 	if (-e $udir) {
                   2893: 	    my $file=$udir.'/userfiles/'.$ufile;
                   2894: 	    if (-e $file) {
1.253     foxr     2895: 		#
                   2896: 		#   If the file is a regular file unlink is fine...
1.520     raeburn  2897: 		#   However it's possible the client wants a dir 
                   2898: 		#   removed, in which case rmdir is more appropriate.
                   2899: 		#   Note: rmdir will only remove an empty directory.
1.253     foxr     2900: 		#
1.240     banghart 2901: 	        if (-f $file){
1.241     albertel 2902: 		    unlink($file);
1.520     raeburn  2903:                     # for html files remove the associated .bak file 
                   2904:                     # which may have been created by the editor.
                   2905:                     if ($ufile =~ m{^((docs|supplemental)/(?:\d+|default)/\d+(?:|/.+)/)[^/]+\.x?html?$}i) {
                   2906:                         my $path = $1;
                   2907:                         if (-e $file.'.bak') {
                   2908:                             unlink($file.'.bak');
                   2909:                         }
                   2910:                     }
1.241     albertel 2911: 		} elsif(-d $file) {
                   2912: 		    rmdir($file);
1.240     banghart 2913: 		}
1.226     foxr     2914: 		if (-e $file) {
1.253     foxr     2915: 		    #  File is still there after we deleted it ?!?
                   2916: 
1.226     foxr     2917: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2918: 		} else {
                   2919: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2920: 		}
                   2921: 	    } else {
                   2922: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2923: 	    }
                   2924: 	} else {
                   2925: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2926: 	}
                   2927:     }
                   2928:     return 1;
                   2929: }
                   2930: &register_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
                   2931: 
1.236     albertel 2932: #
                   2933: #   make a directory in a user's home directory userfiles subdirectory.
                   2934: # Parameters:
                   2935: #    cmd   - the Lond request keyword that got us here.
                   2936: #    tail  - the part of the command past the keyword.
                   2937: #    client- File descriptor connected with the client.
                   2938: #
                   2939: # Returns:
                   2940: #    1    - Continue processing.
                   2941: sub mkdir_user_file_handler {
                   2942:     my ($cmd, $tail, $client) = @_;
                   2943: 
                   2944:     my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2945:     $dir=&unescape($dir);
                   2946:     my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2947:     if ($ufile =~m|/\.\./|) {
                   2948: 	# any files paths with /../ in them refuse 
                   2949: 	# to deal with
                   2950: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2951:     } else {
                   2952: 	my $udir = &propath($udom,$uname);
                   2953: 	if (-e $udir) {
1.264     albertel 2954: 	    my $newdir=$udir.'/userfiles/'.$ufile.'/';
                   2955: 	    if (!&mkpath($newdir)) {
                   2956: 		&Failure($client, "failed\n", "$cmd:$tail");
1.236     albertel 2957: 	    }
1.264     albertel 2958: 	    &Reply($client, "ok\n", "$cmd:$tail");
1.236     albertel 2959: 	} else {
                   2960: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2961: 	}
                   2962:     }
                   2963:     return 1;
                   2964: }
                   2965: &register_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
                   2966: 
1.237     albertel 2967: #
                   2968: #   rename a file in a user's home directory userfiles subdirectory.
                   2969: # Parameters:
                   2970: #    cmd   - the Lond request keyword that got us here.
                   2971: #    tail  - the part of the command past the keyword.
                   2972: #    client- File descriptor connected with the client.
                   2973: #
                   2974: # Returns:
                   2975: #    1    - Continue processing.
                   2976: sub rename_user_file_handler {
                   2977:     my ($cmd, $tail, $client) = @_;
                   2978: 
                   2979:     my ($udom,$uname,$old,$new) = split(/:/, $tail);
                   2980:     $old=&unescape($old);
                   2981:     $new=&unescape($new);
                   2982:     if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
                   2983: 	# any files paths with /../ in them refuse to deal with
                   2984: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2985:     } else {
                   2986: 	my $udir = &propath($udom,$uname);
                   2987: 	if (-e $udir) {
                   2988: 	    my $oldfile=$udir.'/userfiles/'.$old;
                   2989: 	    my $newfile=$udir.'/userfiles/'.$new;
                   2990: 	    if (-e $newfile) {
                   2991: 		&Failure($client, "exists\n", "$cmd:$tail");
                   2992: 	    } elsif (! -e $oldfile) {
                   2993: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2994: 	    } else {
                   2995: 		if (!rename($oldfile,$newfile)) {
                   2996: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2997: 		} else {
                   2998: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2999: 		}
                   3000: 	    }
                   3001: 	} else {
                   3002: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   3003: 	}
                   3004:     }
                   3005:     return 1;
                   3006: }
                   3007: &register_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
                   3008: 
1.227     foxr     3009: #
1.382     albertel 3010: #  Checks if the specified user has an active session on the server
                   3011: #  return ok if so, not_found if not
                   3012: #
                   3013: # Parameters:
                   3014: #   cmd      - The request keyword that dispatched to tus.
                   3015: #   tail     - The tail of the request (colon separated parameters).
                   3016: #   client   - Filehandle open on the client.
                   3017: # Return:
                   3018: #    1.
                   3019: sub user_has_session_handler {
                   3020:     my ($cmd, $tail, $client) = @_;
                   3021: 
                   3022:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
                   3023:     
                   3024:     opendir(DIR,$perlvar{'lonIDsDir'});
                   3025:     my $filename;
                   3026:     while ($filename=readdir(DIR)) {
                   3027: 	last if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/);
                   3028:     }
                   3029:     if ($filename) {
                   3030: 	&Reply($client, "ok\n", "$cmd:$tail");
                   3031:     } else {
                   3032: 	&Failure($client, "not_found\n", "$cmd:$tail");
                   3033:     }
                   3034:     return 1;
                   3035: 
                   3036: }
                   3037: &register_handler("userhassession", \&user_has_session_handler, 0,1,0);
                   3038: 
1.560     raeburn  3039: sub del_usersession_handler {
                   3040:     my ($cmd, $tail, $client) = @_;
                   3041: 
                   3042:     my $result;
                   3043:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
                   3044:     if (($udom =~ /^$LONCAPA::match_domain$/) && ($uname =~ /^$LONCAPA::match_username$/)) {
                   3045:         my $lonidsdir = $perlvar{'lonIDsDir'};
                   3046:         if (-d $lonidsdir) {
                   3047:             if (opendir(DIR,$lonidsdir)) {
                   3048:                 my $filename;
                   3049:                 while ($filename=readdir(DIR)) {
                   3050:                     if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/) {
                   3051:                         if (tie(my %oldenv,'GDBM_File',"$lonidsdir/$filename",
                   3052:                                 &GDBM_READER(),0640)) {
                   3053:                             my $linkedfile;
                   3054:                             if (exists($oldenv{'user.linkedenv'})) {
                   3055:                                 $linkedfile = $oldenv{'user.linkedenv'};
                   3056:                             }
                   3057:                             untie(%oldenv);
                   3058:                             $result = unlink("$lonidsdir/$filename");
                   3059:                             if ($result) {
                   3060:                                 if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   3061:                                     if (-l "$lonidsdir/$linkedfile.id") {
                   3062:                                         unlink("$lonidsdir/$linkedfile.id");
                   3063:                                     }
                   3064:                                 }
                   3065:                             }
                   3066:                         } else {
                   3067:                             $result = unlink("$lonidsdir/$filename");
                   3068:                         }
                   3069:                         last;
                   3070:                     }
                   3071:                 }
                   3072:             }
                   3073:         }
                   3074:         if ($result == 1) {
                   3075:             &Reply($client, "$result\n", "$cmd:$tail");
                   3076:         } else {
                   3077:             &Reply($client, "not_found\n", "$cmd:$tail");
                   3078:         }
                   3079:     } else {
                   3080:         &Failure($client, "invalid_user\n", "$cmd:$tail");
                   3081:     }
                   3082:     return 1;
                   3083: }
                   3084: 
                   3085: &register_handler("delusersession", \&del_usersession_handler, 0,1,0);
                   3086: 
1.382     albertel 3087: #
1.263     albertel 3088: #  Authenticate access to a user file by checking that the token the user's 
                   3089: #  passed also exists in their session file
1.227     foxr     3090: #
                   3091: # Parameters:
                   3092: #   cmd      - The request keyword that dispatched to tus.
                   3093: #   tail     - The tail of the request (colon separated parameters).
                   3094: #   client   - Filehandle open on the client.
                   3095: # Return:
                   3096: #    1.
                   3097: sub token_auth_user_file_handler {
                   3098:     my ($cmd, $tail, $client) = @_;
                   3099: 
                   3100:     my ($fname, $session) = split(/:/, $tail);
                   3101:     
                   3102:     chomp($session);
1.393     raeburn  3103:     my $reply="non_auth";
1.343     albertel 3104:     my $file = $perlvar{'lonIDsDir'}.'/'.$session.'.id';
                   3105:     if (open(ENVIN,"$file")) {
1.332     albertel 3106: 	flock(ENVIN,LOCK_SH);
1.343     albertel 3107: 	tie(my %disk_env,'GDBM_File',"$file",&GDBM_READER(),0640);
                   3108: 	if (exists($disk_env{"userfile.$fname"})) {
1.393     raeburn  3109: 	    $reply="ok";
1.343     albertel 3110: 	} else {
                   3111: 	    foreach my $envname (keys(%disk_env)) {
                   3112: 		if ($envname=~ m|^userfile\.\Q$fname\E|) {
1.393     raeburn  3113: 		    $reply="ok";
1.343     albertel 3114: 		    last;
                   3115: 		}
                   3116: 	    }
1.227     foxr     3117: 	}
1.343     albertel 3118: 	untie(%disk_env);
1.227     foxr     3119: 	close(ENVIN);
1.387     albertel 3120: 	&Reply($client, \$reply, "$cmd:$tail");
1.227     foxr     3121:     } else {
                   3122: 	&Failure($client, "invalid_token\n", "$cmd:$tail");
                   3123:     }
                   3124:     return 1;
                   3125: 
                   3126: }
                   3127: &register_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
1.229     foxr     3128: 
                   3129: #
                   3130: #   Unsubscribe from a resource.
                   3131: #
                   3132: # Parameters:
                   3133: #    $cmd      - The command that got us here.
                   3134: #    $tail     - Tail of the command (remaining parameters).
                   3135: #    $client   - File descriptor connected to client.
                   3136: # Returns
                   3137: #     0        - Requested to exit, caller should shut down.
                   3138: #     1        - Continue processing.
                   3139: #
                   3140: sub unsubscribe_handler {
                   3141:     my ($cmd, $tail, $client) = @_;
                   3142: 
                   3143:     my $userinput= "$cmd:$tail";
                   3144:     
                   3145:     my ($fname) = split(/:/,$tail); # Split in case there's extrs.
                   3146: 
                   3147:     &Debug("Unsubscribing $fname");
                   3148:     if (-e $fname) {
                   3149: 	&Debug("Exists");
                   3150: 	&Reply($client, &unsub($fname,$clientip), $userinput);
                   3151:     } else {
                   3152: 	&Failure($client, "not_found\n", $userinput);
                   3153:     }
                   3154:     return 1;
                   3155: }
                   3156: &register_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
1.263     albertel 3157: 
1.230     foxr     3158: #   Subscribe to a resource
                   3159: #
                   3160: # Parameters:
                   3161: #    $cmd      - The command that got us here.
                   3162: #    $tail     - Tail of the command (remaining parameters).
                   3163: #    $client   - File descriptor connected to client.
                   3164: # Returns
                   3165: #     0        - Requested to exit, caller should shut down.
                   3166: #     1        - Continue processing.
                   3167: #
                   3168: sub subscribe_handler {
                   3169:     my ($cmd, $tail, $client)= @_;
                   3170: 
                   3171:     my $userinput  = "$cmd:$tail";
                   3172: 
                   3173:     &Reply( $client, &subscribe($userinput,$clientip), $userinput);
                   3174: 
                   3175:     return 1;
                   3176: }
                   3177: &register_handler("sub", \&subscribe_handler, 0, 1, 0);
                   3178: 
                   3179: #
1.379     albertel 3180: #   Determine the latest version of a resource (it looks for the highest
                   3181: #   past version and then returns that +1)
1.230     foxr     3182: #
                   3183: # Parameters:
                   3184: #    $cmd      - The command that got us here.
                   3185: #    $tail     - Tail of the command (remaining parameters).
1.379     albertel 3186: #                 (Should consist of an absolute path to a file)
1.230     foxr     3187: #    $client   - File descriptor connected to client.
                   3188: # Returns
                   3189: #     0        - Requested to exit, caller should shut down.
                   3190: #     1        - Continue processing.
                   3191: #
                   3192: sub current_version_handler {
                   3193:     my ($cmd, $tail, $client) = @_;
                   3194: 
                   3195:     my $userinput= "$cmd:$tail";
                   3196:    
                   3197:     my $fname   = $tail;
                   3198:     &Reply( $client, &currentversion($fname)."\n", $userinput);
                   3199:     return 1;
                   3200: 
                   3201: }
                   3202: &register_handler("currentversion", \&current_version_handler, 0, 1, 0);
                   3203: 
                   3204: #  Make an entry in a user's activity log.
                   3205: #
                   3206: # Parameters:
                   3207: #    $cmd      - The command that got us here.
                   3208: #    $tail     - Tail of the command (remaining parameters).
                   3209: #    $client   - File descriptor connected to client.
                   3210: # Returns
                   3211: #     0        - Requested to exit, caller should shut down.
                   3212: #     1        - Continue processing.
                   3213: #
                   3214: sub activity_log_handler {
                   3215:     my ($cmd, $tail, $client) = @_;
                   3216: 
                   3217: 
                   3218:     my $userinput= "$cmd:$tail";
                   3219: 
                   3220:     my ($udom,$uname,$what)=split(/:/,$tail);
                   3221:     chomp($what);
                   3222:     my $proname=&propath($udom,$uname);
                   3223:     my $now=time;
                   3224:     my $hfh;
                   3225:     if ($hfh=IO::File->new(">>$proname/activity.log")) { 
                   3226: 	print $hfh "$now:$clientname:$what\n";
                   3227: 	&Reply( $client, "ok\n", $userinput); 
                   3228:     } else {
                   3229: 	&Failure($client, "error: ".($!+0)." IO::File->new Failed "
                   3230: 		 ."while attempting log\n", 
                   3231: 		 $userinput);
                   3232:     }
                   3233: 
                   3234:     return 1;
                   3235: }
1.263     albertel 3236: &register_handler("log", \&activity_log_handler, 0, 1, 0);
1.230     foxr     3237: 
                   3238: #
                   3239: #   Put a namespace entry in a user profile hash.
                   3240: #   My druthers would be for this to be an encrypted interaction too.
                   3241: #   anything that might be an inadvertent covert channel about either
                   3242: #   user authentication or user personal information....
                   3243: #
                   3244: # Parameters:
                   3245: #    $cmd      - The command that got us here.
                   3246: #    $tail     - Tail of the command (remaining parameters).
                   3247: #    $client   - File descriptor connected to client.
                   3248: # Returns
                   3249: #     0        - Requested to exit, caller should shut down.
                   3250: #     1        - Continue processing.
                   3251: #
                   3252: sub put_user_profile_entry {
                   3253:     my ($cmd, $tail, $client)  = @_;
1.229     foxr     3254: 
1.230     foxr     3255:     my $userinput = "$cmd:$tail";
                   3256:     
1.242     raeburn  3257:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
1.230     foxr     3258:     if ($namespace ne 'roles') {
                   3259: 	chomp($what);
                   3260: 	my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3261: 				  &GDBM_WRCREAT(),"P",$what);
                   3262: 	if($hashref) {
                   3263: 	    my @pairs=split(/\&/,$what);
                   3264: 	    foreach my $pair (@pairs) {
                   3265: 		my ($key,$value)=split(/=/,$pair);
                   3266: 		$hashref->{$key}=$value;
                   3267: 	    }
1.311     albertel 3268: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     3269: 		&Reply( $client, "ok\n", $userinput);
                   3270: 	    } else {
                   3271: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3272: 			"while attempting put\n", 
                   3273: 			$userinput);
                   3274: 	    }
                   3275: 	} else {
1.316     albertel 3276: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.230     foxr     3277: 		     "while attempting put\n", $userinput);
                   3278: 	}
                   3279:     } else {
                   3280:         &Failure( $client, "refused\n", $userinput);
                   3281:     }
                   3282:     
                   3283:     return 1;
                   3284: }
                   3285: &register_handler("put", \&put_user_profile_entry, 0, 1, 0);
                   3286: 
1.283     albertel 3287: #   Put a piece of new data in hash, returns error if entry already exists
                   3288: # Parameters:
                   3289: #    $cmd      - The command that got us here.
                   3290: #    $tail     - Tail of the command (remaining parameters).
                   3291: #    $client   - File descriptor connected to client.
                   3292: # Returns
                   3293: #     0        - Requested to exit, caller should shut down.
                   3294: #     1        - Continue processing.
                   3295: #
                   3296: sub newput_user_profile_entry {
                   3297:     my ($cmd, $tail, $client)  = @_;
                   3298: 
                   3299:     my $userinput = "$cmd:$tail";
                   3300: 
                   3301:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
                   3302:     if ($namespace eq 'roles') {
                   3303:         &Failure( $client, "refused\n", $userinput);
                   3304: 	return 1;
                   3305:     }
                   3306: 
                   3307:     chomp($what);
                   3308: 
                   3309:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3310: 				 &GDBM_WRCREAT(),"N",$what);
                   3311:     if(!$hashref) {
1.316     albertel 3312: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.283     albertel 3313: 		  "while attempting put\n", $userinput);
                   3314: 	return 1;
                   3315:     }
                   3316: 
                   3317:     my @pairs=split(/\&/,$what);
                   3318:     foreach my $pair (@pairs) {
                   3319: 	my ($key,$value)=split(/=/,$pair);
                   3320: 	if (exists($hashref->{$key})) {
1.513     raeburn  3321:             if (!&untie_user_hash($hashref)) {
                   3322:                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
                   3323:                          "while attempting newput - early out as key exists");
                   3324:             }
                   3325:             &Failure($client, "key_exists: ".$key."\n",$userinput);
                   3326:             return 1;
1.283     albertel 3327: 	}
                   3328:     }
                   3329: 
                   3330:     foreach my $pair (@pairs) {
                   3331: 	my ($key,$value)=split(/=/,$pair);
                   3332: 	$hashref->{$key}=$value;
                   3333:     }
                   3334: 
1.311     albertel 3335:     if (&untie_user_hash($hashref)) {
1.283     albertel 3336: 	&Reply( $client, "ok\n", $userinput);
                   3337:     } else {
                   3338: 	&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3339: 		 "while attempting put\n", 
                   3340: 		 $userinput);
                   3341:     }
                   3342:     return 1;
                   3343: }
                   3344: &register_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
                   3345: 
1.230     foxr     3346: # 
                   3347: #   Increment a profile entry in the user history file.
                   3348: #   The history contains keyword value pairs.  In this case,
                   3349: #   The value itself is a pair of numbers.  The first, the current value
                   3350: #   the second an increment that this function applies to the current
                   3351: #   value.
                   3352: #
                   3353: # Parameters:
                   3354: #    $cmd      - The command that got us here.
                   3355: #    $tail     - Tail of the command (remaining parameters).
                   3356: #    $client   - File descriptor connected to client.
                   3357: # Returns
                   3358: #     0        - Requested to exit, caller should shut down.
                   3359: #     1        - Continue processing.
                   3360: #
                   3361: sub increment_user_value_handler {
                   3362:     my ($cmd, $tail, $client) = @_;
                   3363:     
                   3364:     my $userinput   = "$cmd:$tail";
                   3365:     
                   3366:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
                   3367:     if ($namespace ne 'roles') {
                   3368:         chomp($what);
                   3369: 	my $hashref = &tie_user_hash($udom, $uname,
                   3370: 				     $namespace, &GDBM_WRCREAT(),
                   3371: 				     "P",$what);
                   3372: 	if ($hashref) {
                   3373: 	    my @pairs=split(/\&/,$what);
                   3374: 	    foreach my $pair (@pairs) {
                   3375: 		my ($key,$value)=split(/=/,$pair);
1.284     raeburn  3376:                 $value = &unescape($value);
1.230     foxr     3377: 		# We could check that we have a number...
                   3378: 		if (! defined($value) || $value eq '') {
                   3379: 		    $value = 1;
                   3380: 		}
                   3381: 		$hashref->{$key}+=$value;
1.284     raeburn  3382:                 if ($namespace eq 'nohist_resourcetracker') {
                   3383:                     if ($hashref->{$key} < 0) {
                   3384:                         $hashref->{$key} = 0;
                   3385:                     }
                   3386:                 }
1.230     foxr     3387: 	    }
1.311     albertel 3388: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     3389: 		&Reply( $client, "ok\n", $userinput);
                   3390: 	    } else {
                   3391: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3392: 			 "while attempting inc\n", $userinput);
                   3393: 	    }
                   3394: 	} else {
                   3395: 	    &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3396: 		     "while attempting inc\n", $userinput);
                   3397: 	}
                   3398:     } else {
                   3399: 	&Failure($client, "refused\n", $userinput);
                   3400:     }
                   3401:     
                   3402:     return 1;
                   3403: }
                   3404: &register_handler("inc", \&increment_user_value_handler, 0, 1, 0);
                   3405: 
                   3406: #
                   3407: #   Put a new role for a user.  Roles are LonCAPA's packaging of permissions.
                   3408: #   Each 'role' a user has implies a set of permissions.  Adding a new role
                   3409: #   for a person grants the permissions packaged with that role
                   3410: #   to that user when the role is selected.
                   3411: #
                   3412: # Parameters:
                   3413: #    $cmd       - The command string (rolesput).
                   3414: #    $tail      - The remainder of the request line.  For rolesput this
                   3415: #                 consists of a colon separated list that contains:
                   3416: #                 The domain and user that is granting the role (logged).
                   3417: #                 The domain and user that is getting the role.
                   3418: #                 The roles being granted as a set of & separated pairs.
                   3419: #                 each pair a key value pair.
                   3420: #    $client    - File descriptor connected to the client.
                   3421: # Returns:
                   3422: #     0         - If the daemon should exit
                   3423: #     1         - To continue processing.
                   3424: #
                   3425: #
                   3426: sub roles_put_handler {
                   3427:     my ($cmd, $tail, $client) = @_;
                   3428: 
                   3429:     my $userinput  = "$cmd:$tail";
                   3430: 
                   3431:     my ( $exedom, $exeuser, $udom, $uname,  $what) = split(/:/,$tail);
                   3432:     
                   3433: 
                   3434:     my $namespace='roles';
                   3435:     chomp($what);
                   3436:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3437: 				 &GDBM_WRCREAT(), "P",
                   3438: 				 "$exedom:$exeuser:$what");
                   3439:     #
                   3440:     #  Log the attempt to set a role.  The {}'s here ensure that the file 
                   3441:     #  handle is open for the minimal amount of time.  Since the flush
                   3442:     #  is done on close this improves the chances the log will be an un-
                   3443:     #  corrupted ordered thing.
                   3444:     if ($hashref) {
1.261     foxr     3445: 	my $pass_entry = &get_auth_type($udom, $uname);
                   3446: 	my ($auth_type,$pwd)  = split(/:/, $pass_entry);
                   3447: 	$auth_type = $auth_type.":";
1.230     foxr     3448: 	my @pairs=split(/\&/,$what);
                   3449: 	foreach my $pair (@pairs) {
                   3450: 	    my ($key,$value)=split(/=/,$pair);
                   3451: 	    &manage_permissions($key, $udom, $uname,
1.260     foxr     3452: 			       $auth_type);
1.230     foxr     3453: 	    $hashref->{$key}=$value;
                   3454: 	}
1.311     albertel 3455: 	if (&untie_user_hash($hashref)) {
1.230     foxr     3456: 	    &Reply($client, "ok\n", $userinput);
                   3457: 	} else {
                   3458: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3459: 		     "while attempting rolesput\n", $userinput);
                   3460: 	}
                   3461:     } else {
                   3462: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3463: 		 "while attempting rolesput\n", $userinput);
                   3464:     }
                   3465:     return 1;
                   3466: }
                   3467: &register_handler("rolesput", \&roles_put_handler, 1,1,0);  # Encoded client only.
                   3468: 
                   3469: #
1.231     foxr     3470: #   Deletes (removes) a role for a user.   This is equivalent to removing
                   3471: #  a permissions package associated with the role from the user's profile.
                   3472: #
                   3473: # Parameters:
                   3474: #     $cmd                 - The command (rolesdel)
                   3475: #     $tail                - The remainder of the request line. This consists
                   3476: #                             of:
                   3477: #                             The domain and user requesting the change (logged)
                   3478: #                             The domain and user being changed.
                   3479: #                             The roles being revoked.  These are shipped to us
                   3480: #                             as a bunch of & separated role name keywords.
                   3481: #     $client              - The file handle open on the client.
                   3482: # Returns:
                   3483: #     1                    - Continue processing
                   3484: #     0                    - Exit.
                   3485: #
                   3486: sub roles_delete_handler {
                   3487:     my ($cmd, $tail, $client)  = @_;
                   3488: 
                   3489:     my $userinput    = "$cmd:$tail";
                   3490:    
                   3491:     my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
                   3492:     &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
                   3493: 	   "what = ".$what);
                   3494:     my $namespace='roles';
                   3495:     chomp($what);
                   3496:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3497: 				 &GDBM_WRCREAT(), "D",
                   3498: 				 "$exedom:$exeuser:$what");
                   3499:     
                   3500:     if ($hashref) {
                   3501: 	my @rolekeys=split(/\&/,$what);
                   3502: 	
                   3503: 	foreach my $key (@rolekeys) {
                   3504: 	    delete $hashref->{$key};
                   3505: 	}
1.315     albertel 3506: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3507: 	    &Reply($client, "ok\n", $userinput);
                   3508: 	} else {
                   3509: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3510: 		     "while attempting rolesdel\n", $userinput);
                   3511: 	}
                   3512:     } else {
                   3513:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3514: 		 "while attempting rolesdel\n", $userinput);
                   3515:     }
                   3516:     
                   3517:     return 1;
                   3518: }
                   3519: &register_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
                   3520: 
                   3521: # Unencrypted get from a user's profile database.  See 
                   3522: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
                   3523: # This function retrieves a keyed item from a specific named database in the
                   3524: # user's directory.
                   3525: #
                   3526: # Parameters:
                   3527: #   $cmd             - Command request keyword (get).
                   3528: #   $tail            - Tail of the command.  This is a colon separated list
                   3529: #                      consisting of the domain and username that uniquely
                   3530: #                      identifies the profile,
                   3531: #                      The 'namespace' which selects the gdbm file to 
                   3532: #                      do the lookup in, 
                   3533: #                      & separated list of keys to lookup.  Note that
                   3534: #                      the values are returned as an & separated list too.
                   3535: #   $client          - File descriptor open on the client.
                   3536: # Returns:
                   3537: #   1       - Continue processing.
                   3538: #   0       - Exit.
                   3539: #
                   3540: sub get_profile_entry {
                   3541:     my ($cmd, $tail, $client) = @_;
                   3542: 
                   3543:     my $userinput= "$cmd:$tail";
                   3544:    
                   3545:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   3546:     chomp($what);
1.255     foxr     3547: 
1.390     raeburn  3548: 
1.255     foxr     3549:     my $replystring = read_profile($udom, $uname, $namespace, $what);
                   3550:     my ($first) = split(/:/,$replystring);
                   3551:     if($first ne "error") {
1.387     albertel 3552: 	&Reply($client, \$replystring, $userinput);
1.231     foxr     3553:     } else {
1.255     foxr     3554: 	&Failure($client, $replystring." while attempting get\n", $userinput);
1.231     foxr     3555:     }
                   3556:     return 1;
1.255     foxr     3557: 
                   3558: 
1.231     foxr     3559: }
                   3560: &register_handler("get", \&get_profile_entry, 0,1,0);
                   3561: 
                   3562: #
                   3563: #  Process the encrypted get request.  Note that the request is sent
                   3564: #  in clear, but the reply is encrypted.  This is a small covert channel:
                   3565: #  information about the sensitive keys is given to the snooper.  Just not
                   3566: #  information about the values of the sensitive key.  Hmm if I wanted to
                   3567: #  know these I'd snoop for the egets. Get the profile item names from them
                   3568: #  and then issue a get for them since there's no enforcement of the
                   3569: #  requirement of an encrypted get for particular profile items.  If I
                   3570: #  were re-doing this, I'd force the request to be encrypted as well as the
                   3571: #  reply.  I'd also just enforce encrypted transactions for all gets since
                   3572: #  that would prevent any covert channel snooping.
                   3573: #
                   3574: #  Parameters:
                   3575: #     $cmd               - Command keyword of request (eget).
1.536     raeburn  3576: #     $tail              - Tail of the command.  See GetProfileEntry
                   3577: #                          for more information about this.
1.231     foxr     3578: #     $client            - File open on the client.
                   3579: #  Returns:
                   3580: #     1      - Continue processing
                   3581: #     0      - server should exit.
                   3582: sub get_profile_entry_encrypted {
                   3583:     my ($cmd, $tail, $client) = @_;
                   3584: 
                   3585:     my $userinput = "$cmd:$tail";
                   3586:    
1.339     albertel 3587:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
1.231     foxr     3588:     chomp($what);
1.255     foxr     3589:     my $qresult = read_profile($udom, $uname, $namespace, $what);
                   3590:     my ($first) = split(/:/, $qresult);
                   3591:     if($first ne "error") {
                   3592: 	
                   3593: 	if ($cipher) {
                   3594: 	    my $cmdlength=length($qresult);
                   3595: 	    $qresult.="         ";
                   3596: 	    my $encqresult='';
                   3597: 	    for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   3598: 		$encqresult.= unpack("H16", 
                   3599: 				     $cipher->encrypt(substr($qresult,
                   3600: 							     $encidx,
                   3601: 							     8)));
                   3602: 	    }
                   3603: 	    &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
                   3604: 	} else {
1.231     foxr     3605: 		&Failure( $client, "error:no_key\n", $userinput);
                   3606: 	    }
                   3607:     } else {
1.255     foxr     3608: 	&Failure($client, "$qresult while attempting eget\n", $userinput);
                   3609: 
1.231     foxr     3610:     }
                   3611:     
                   3612:     return 1;
                   3613: }
1.255     foxr     3614: &register_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
1.263     albertel 3615: 
1.231     foxr     3616: #
                   3617: #   Deletes a key in a user profile database.
                   3618: #   
                   3619: #   Parameters:
                   3620: #       $cmd                  - Command keyword (del).
                   3621: #       $tail                 - Command tail.  IN this case a colon
                   3622: #                               separated list containing:
                   3623: #                               The domain and user that identifies uniquely
                   3624: #                               the identity of the user.
                   3625: #                               The profile namespace (name of the profile
                   3626: #                               database file).
                   3627: #                               & separated list of keywords to delete.
                   3628: #       $client              - File open on client socket.
                   3629: # Returns:
                   3630: #     1   - Continue processing
                   3631: #     0   - Exit server.
                   3632: #
                   3633: #
                   3634: sub delete_profile_entry {
                   3635:     my ($cmd, $tail, $client) = @_;
                   3636: 
                   3637:     my $userinput = "cmd:$tail";
                   3638: 
                   3639:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   3640:     chomp($what);
                   3641:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3642: 				 &GDBM_WRCREAT(),
                   3643: 				 "D",$what);
                   3644:     if ($hashref) {
                   3645:         my @keys=split(/\&/,$what);
                   3646: 	foreach my $key (@keys) {
                   3647: 	    delete($hashref->{$key});
                   3648: 	}
1.315     albertel 3649: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3650: 	    &Reply($client, "ok\n", $userinput);
                   3651: 	} else {
                   3652: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3653: 		    "while attempting del\n", $userinput);
                   3654: 	}
                   3655:     } else {
                   3656: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3657: 		 "while attempting del\n", $userinput);
                   3658:     }
                   3659:     return 1;
                   3660: }
                   3661: &register_handler("del", \&delete_profile_entry, 0, 1, 0);
1.263     albertel 3662: 
1.231     foxr     3663: #
                   3664: #  List the set of keys that are defined in a profile database file.
                   3665: #  A successful reply from this will contain an & separated list of
                   3666: #  the keys. 
                   3667: # Parameters:
                   3668: #     $cmd              - Command request (keys).
                   3669: #     $tail             - Remainder of the request, a colon separated
                   3670: #                         list containing domain/user that identifies the
                   3671: #                         user being queried, and the database namespace
                   3672: #                         (database filename essentially).
                   3673: #     $client           - File open on the client.
                   3674: #  Returns:
                   3675: #    1    - Continue processing.
                   3676: #    0    - Exit the server.
                   3677: #
                   3678: sub get_profile_keys {
                   3679:     my ($cmd, $tail, $client) = @_;
                   3680: 
                   3681:     my $userinput = "$cmd:$tail";
                   3682: 
                   3683:     my ($udom,$uname,$namespace)=split(/:/,$tail);
                   3684:     my $qresult='';
                   3685:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3686: 				  &GDBM_READER());
                   3687:     if ($hashref) {
                   3688: 	foreach my $key (keys %$hashref) {
                   3689: 	    $qresult.="$key&";
                   3690: 	}
1.315     albertel 3691: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3692: 	    $qresult=~s/\&$//;
1.387     albertel 3693: 	    &Reply($client, \$qresult, $userinput);
1.231     foxr     3694: 	} else {
                   3695: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3696: 		    "while attempting keys\n", $userinput);
                   3697: 	}
                   3698:     } else {
                   3699: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3700: 		 "while attempting keys\n", $userinput);
                   3701:     }
                   3702:    
                   3703:     return 1;
                   3704: }
                   3705: &register_handler("keys", \&get_profile_keys, 0, 1, 0);
                   3706: 
                   3707: #
                   3708: #   Dump the contents of a user profile database.
                   3709: #   Note that this constitutes a very large covert channel too since
                   3710: #   the dump will return sensitive information that is not encrypted.
                   3711: #   The naive security assumption is that the session negotiation ensures
                   3712: #   our client is trusted and I don't believe that's assured at present.
                   3713: #   Sure want badly to go to ssl or tls.  Of course if my peer isn't really
                   3714: #   a LonCAPA node they could have negotiated an encryption key too so >sigh<.
                   3715: # 
                   3716: #  Parameters:
                   3717: #     $cmd           - The command request keyword (currentdump).
                   3718: #     $tail          - Remainder of the request, consisting of a colon
                   3719: #                      separated list that has the domain/username and
                   3720: #                      the namespace to dump (database file).
                   3721: #     $client        - file open on the remote client.
                   3722: # Returns:
                   3723: #     1    - Continue processing.
                   3724: #     0    - Exit the server.
                   3725: #
                   3726: sub dump_profile_database {
                   3727:     my ($cmd, $tail, $client) = @_;
                   3728: 
1.494     droeschl 3729:     my $res = LONCAPA::Lond::dump_profile_database($tail);
                   3730: 
                   3731:     if ($res =~ /^error:/) {
                   3732:         Failure($client, \$res, "$cmd:$tail");
                   3733:     } else {
                   3734:         Reply($client, \$res, "$cmd:$tail");
                   3735:     }
                   3736: 
                   3737:     return 1;  
                   3738: 
                   3739:     #TODO remove 
1.231     foxr     3740:     my $userinput = "$cmd:$tail";
                   3741:    
                   3742:     my ($udom,$uname,$namespace) = split(/:/,$tail);
                   3743:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3744: 				 &GDBM_READER());
                   3745:     if ($hashref) {
                   3746: 	# Structure of %data:
                   3747: 	# $data{$symb}->{$parameter}=$value;
                   3748: 	# $data{$symb}->{'v.'.$parameter}=$version;
                   3749: 	# since $parameter will be unescaped, we do not
                   3750:  	# have to worry about silly parameter names...
                   3751: 	
                   3752:         my $qresult='';
                   3753: 	my %data = ();                     # A hash of anonymous hashes..
                   3754: 	while (my ($key,$value) = each(%$hashref)) {
                   3755: 	    my ($v,$symb,$param) = split(/:/,$key);
                   3756: 	    next if ($v eq 'version' || $symb eq 'keys');
                   3757: 	    next if (exists($data{$symb}) && 
                   3758: 		     exists($data{$symb}->{$param}) &&
                   3759: 		     $data{$symb}->{'v.'.$param} > $v);
                   3760: 	    $data{$symb}->{$param}=$value;
                   3761: 	    $data{$symb}->{'v.'.$param}=$v;
                   3762: 	}
1.311     albertel 3763: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3764: 	    while (my ($symb,$param_hash) = each(%data)) {
                   3765: 		while(my ($param,$value) = each (%$param_hash)){
                   3766: 		    next if ($param =~ /^v\./);       # Ignore versions...
                   3767: 		    #
                   3768: 		    #   Just dump the symb=value pairs separated by &
                   3769: 		    #
                   3770: 		    $qresult.=$symb.':'.$param.'='.$value.'&';
                   3771: 		}
                   3772: 	    }
                   3773: 	    chop($qresult);
1.387     albertel 3774: 	    &Reply($client , \$qresult, $userinput);
1.231     foxr     3775: 	} else {
                   3776: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3777: 		     "while attempting currentdump\n", $userinput);
                   3778: 	}
                   3779:     } else {
                   3780: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3781: 		"while attempting currentdump\n", $userinput);
                   3782:     }
                   3783: 
                   3784:     return 1;
                   3785: }
                   3786: &register_handler("currentdump", \&dump_profile_database, 0, 1, 0);
                   3787: 
                   3788: #
                   3789: #   Dump a profile database with an optional regular expression
                   3790: #   to match against the keys.  In this dump, no effort is made
                   3791: #   to separate symb from version information. Presumably the
                   3792: #   databases that are dumped by this command are of a different
                   3793: #   structure.  Need to look at this and improve the documentation of
                   3794: #   both this and the currentdump handler.
                   3795: # Parameters:
                   3796: #    $cmd                     - The command keyword.
                   3797: #    $tail                    - All of the characters after the $cmd:
                   3798: #                               These are expected to be a colon
                   3799: #                               separated list containing:
                   3800: #                               domain/user - identifying the user.
                   3801: #                               namespace   - identifying the database.
                   3802: #                               regexp      - optional regular expression
                   3803: #                                             that is matched against
                   3804: #                                             database keywords to do
                   3805: #                                             selective dumps.
1.488     raeburn  3806: #                               range       - optional range of entries
                   3807: #                                             e.g., 10-20 would return the
                   3808: #                                             10th to 19th items, etc.  
1.231     foxr     3809: #   $client                   - Channel open on the client.
                   3810: # Returns:
                   3811: #    1    - Continue processing.
                   3812: # Side effects:
                   3813: #    response is written to $client.
                   3814: #
                   3815: sub dump_with_regexp {
                   3816:     my ($cmd, $tail, $client) = @_;
                   3817: 
1.494     droeschl 3818:     my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
1.490     droeschl 3819:     
                   3820:     if ($res =~ /^error:/) {
                   3821:         Failure($client, \$res, "$cmd:$tail");
                   3822:     } else {
                   3823:         Reply($client, \$res, "$cmd:$tail");
                   3824:     }
1.231     foxr     3825: 
                   3826:     return 1;
                   3827: }
                   3828: &register_handler("dump", \&dump_with_regexp, 0, 1, 0);
                   3829: 
                   3830: #  Store a set of key=value pairs associated with a versioned name.
                   3831: #
                   3832: #  Parameters:
                   3833: #    $cmd                - Request command keyword.
                   3834: #    $tail               - Tail of the request.  This is a colon
                   3835: #                          separated list containing:
                   3836: #                          domain/user - User and authentication domain.
                   3837: #                          namespace   - Name of the database being modified
                   3838: #                          rid         - Resource keyword to modify.
                   3839: #                          what        - new value associated with rid.
1.512     raeburn  3840: #                          laststore   - (optional) version=timestamp
                   3841: #                                        for most recent transaction for rid
                   3842: #                                        in namespace, when cstore was called
1.231     foxr     3843: #
                   3844: #    $client             - Socket open on the client.
                   3845: #
                   3846: #
                   3847: #  Returns:
                   3848: #      1 (keep on processing).
                   3849: #  Side-Effects:
                   3850: #    Writes to the client
1.512     raeburn  3851: #    Successful storage will cause either 'ok', or, if $laststore was included
                   3852: #    in the tail of the request, and the version number for the last transaction
                   3853: #    is larger than the version in $laststore, delay:$numtrans , where $numtrans
                   3854: #    is the number of store evevnts recorded for rid in namespace since
                   3855: #    lonnet::store() was called by the client.
                   3856: #
1.231     foxr     3857: sub store_handler {
                   3858:     my ($cmd, $tail, $client) = @_;
                   3859:  
                   3860:     my $userinput = "$cmd:$tail";
1.512     raeburn  3861:     chomp($tail);
                   3862:     my ($udom,$uname,$namespace,$rid,$what,$laststore) =split(/:/,$tail);
1.231     foxr     3863:     if ($namespace ne 'roles') {
                   3864: 
                   3865: 	my @pairs=split(/\&/,$what);
                   3866: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
1.268     albertel 3867: 				       &GDBM_WRCREAT(), "S",
1.231     foxr     3868: 				       "$rid:$what");
                   3869: 	if ($hashref) {
                   3870: 	    my $now = time;
1.512     raeburn  3871:             my $numtrans;
                   3872:             if ($laststore) {
                   3873:                 my ($previousversion,$previoustime) = split(/\=/,$laststore);
                   3874:                 my ($lastversion,$lasttime) = (0,0);
                   3875:                 $lastversion = $hashref->{"version:$rid"};
                   3876:                 if ($lastversion) {
                   3877:                     $lasttime = $hashref->{"$lastversion:$rid:timestamp"};
                   3878:                 }
                   3879:                 if (($previousversion) && ($previousversion !~ /\D/)) {
                   3880:                     if (($lastversion > $previousversion) && ($lasttime >= $previoustime)) {
                   3881:                         $numtrans = $lastversion - $previousversion;
                   3882:                     }
                   3883:                 } elsif ($lastversion) {
                   3884:                     $numtrans = $lastversion;
                   3885:                 }
                   3886:                 if ($numtrans) {
                   3887:                     $numtrans =~ s/D//g;
                   3888:                 }
                   3889:             }
1.231     foxr     3890: 	    $hashref->{"version:$rid"}++;
                   3891: 	    my $version=$hashref->{"version:$rid"};
                   3892: 	    my $allkeys=''; 
                   3893: 	    foreach my $pair (@pairs) {
                   3894: 		my ($key,$value)=split(/=/,$pair);
                   3895: 		$allkeys.=$key.':';
                   3896: 		$hashref->{"$version:$rid:$key"}=$value;
                   3897: 	    }
                   3898: 	    $hashref->{"$version:$rid:timestamp"}=$now;
                   3899: 	    $allkeys.='timestamp';
                   3900: 	    $hashref->{"$version:keys:$rid"}=$allkeys;
1.311     albertel 3901: 	    if (&untie_user_hash($hashref)) {
1.512     raeburn  3902:                 my $msg = 'ok';
                   3903:                 if ($numtrans) {
                   3904:                     $msg = 'delay:'.$numtrans;
                   3905:                 }
                   3906: 		&Reply($client, "$msg\n", $userinput);
1.231     foxr     3907: 	    } else {
                   3908: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3909: 			"while attempting store\n", $userinput);
                   3910: 	    }
                   3911: 	} else {
                   3912: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3913: 		     "while attempting store\n", $userinput);
                   3914: 	}
                   3915:     } else {
                   3916: 	&Failure($client, "refused\n", $userinput);
                   3917:     }
                   3918: 
                   3919:     return 1;
                   3920: }
                   3921: &register_handler("store", \&store_handler, 0, 1, 0);
1.263     albertel 3922: 
1.323     albertel 3923: #  Modify a set of key=value pairs associated with a versioned name.
                   3924: #
                   3925: #  Parameters:
                   3926: #    $cmd                - Request command keyword.
                   3927: #    $tail               - Tail of the request.  This is a colon
                   3928: #                          separated list containing:
                   3929: #                          domain/user - User and authentication domain.
                   3930: #                          namespace   - Name of the database being modified
                   3931: #                          rid         - Resource keyword to modify.
                   3932: #                          v           - Version item to modify
                   3933: #                          what        - new value associated with rid.
                   3934: #
                   3935: #    $client             - Socket open on the client.
                   3936: #
                   3937: #
                   3938: #  Returns:
                   3939: #      1 (keep on processing).
                   3940: #  Side-Effects:
                   3941: #    Writes to the client
                   3942: sub putstore_handler {
                   3943:     my ($cmd, $tail, $client) = @_;
                   3944:  
                   3945:     my $userinput = "$cmd:$tail";
                   3946: 
                   3947:     my ($udom,$uname,$namespace,$rid,$v,$what) =split(/:/,$tail);
                   3948:     if ($namespace ne 'roles') {
                   3949: 
                   3950: 	chomp($what);
                   3951: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
                   3952: 				       &GDBM_WRCREAT(), "M",
                   3953: 				       "$rid:$v:$what");
                   3954: 	if ($hashref) {
                   3955: 	    my $now = time;
                   3956: 	    my %data = &hash_extract($what);
                   3957: 	    my @allkeys;
                   3958: 	    while (my($key,$value) = each(%data)) {
                   3959: 		push(@allkeys,$key);
                   3960: 		$hashref->{"$v:$rid:$key"} = $value;
                   3961: 	    }
                   3962: 	    my $allkeys = join(':',@allkeys);
                   3963: 	    $hashref->{"$v:keys:$rid"}=$allkeys;
                   3964: 
                   3965: 	    if (&untie_user_hash($hashref)) {
                   3966: 		&Reply($client, "ok\n", $userinput);
                   3967: 	    } else {
                   3968: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3969: 			"while attempting store\n", $userinput);
                   3970: 	    }
                   3971: 	} else {
                   3972: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3973: 		     "while attempting store\n", $userinput);
                   3974: 	}
                   3975:     } else {
                   3976: 	&Failure($client, "refused\n", $userinput);
                   3977:     }
                   3978: 
                   3979:     return 1;
                   3980: }
                   3981: &register_handler("putstore", \&putstore_handler, 0, 1, 0);
                   3982: 
                   3983: sub hash_extract {
                   3984:     my ($str)=@_;
                   3985:     my %hash;
                   3986:     foreach my $pair (split(/\&/,$str)) {
                   3987: 	my ($key,$value)=split(/=/,$pair);
                   3988: 	$hash{$key}=$value;
                   3989:     }
                   3990:     return (%hash);
                   3991: }
                   3992: sub hash_to_str {
                   3993:     my ($hash_ref)=@_;
                   3994:     my $str;
                   3995:     foreach my $key (keys(%$hash_ref)) {
                   3996: 	$str.=$key.'='.$hash_ref->{$key}.'&';
                   3997:     }
                   3998:     $str=~s/\&$//;
                   3999:     return $str;
                   4000: }
                   4001: 
1.231     foxr     4002: #
                   4003: #  Dump out all versions of a resource that has key=value pairs associated
                   4004: # with it for each version.  These resources are built up via the store
                   4005: # command.
                   4006: #
                   4007: #  Parameters:
                   4008: #     $cmd               - Command keyword.
                   4009: #     $tail              - Remainder of the request which consists of:
                   4010: #                          domain/user   - User and auth. domain.
                   4011: #                          namespace     - name of resource database.
                   4012: #                          rid           - Resource id.
                   4013: #    $client             - socket open on the client.
                   4014: #
                   4015: # Returns:
                   4016: #      1  indicating the caller should not yet exit.
                   4017: # Side-effects:
                   4018: #   Writes a reply to the client.
                   4019: #   The reply is a string of the following shape:
                   4020: #   version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
                   4021: #    Where the 1 above represents version 1.
                   4022: #    this continues for all pairs of keys in all versions.
                   4023: #
                   4024: #
                   4025: #    
                   4026: #
                   4027: sub restore_handler {
                   4028:     my ($cmd, $tail, $client) = @_;
                   4029: 
                   4030:     my $userinput = "$cmd:$tail";	# Only used for logging purposes.
1.351     banghart 4031:     my ($udom,$uname,$namespace,$rid) = split(/:/,$tail);
1.352     albertel 4032:     $namespace=~s/\//\_/g;
1.350     albertel 4033:     $namespace = &LONCAPA::clean_username($namespace);
1.349     albertel 4034: 
1.231     foxr     4035:     chomp($rid);
                   4036:     my $qresult='';
1.309     albertel 4037:     my $hashref = &tie_user_hash($udom, $uname, $namespace, &GDBM_READER());
                   4038:     if ($hashref) {
                   4039: 	my $version=$hashref->{"version:$rid"};
1.231     foxr     4040: 	$qresult.="version=$version&";
                   4041: 	my $scope;
                   4042: 	for ($scope=1;$scope<=$version;$scope++) {
1.309     albertel 4043: 	    my $vkeys=$hashref->{"$scope:keys:$rid"};
1.231     foxr     4044: 	    my @keys=split(/:/,$vkeys);
                   4045: 	    my $key;
                   4046: 	    $qresult.="$scope:keys=$vkeys&";
                   4047: 	    foreach $key (@keys) {
1.309     albertel 4048: 		$qresult.="$scope:$key=".$hashref->{"$scope:$rid:$key"}."&";
1.231     foxr     4049: 	    }                                  
                   4050: 	}
1.311     albertel 4051: 	if (&untie_user_hash($hashref)) {
1.231     foxr     4052: 	    $qresult=~s/\&$//;
1.387     albertel 4053: 	    &Reply( $client, \$qresult, $userinput);
1.231     foxr     4054: 	} else {
                   4055: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4056: 		    "while attempting restore\n", $userinput);
                   4057: 	}
                   4058:     } else {
                   4059: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4060: 		"while attempting restore\n", $userinput);
                   4061:     }
                   4062:   
                   4063:     return 1;
                   4064: 
                   4065: 
                   4066: }
                   4067: &register_handler("restore", \&restore_handler, 0,1,0);
1.234     foxr     4068: 
                   4069: #
1.324     raeburn  4070: #   Add a chat message to a synchronous discussion board.
1.234     foxr     4071: #
                   4072: # Parameters:
                   4073: #    $cmd                - Request keyword.
                   4074: #    $tail               - Tail of the command. A colon separated list
                   4075: #                          containing:
                   4076: #                          cdom    - Domain on which the chat board lives
1.324     raeburn  4077: #                          cnum    - Course containing the chat board.
                   4078: #                          newpost - Body of the posting.
                   4079: #                          group   - Optional group, if chat board is only 
                   4080: #                                    accessible in a group within the course 
1.234     foxr     4081: #   $client              - Socket open on the client.
                   4082: # Returns:
                   4083: #   1    - Indicating caller should keep on processing.
                   4084: #
                   4085: # Side-effects:
                   4086: #   writes a reply to the client.
                   4087: #
                   4088: #
                   4089: sub send_chat_handler {
                   4090:     my ($cmd, $tail, $client) = @_;
                   4091: 
                   4092:     
                   4093:     my $userinput = "$cmd:$tail";
                   4094: 
1.324     raeburn  4095:     my ($cdom,$cnum,$newpost,$group)=split(/\:/,$tail);
                   4096:     &chat_add($cdom,$cnum,$newpost,$group);
1.234     foxr     4097:     &Reply($client, "ok\n", $userinput);
                   4098: 
                   4099:     return 1;
                   4100: }
                   4101: &register_handler("chatsend", \&send_chat_handler, 0, 1, 0);
1.263     albertel 4102: 
1.234     foxr     4103: #
1.324     raeburn  4104: #   Retrieve the set of chat messages from a discussion board.
1.234     foxr     4105: #
                   4106: #  Parameters:
                   4107: #    $cmd             - Command keyword that initiated the request.
                   4108: #    $tail            - Remainder of the request after the command
                   4109: #                       keyword.  In this case a colon separated list of
                   4110: #                       chat domain    - Which discussion board.
                   4111: #                       chat id        - Discussion thread(?)
                   4112: #                       domain/user    - Authentication domain and username
                   4113: #                                        of the requesting person.
1.324     raeburn  4114: #                       group          - Optional course group containing
                   4115: #                                        the board.      
1.234     foxr     4116: #   $client           - Socket open on the client program.
                   4117: # Returns:
                   4118: #    1     - continue processing
                   4119: # Side effects:
                   4120: #    Response is written to the client.
                   4121: #
                   4122: sub retrieve_chat_handler {
                   4123:     my ($cmd, $tail, $client) = @_;
                   4124: 
                   4125: 
                   4126:     my $userinput = "$cmd:$tail";
                   4127: 
1.324     raeburn  4128:     my ($cdom,$cnum,$udom,$uname,$group)=split(/\:/,$tail);
1.234     foxr     4129:     my $reply='';
1.324     raeburn  4130:     foreach (&get_chat($cdom,$cnum,$udom,$uname,$group)) {
1.234     foxr     4131: 	$reply.=&escape($_).':';
                   4132:     }
                   4133:     $reply=~s/\:$//;
1.387     albertel 4134:     &Reply($client, \$reply, $userinput);
1.234     foxr     4135: 
                   4136: 
                   4137:     return 1;
                   4138: }
                   4139: &register_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
                   4140: 
                   4141: #
                   4142: #  Initiate a query of an sql database.  SQL query repsonses get put in
                   4143: #  a file for later retrieval.  This prevents sql query results from
                   4144: #  bottlenecking the system.  Note that with loncnew, perhaps this is
                   4145: #  less of an issue since multiple outstanding requests can be concurrently
                   4146: #  serviced.
                   4147: #
                   4148: #  Parameters:
1.535     raeburn  4149: #     $cmd       - Command keyword that initiated the request.
1.234     foxr     4150: #     $tail      - Remainder of the command after the keyword.
                   4151: #                  For this function, this consists of a query and
                   4152: #                  3 arguments that are self-documentingly labelled
                   4153: #                  in the original arg1, arg2, arg3.
                   4154: #     $client    - Socket open on the client.
                   4155: # Return:
                   4156: #    1   - Indicating processing should continue.
                   4157: # Side-effects:
                   4158: #    a reply is written to $client.
                   4159: #
                   4160: sub send_query_handler {
                   4161:     my ($cmd, $tail, $client) = @_;
                   4162: 
                   4163:     my $userinput = "$cmd:$tail";
                   4164: 
                   4165:     my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
                   4166:     $query=~s/\n*$//g;
1.534     raeburn  4167:     if (($query eq 'usersearch') || ($query eq 'instdirsearch')) {
                   4168:         my $usersearchconf = &get_usersearch_config($currentdomainid,'directorysrch');
                   4169:         my $earlyout;
                   4170:         if (ref($usersearchconf) eq 'HASH') {
                   4171:             if ($currentdomainid eq $clienthomedom) {
                   4172:                 if ($query eq 'usersearch') {
                   4173:                     if ($usersearchconf->{'lcavailable'} eq '0') {
                   4174:                         $earlyout = 1;
                   4175:                     }
                   4176:                 } else {
                   4177:                     if ($usersearchconf->{'available'} eq '0') {
                   4178:                         $earlyout = 1;
                   4179:                     }
                   4180:                 }
                   4181:             } else {
                   4182:                 if ($query eq 'usersearch') {
                   4183:                     if ($usersearchconf->{'lclocalonly'}) {
                   4184:                         $earlyout = 1;
                   4185:                     }
                   4186:                 } else {
                   4187:                     if ($usersearchconf->{'localonly'}) {
                   4188:                         $earlyout = 1;
                   4189:                     }
                   4190:                 }
                   4191:             }
                   4192:         }
                   4193:         if ($earlyout) {
                   4194:             &Reply($client, "query_not_authorized\n");
                   4195:             return 1;
                   4196:         }
                   4197:     }
1.234     foxr     4198:     &Reply($client, "". &sql_reply("$clientname\&$query".
                   4199: 				"\&$arg1"."\&$arg2"."\&$arg3")."\n",
                   4200: 	  $userinput);
                   4201:     
                   4202:     return 1;
                   4203: }
                   4204: &register_handler("querysend", \&send_query_handler, 0, 1, 0);
                   4205: 
                   4206: #
                   4207: #   Add a reply to an sql query.  SQL queries are done asyncrhonously.
                   4208: #   The query is submitted via a "querysend" transaction.
                   4209: #   There it is passed on to the lonsql daemon, queued and issued to
                   4210: #   mysql.
                   4211: #     This transaction is invoked when the sql transaction is complete
                   4212: #   it stores the query results in flie and indicates query completion.
                   4213: #   presumably local software then fetches this response... I'm guessing
                   4214: #   the sequence is: lonc does a querysend, we ask lonsql to do it.
                   4215: #   lonsql on completion of the query interacts with the lond of our
                   4216: #   client to do a query reply storing two files:
                   4217: #    - id     - The results of the query.
                   4218: #    - id.end - Indicating the transaction completed. 
                   4219: #    NOTE: id is a unique id assigned to the query and querysend time.
                   4220: # Parameters:
                   4221: #    $cmd        - Command keyword that initiated this request.
                   4222: #    $tail       - Remainder of the tail.  In this case that's a colon
                   4223: #                  separated list containing the query Id and the 
                   4224: #                  results of the query.
                   4225: #    $client     - Socket open on the client.
                   4226: # Return:
                   4227: #    1           - Indicating that we should continue processing.
                   4228: # Side effects:
                   4229: #    ok written to the client.
                   4230: #
                   4231: sub reply_query_handler {
                   4232:     my ($cmd, $tail, $client) = @_;
                   4233: 
                   4234: 
                   4235:     my $userinput = "$cmd:$tail";
                   4236: 
1.339     albertel 4237:     my ($id,$reply)=split(/:/,$tail); 
1.234     foxr     4238:     my $store;
                   4239:     my $execdir=$perlvar{'lonDaemons'};
                   4240:     if ($store=IO::File->new(">$execdir/tmp/$id")) {
                   4241: 	$reply=~s/\&/\n/g;
                   4242: 	print $store $reply;
                   4243: 	close $store;
                   4244: 	my $store2=IO::File->new(">$execdir/tmp/$id.end");
                   4245: 	print $store2 "done\n";
                   4246: 	close $store2;
                   4247: 	&Reply($client, "ok\n", $userinput);
                   4248:     } else {
                   4249: 	&Failure($client, "error: ".($!+0)
                   4250: 		." IO::File->new Failed ".
                   4251: 		"while attempting queryreply\n", $userinput);
                   4252:     }
                   4253:  
                   4254: 
                   4255:     return 1;
                   4256: }
                   4257: &register_handler("queryreply", \&reply_query_handler, 0, 1, 0);
                   4258: 
                   4259: #
                   4260: #  Process the courseidput request.  Not quite sure what this means
                   4261: #  at the system level sense.  It appears a gdbm file in the 
                   4262: #  /home/httpd/lonUsers/$domain/nohist_courseids is tied and
                   4263: #  a set of entries made in that database.
                   4264: #
                   4265: # Parameters:
                   4266: #   $cmd      - The command keyword that initiated this request.
                   4267: #   $tail     - Tail of the command.  In this case consists of a colon
                   4268: #               separated list contaning the domain to apply this to and
                   4269: #               an ampersand separated list of keyword=value pairs.
1.272     raeburn  4270: #               Each value is a colon separated list that includes:  
                   4271: #               description, institutional code and course owner.
                   4272: #               For backward compatibility with versions included
                   4273: #               in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
                   4274: #               code and/or course owner are preserved from the existing 
                   4275: #               record when writing a new record in response to 1.1 or 
                   4276: #               1.2 implementations of lonnet::flushcourselogs().   
                   4277: #                      
1.234     foxr     4278: #   $client   - Socket open on the client.
                   4279: # Returns:
                   4280: #   1    - indicating that processing should continue
                   4281: #
                   4282: # Side effects:
                   4283: #   reply is written to the client.
                   4284: #
                   4285: sub put_course_id_handler {
                   4286:     my ($cmd, $tail, $client) = @_;
                   4287: 
                   4288: 
                   4289:     my $userinput = "$cmd:$tail";
                   4290: 
1.266     raeburn  4291:     my ($udom, $what) = split(/:/, $tail,2);
1.234     foxr     4292:     chomp($what);
                   4293:     my $now=time;
                   4294:     my @pairs=split(/\&/,$what);
                   4295: 
                   4296:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   4297:     if ($hashref) {
                   4298: 	foreach my $pair (@pairs) {
1.271     raeburn  4299:             my ($key,$courseinfo) = split(/=/,$pair,2);
                   4300:             $courseinfo =~ s/=/:/g;
1.384     raeburn  4301:             if (defined($hashref->{$key})) {
                   4302:                 my $value = &Apache::lonnet::thaw_unescape($hashref->{$key});
                   4303:                 if (ref($value) eq 'HASH') {
                   4304:                     my @items = ('description','inst_code','owner','type');
                   4305:                     my @new_items = split(/:/,$courseinfo,-1);
                   4306:                     my %storehash; 
                   4307:                     for (my $i=0; $i<@new_items; $i++) {
1.391     raeburn  4308:                         $storehash{$items[$i]} = &unescape($new_items[$i]);
1.384     raeburn  4309:                     }
                   4310:                     $hashref->{$key} = 
                   4311:                         &Apache::lonnet::freeze_escape(\%storehash);
                   4312:                     my $unesc_key = &unescape($key);
                   4313:                     $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
                   4314:                     next;
1.383     raeburn  4315:                 }
1.384     raeburn  4316:             }
                   4317:             my @current_items = split(/:/,$hashref->{$key},-1);
                   4318:             shift(@current_items); # remove description
                   4319:             pop(@current_items);   # remove last access
                   4320:             my $numcurrent = scalar(@current_items);
                   4321:             if ($numcurrent > 3) {
                   4322:                 $numcurrent = 3;
                   4323:             }
                   4324:             my @new_items = split(/:/,$courseinfo,-1);
                   4325:             my $numnew = scalar(@new_items);
                   4326:             if ($numcurrent > 0) {
                   4327:                 if ($numnew <= $numcurrent) { # flushcourselogs() from pre 2.2 
                   4328:                     for (my $j=$numcurrent-$numnew; $j>=0; $j--) {
                   4329:                         $courseinfo .= ':'.$current_items[$numcurrent-$j-1];
1.333     raeburn  4330:                     }
1.272     raeburn  4331:                 }
                   4332:             }
1.384     raeburn  4333:             $hashref->{$key}=$courseinfo.':'.$now;
1.234     foxr     4334: 	}
1.311     albertel 4335: 	if (&untie_domain_hash($hashref)) {
1.253     foxr     4336: 	    &Reply( $client, "ok\n", $userinput);
1.234     foxr     4337: 	} else {
1.253     foxr     4338: 	    &Failure($client, "error: ".($!+0)
1.234     foxr     4339: 		     ." untie(GDBM) Failed ".
                   4340: 		     "while attempting courseidput\n", $userinput);
                   4341: 	}
                   4342:     } else {
1.253     foxr     4343: 	&Failure($client, "error: ".($!+0)
1.234     foxr     4344: 		 ." tie(GDBM) Failed ".
                   4345: 		 "while attempting courseidput\n", $userinput);
                   4346:     }
                   4347: 
                   4348:     return 1;
                   4349: }
                   4350: &register_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
                   4351: 
1.383     raeburn  4352: sub put_course_id_hash_handler {
                   4353:     my ($cmd, $tail, $client) = @_;
                   4354:     my $userinput = "$cmd:$tail";
1.384     raeburn  4355:     my ($udom,$mode,$what) = split(/:/, $tail,3);
1.383     raeburn  4356:     chomp($what);
                   4357:     my $now=time;
                   4358:     my @pairs=split(/\&/,$what);
1.384     raeburn  4359:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
1.383     raeburn  4360:     if ($hashref) {
                   4361:         foreach my $pair (@pairs) {
                   4362:             my ($key,$value)=split(/=/,$pair);
1.384     raeburn  4363:             my $unesc_key = &unescape($key);
                   4364:             if ($mode ne 'timeonly') {
                   4365:                 if (!defined($hashref->{&escape('lasttime:'.$unesc_key)})) {
                   4366:                     my $curritems = &Apache::lonnet::thaw_unescape($key); 
                   4367:                     if (ref($curritems) ne 'HASH') {
                   4368:                         my @current_items = split(/:/,$hashref->{$key},-1);
                   4369:                         my $lasttime = pop(@current_items);
                   4370:                         $hashref->{&escape('lasttime:'.$unesc_key)} = $lasttime;
                   4371:                     } else {
                   4372:                         $hashref->{&escape('lasttime:'.$unesc_key)} = '';
                   4373:                     }
                   4374:                 } 
                   4375:                 $hashref->{$key} = $value;
                   4376:             }
                   4377:             if ($mode ne 'notime') {
                   4378:                 $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
                   4379:             }
1.383     raeburn  4380:         }
                   4381:         if (&untie_domain_hash($hashref)) {
                   4382:             &Reply($client, "ok\n", $userinput);
                   4383:         } else {
                   4384:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4385:                      "while attempting courseidputhash\n", $userinput);
                   4386:         }
                   4387:     } else {
                   4388:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4389:                   "while attempting courseidputhash\n", $userinput);
                   4390:     }
                   4391:     return 1;
                   4392: }
                   4393: &register_handler("courseidputhash", \&put_course_id_hash_handler, 0, 1, 0);
                   4394: 
1.234     foxr     4395: #  Retrieves the value of a course id resource keyword pattern
                   4396: #  defined since a starting date.  Both the starting date and the
                   4397: #  keyword pattern are optional.  If the starting date is not supplied it
                   4398: #  is treated as the beginning of time.  If the pattern is not found,
                   4399: #  it is treatred as "." matching everything.
                   4400: #
                   4401: #  Parameters:
                   4402: #     $cmd     - Command keyword that resulted in us being dispatched.
                   4403: #     $tail    - The remainder of the command that, in this case, consists
                   4404: #                of a colon separated list of:
                   4405: #                 domain   - The domain in which the course database is 
                   4406: #                            defined.
                   4407: #                 since    - Optional parameter describing the minimum
                   4408: #                            time of definition(?) of the resources that
                   4409: #                            will match the dump.
                   4410: #                 description - regular expression that is used to filter
                   4411: #                            the dump.  Only keywords matching this regexp
                   4412: #                            will be used.
1.272     raeburn  4413: #                 institutional code - optional supplied code to filter 
                   4414: #                            the dump. Only courses with an institutional code 
                   4415: #                            that match the supplied code will be returned.
1.336     raeburn  4416: #                 owner    - optional supplied username and domain of owner to
                   4417: #                            filter the dump.  Only courses for which the course
                   4418: #                            owner matches the supplied username and/or domain
                   4419: #                            will be returned. Pre-2.2.0 legacy entries from 
                   4420: #                            nohist_courseiddump will only contain usernames.
1.384     raeburn  4421: #                 type     - optional parameter for selection 
1.418     raeburn  4422: #                 regexp_ok - if 1 or -1 allow the supplied institutional code
                   4423: #                            filter to behave as a regular expression:
                   4424: #	                      1 will not exclude the course if the instcode matches the RE 
                   4425: #                            -1 will exclude the course if the instcode matches the RE
1.384     raeburn  4426: #                 rtn_as_hash - whether to return the information available for
                   4427: #                            each matched item as a frozen hash of all 
                   4428: #                            key, value pairs in the item's hash, or as a 
                   4429: #                            colon-separated list of (in order) description,
                   4430: #                            institutional code, and course owner.
1.404     raeburn  4431: #                 selfenrollonly - filter by courses allowing self-enrollment  
                   4432: #                                  now or in the future (selfenrollonly = 1).
                   4433: #                 catfilter - filter by course category, assigned to a course 
                   4434: #                             using manually defined categories (i.e., not
1.407     raeburn  4435: #                             self-cataloging based on on institutional code).   
1.404     raeburn  4436: #                 showhidden - include course in results even if course  
1.407     raeburn  4437: #                              was set to be excluded from course catalog (DC only).
1.404     raeburn  4438: #                 caller -  if set to 'coursecatalog', courses set to be hidden
                   4439: #                           from course catalog will be excluded from results (unless
                   4440: #                           overridden by "showhidden".
1.427     raeburn  4441: #                 cloner - escaped username:domain of course cloner (if picking course to
1.419     raeburn  4442: #                          clone).
                   4443: #                 cc_clone_list - escaped comma separated list of courses for which 
                   4444: #                                 course cloner has active CC role (and so can clone
                   4445: #                                 automatically).
1.427     raeburn  4446: #                 cloneonly - filter by courses for which cloner has rights to clone.
                   4447: #                 createdbefore - include courses for which creation date preceeded this date.
                   4448: #                 createdafter - include courses for which creation date followed this date.
                   4449: #                 creationcontext - include courses created in specified context 
1.404     raeburn  4450: #
1.445     raeburn  4451: #                 domcloner - flag to indicate if user can create CCs in course's domain.
1.505     raeburn  4452: #                             If so, ability to clone course is automatic.
                   4453: #                 hasuniquecode - filter by courses for which a six character unique code has 
                   4454: #                                 been set.
1.445     raeburn  4455: #
1.234     foxr     4456: #     $client  - The socket open on the client.
                   4457: # Returns:
                   4458: #    1     - Continue processing.
                   4459: # Side Effects:
                   4460: #   a reply is written to $client.
                   4461: sub dump_course_id_handler {
                   4462:     my ($cmd, $tail, $client) = @_;
1.494     droeschl 4463: 
                   4464:     my $res = LONCAPA::Lond::dump_course_id_handler($tail);
                   4465:     if ($res =~ /^error:/) {
                   4466:         Failure($client, \$res, "$cmd:$tail");
                   4467:     } else {
                   4468:         Reply($client, \$res, "$cmd:$tail");
                   4469:     }
                   4470: 
                   4471:     return 1;  
                   4472: 
                   4473:     #TODO remove
1.234     foxr     4474:     my $userinput = "$cmd:$tail";
                   4475: 
1.333     raeburn  4476:     my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter,
1.404     raeburn  4477:         $typefilter,$regexp_ok,$rtn_as_hash,$selfenrollonly,$catfilter,$showhidden,
1.427     raeburn  4478:         $caller,$cloner,$cc_clone_list,$cloneonly,$createdbefore,$createdafter,
1.505     raeburn  4479:         $creationcontext,$domcloner,$hasuniquecode) =split(/:/,$tail);
1.397     raeburn  4480:     my $now = time;
1.419     raeburn  4481:     my ($cloneruname,$clonerudom,%cc_clone);
1.234     foxr     4482:     if (defined($description)) {
                   4483: 	$description=&unescape($description);
                   4484:     } else {
                   4485: 	$description='.';
                   4486:     }
1.266     raeburn  4487:     if (defined($instcodefilter)) {
                   4488:         $instcodefilter=&unescape($instcodefilter);
                   4489:     } else {
                   4490:         $instcodefilter='.';
                   4491:     }
1.336     raeburn  4492:     my ($ownerunamefilter,$ownerdomfilter);
1.266     raeburn  4493:     if (defined($ownerfilter)) {
                   4494:         $ownerfilter=&unescape($ownerfilter);
1.336     raeburn  4495:         if ($ownerfilter ne '.' && defined($ownerfilter)) {
                   4496:             if ($ownerfilter =~ /^([^:]*):([^:]*)$/) {
                   4497:                  $ownerunamefilter = $1;
                   4498:                  $ownerdomfilter = $2;
                   4499:             } else {
                   4500:                 $ownerunamefilter = $ownerfilter;
                   4501:                 $ownerdomfilter = '';
                   4502:             }
                   4503:         }
1.266     raeburn  4504:     } else {
                   4505:         $ownerfilter='.';
                   4506:     }
1.336     raeburn  4507: 
1.282     raeburn  4508:     if (defined($coursefilter)) {
                   4509:         $coursefilter=&unescape($coursefilter);
                   4510:     } else {
                   4511:         $coursefilter='.';
                   4512:     }
1.333     raeburn  4513:     if (defined($typefilter)) {
                   4514:         $typefilter=&unescape($typefilter);
                   4515:     } else {
                   4516:         $typefilter='.';
                   4517:     }
1.344     raeburn  4518:     if (defined($regexp_ok)) {
                   4519:         $regexp_ok=&unescape($regexp_ok);
                   4520:     }
1.401     raeburn  4521:     if (defined($catfilter)) {
                   4522:         $catfilter=&unescape($catfilter);
                   4523:     }
1.419     raeburn  4524:     if (defined($cloner)) {
                   4525:         $cloner = &unescape($cloner);
                   4526:         ($cloneruname,$clonerudom) = ($cloner =~ /^($LONCAPA::match_username):($LONCAPA::match_domain)$/); 
                   4527:     }
                   4528:     if (defined($cc_clone_list)) {
                   4529:         $cc_clone_list = &unescape($cc_clone_list);
                   4530:         my @cc_cloners = split('&',$cc_clone_list);
                   4531:         foreach my $cid (@cc_cloners) {
                   4532:             my ($clonedom,$clonenum) = split(':',$cid);
                   4533:             next if ($clonedom ne $udom); 
                   4534:             $cc_clone{$clonedom.'_'.$clonenum} = 1;
                   4535:         } 
                   4536:     }
1.431     raeburn  4537:     if ($createdbefore ne '') {
1.427     raeburn  4538:         $createdbefore = &unescape($createdbefore);
                   4539:     } else {
                   4540:        $createdbefore = 0;
                   4541:     }
1.431     raeburn  4542:     if ($createdafter ne '') {
1.427     raeburn  4543:         $createdafter = &unescape($createdafter);
                   4544:     } else {
                   4545:         $createdafter = 0;
                   4546:     }
1.431     raeburn  4547:     if ($creationcontext ne '') {
1.427     raeburn  4548:         $creationcontext = &unescape($creationcontext);
                   4549:     } else {
                   4550:         $creationcontext = '.';
                   4551:     }
1.505     raeburn  4552:     unless ($hasuniquecode) {
                   4553:         $hasuniquecode = '.';
                   4554:     }
1.384     raeburn  4555:     my $unpack = 1;
1.485     raeburn  4556:     if ($description eq '.' && $instcodefilter eq '.' && $ownerfilter eq '.' && 
1.384     raeburn  4557:         $typefilter eq '.') {
                   4558:         $unpack = 0;
                   4559:     }
                   4560:     if (!defined($since)) { $since=0; }
1.234     foxr     4561:     my $qresult='';
                   4562:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   4563:     if ($hashref) {
1.384     raeburn  4564: 	while (my ($key,$value) = each(%$hashref)) {
1.397     raeburn  4565:             my ($unesc_key,$lasttime_key,$lasttime,$is_hash,%val,
1.427     raeburn  4566:                 %unesc_val,$selfenroll_end,$selfenroll_types,$created,
                   4567:                 $context);
1.384     raeburn  4568:             $unesc_key = &unescape($key);
                   4569:             if ($unesc_key =~ /^lasttime:/) {
                   4570:                 next;
                   4571:             } else {
                   4572:                 $lasttime_key = &escape('lasttime:'.$unesc_key);
                   4573:             }
                   4574:             if ($hashref->{$lasttime_key} ne '') {
                   4575:                 $lasttime = $hashref->{$lasttime_key};
                   4576:                 next if ($lasttime<$since);
                   4577:             }
1.419     raeburn  4578:             my ($canclone,$valchange);
1.384     raeburn  4579:             my $items = &Apache::lonnet::thaw_unescape($value);
                   4580:             if (ref($items) eq 'HASH') {
1.429     raeburn  4581:                 if ($hashref->{$lasttime_key} eq '') {
1.430     raeburn  4582:                     next if ($since > 1);
1.429     raeburn  4583:                 }
1.384     raeburn  4584:                 $is_hash =  1;
1.445     raeburn  4585:                 if ($domcloner) {
                   4586:                     $canclone = 1;
                   4587:                 } elsif (defined($clonerudom)) {
1.419     raeburn  4588:                     if ($items->{'cloners'}) {
                   4589:                         my @cloneable = split(',',$items->{'cloners'});
                   4590:                         if (@cloneable) {
                   4591:                             if (grep(/^\*$/,@cloneable))  {
                   4592:                                 $canclone = 1;
                   4593:                             } elsif (grep(/^\*:\Q$clonerudom\E$/,@cloneable)) {
                   4594:                                 $canclone = 1;
                   4595:                             } elsif (grep(/^\Q$cloneruname\E:\Q$clonerudom\E$/,@cloneable)) {
                   4596:                                 $canclone = 1;
                   4597:                             }
                   4598:                         }
                   4599:                         unless ($canclone) {
                   4600:                             if ($cloneruname ne '' && $clonerudom ne '') {
                   4601:                                 if ($cc_clone{$unesc_key}) {
                   4602:                                     $canclone = 1;
                   4603:                                     $items->{'cloners'} .= ','.$cloneruname.':'.
                   4604:                                                            $clonerudom;
                   4605:                                     $valchange = 1;
                   4606:                                 }
                   4607:                             }
                   4608:                         }
                   4609:                     } elsif (defined($cloneruname)) {
                   4610:                         if ($cc_clone{$unesc_key}) {
                   4611:                             $canclone = 1;
                   4612:                             $items->{'cloners'} = $cloneruname.':'.$clonerudom;
                   4613:                             $valchange = 1;
                   4614:                         }
1.437     raeburn  4615:                         unless ($canclone) {
                   4616:                             if ($items->{'owner'} =~ /:/) {
                   4617:                                 if ($items->{'owner'} eq $cloner) {
                   4618:                                     $canclone = 1;
                   4619:                                 }
1.444     raeburn  4620:                             } elsif ($cloner eq $items->{'owner'}.':'.$udom) {
1.437     raeburn  4621:                                 $canclone = 1;
                   4622:                             }
                   4623:                             if ($canclone) {
                   4624:                                 $items->{'cloners'} = $cloneruname.':'.$clonerudom;
                   4625:                                 $valchange = 1;
                   4626:                             }
                   4627:                         }
1.419     raeburn  4628:                     }
                   4629:                 }
1.384     raeburn  4630:                 if ($unpack || !$rtn_as_hash) {
                   4631:                     $unesc_val{'descr'} = $items->{'description'};
                   4632:                     $unesc_val{'inst_code'} = $items->{'inst_code'};
                   4633:                     $unesc_val{'owner'} = $items->{'owner'};
                   4634:                     $unesc_val{'type'} = $items->{'type'};
1.419     raeburn  4635:                     $unesc_val{'cloners'} = $items->{'cloners'};
1.427     raeburn  4636:                     $unesc_val{'created'} = $items->{'created'};
                   4637:                     $unesc_val{'context'} = $items->{'context'};
1.404     raeburn  4638:                 }
                   4639:                 $selfenroll_types = $items->{'selfenroll_types'};
                   4640:                 $selfenroll_end = $items->{'selfenroll_end_date'};
1.427     raeburn  4641:                 $created = $items->{'created'};
                   4642:                 $context = $items->{'context'};
1.505     raeburn  4643:                 if ($hasuniquecode ne '.') {
                   4644:                     next unless ($items->{'uniquecode'});
                   4645:                 }
1.404     raeburn  4646:                 if ($selfenrollonly) {
                   4647:                     next if (!$selfenroll_types);
                   4648:                     if (($selfenroll_end > 0) && ($selfenroll_end <= $now)) {
                   4649:                         next;
1.397     raeburn  4650:                     }
1.404     raeburn  4651:                 }
1.427     raeburn  4652:                 if ($creationcontext ne '.') {
                   4653:                     next if (($context ne '') && ($context ne $creationcontext));  
                   4654:                 }
                   4655:                 if ($createdbefore > 0) {
                   4656:                     next if (($created eq '') || ($created > $createdbefore));   
                   4657:                 }
                   4658:                 if ($createdafter > 0) {
                   4659:                     next if (($created eq '') || ($created <= $createdafter)); 
                   4660:                 }
1.404     raeburn  4661:                 if ($catfilter ne '') {
1.406     raeburn  4662:                     next if ($items->{'categories'} eq '');
                   4663:                     my @categories = split('&',$items->{'categories'}); 
1.407     raeburn  4664:                     next if (@categories == 0);
                   4665:                     my @subcats = split('&',$catfilter);
                   4666:                     my $matchcat = 0;
                   4667:                     foreach my $cat (@categories) {
                   4668:                         if (grep(/^\Q$cat\E$/,@subcats)) {
                   4669:                             $matchcat = 1;
                   4670:                             last;
                   4671:                         }
                   4672:                     }
                   4673:                     next if (!$matchcat);
1.404     raeburn  4674:                 }
                   4675:                 if ($caller eq 'coursecatalog') {
1.405     raeburn  4676:                     if ($items->{'hidefromcat'} eq 'yes') {
                   4677:                         next if !$showhidden;
1.401     raeburn  4678:                     }
1.384     raeburn  4679:                 }
1.383     raeburn  4680:             } else {
1.401     raeburn  4681:                 next if ($catfilter ne '');
1.419     raeburn  4682:                 next if ($selfenrollonly);
1.427     raeburn  4683:                 next if ($createdbefore || $createdafter);
                   4684:                 next if ($creationcontext ne '.');
1.419     raeburn  4685:                 if ((defined($clonerudom)) && (defined($cloneruname)))  {
                   4686:                     if ($cc_clone{$unesc_key}) {
                   4687:                         $canclone = 1;
                   4688:                         $val{'cloners'} = &escape($cloneruname.':'.$clonerudom);
                   4689:                     }
                   4690:                 }
1.384     raeburn  4691:                 $is_hash =  0;
1.388     raeburn  4692:                 my @courseitems = split(/:/,$value);
1.403     raeburn  4693:                 $lasttime = pop(@courseitems);
1.402     raeburn  4694:                 if ($hashref->{$lasttime_key} eq '') {
                   4695:                     next if ($lasttime<$since);
                   4696:                 }
1.384     raeburn  4697: 	        ($val{'descr'},$val{'inst_code'},$val{'owner'},$val{'type'}) = @courseitems;
1.383     raeburn  4698:             }
1.419     raeburn  4699:             if ($cloneonly) {
                   4700:                next unless ($canclone);
                   4701:             }
1.266     raeburn  4702:             my $match = 1;
1.384     raeburn  4703: 	    if ($description ne '.') {
                   4704:                 if (!$is_hash) {
                   4705:                     $unesc_val{'descr'} = &unescape($val{'descr'});
                   4706:                 }
                   4707:                 if (eval{$unesc_val{'descr'} !~ /\Q$description\E/i}) {
1.266     raeburn  4708:                     $match = 0;
1.384     raeburn  4709:                 }
1.266     raeburn  4710:             }
1.384     raeburn  4711:             if ($instcodefilter ne '.') {
                   4712:                 if (!$is_hash) {
                   4713:                     $unesc_val{'inst_code'} = &unescape($val{'inst_code'});
                   4714:                 }
1.418     raeburn  4715:                 if ($regexp_ok == 1) {
1.384     raeburn  4716:                     if (eval{$unesc_val{'inst_code'} !~ /$instcodefilter/}) {
1.344     raeburn  4717:                         $match = 0;
                   4718:                     }
1.418     raeburn  4719:                 } elsif ($regexp_ok == -1) {
                   4720:                     if (eval{$unesc_val{'inst_code'} =~ /$instcodefilter/}) {
                   4721:                         $match = 0;
                   4722:                     }
1.344     raeburn  4723:                 } else {
1.384     raeburn  4724:                     if (eval{$unesc_val{'inst_code'} !~ /\Q$instcodefilter\E/i}) {
1.344     raeburn  4725:                         $match = 0;
                   4726:                     }
1.266     raeburn  4727:                 }
1.234     foxr     4728: 	    }
1.384     raeburn  4729:             if ($ownerfilter ne '.') {
                   4730:                 if (!$is_hash) {
                   4731:                     $unesc_val{'owner'} = &unescape($val{'owner'});
                   4732:                 }
1.336     raeburn  4733:                 if (($ownerunamefilter ne '') && ($ownerdomfilter ne '')) {
1.384     raeburn  4734:                     if ($unesc_val{'owner'} =~ /:/) {
                   4735:                         if (eval{$unesc_val{'owner'} !~ 
                   4736:                              /\Q$ownerunamefilter\E:\Q$ownerdomfilter\E$/i}) {
1.336     raeburn  4737:                             $match = 0;
                   4738:                         } 
                   4739:                     } else {
1.384     raeburn  4740:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336     raeburn  4741:                             $match = 0;
                   4742:                         }
                   4743:                     }
                   4744:                 } elsif ($ownerunamefilter ne '') {
1.384     raeburn  4745:                     if ($unesc_val{'owner'} =~ /:/) {
                   4746:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E:[^:]+$/i}) {
1.336     raeburn  4747:                              $match = 0;
                   4748:                         }
                   4749:                     } else {
1.384     raeburn  4750:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336     raeburn  4751:                             $match = 0;
                   4752:                         }
                   4753:                     }
                   4754:                 } elsif ($ownerdomfilter ne '') {
1.384     raeburn  4755:                     if ($unesc_val{'owner'} =~ /:/) {
                   4756:                         if (eval{$unesc_val{'owner'} !~ /^[^:]+:\Q$ownerdomfilter\E/}) {
1.336     raeburn  4757:                              $match = 0;
                   4758:                         }
                   4759:                     } else {
                   4760:                         if ($ownerdomfilter ne $udom) {
                   4761:                             $match = 0;
                   4762:                         }
                   4763:                     }
1.266     raeburn  4764:                 }
                   4765:             }
1.384     raeburn  4766:             if ($coursefilter ne '.') {
                   4767:                 if (eval{$unesc_key !~ /^$udom(_)\Q$coursefilter\E$/}) {
1.282     raeburn  4768:                     $match = 0;
                   4769:                 }
                   4770:             }
1.384     raeburn  4771:             if ($typefilter ne '.') {
                   4772:                 if (!$is_hash) {
                   4773:                     $unesc_val{'type'} = &unescape($val{'type'});
                   4774:                 }
                   4775:                 if ($unesc_val{'type'} eq '') {
1.333     raeburn  4776:                     if ($typefilter ne 'Course') {
                   4777:                         $match = 0;
                   4778:                     }
1.383     raeburn  4779:                 } else {
1.384     raeburn  4780:                     if (eval{$unesc_val{'type'} !~ /^\Q$typefilter\E$/}) {
1.333     raeburn  4781:                         $match = 0;
                   4782:                     }
                   4783:                 }
                   4784:             }
1.266     raeburn  4785:             if ($match == 1) {
1.384     raeburn  4786:                 if ($rtn_as_hash) {
                   4787:                     if ($is_hash) {
1.419     raeburn  4788:                         if ($valchange) {
                   4789:                             my $newvalue = &Apache::lonnet::freeze_escape($items);
                   4790:                             $qresult.=$key.'='.$newvalue.'&';
                   4791:                         } else {
                   4792:                             $qresult.=$key.'='.$value.'&';
                   4793:                         }
1.384     raeburn  4794:                     } else {
1.388     raeburn  4795:                         my %rtnhash = ( 'description' => &unescape($val{'descr'}),
                   4796:                                         'inst_code' => &unescape($val{'inst_code'}),
                   4797:                                         'owner'     => &unescape($val{'owner'}),
                   4798:                                         'type'      => &unescape($val{'type'}),
1.419     raeburn  4799:                                         'cloners'   => &unescape($val{'cloners'}),
1.384     raeburn  4800:                                       );
                   4801:                         my $items = &Apache::lonnet::freeze_escape(\%rtnhash);
                   4802:                         $qresult.=$key.'='.$items.'&';
                   4803:                     }
1.383     raeburn  4804:                 } else {
1.384     raeburn  4805:                     if ($is_hash) {
                   4806:                         $qresult .= $key.'='.&escape($unesc_val{'descr'}).':'.
                   4807:                                     &escape($unesc_val{'inst_code'}).':'.
                   4808:                                     &escape($unesc_val{'owner'}).'&';
                   4809:                     } else {
                   4810:                         $qresult .= $key.'='.$val{'descr'}.':'.$val{'inst_code'}.
                   4811:                                     ':'.$val{'owner'}.'&';
                   4812:                     }
1.383     raeburn  4813:                 }
1.266     raeburn  4814:             }
1.234     foxr     4815: 	}
1.311     albertel 4816: 	if (&untie_domain_hash($hashref)) {
1.234     foxr     4817: 	    chop($qresult);
1.387     albertel 4818: 	    &Reply($client, \$qresult, $userinput);
1.234     foxr     4819: 	} else {
                   4820: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4821: 		    "while attempting courseiddump\n", $userinput);
                   4822: 	}
                   4823:     } else {
                   4824: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4825: 		"while attempting courseiddump\n", $userinput);
                   4826:     }
                   4827:     return 1;
                   4828: }
                   4829: &register_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
1.238     foxr     4830: 
1.438     raeburn  4831: sub course_lastaccess_handler {
                   4832:     my ($cmd, $tail, $client) = @_;
                   4833:     my $userinput = "$cmd:$tail";
                   4834:     my ($cdom,$cnum) = split(':',$tail); 
                   4835:     my (%lastaccess,$qresult);
                   4836:     my $hashref = &tie_domain_hash($cdom, "nohist_courseids", &GDBM_WRCREAT());
                   4837:     if ($hashref) {
                   4838:         while (my ($key,$value) = each(%$hashref)) {
                   4839:             my ($unesc_key,$lasttime);
                   4840:             $unesc_key = &unescape($key);
                   4841:             if ($cnum) {
                   4842:                 next unless ($unesc_key =~ /\Q$cdom\E_\Q$cnum\E$/);
                   4843:             }
                   4844:             if ($unesc_key =~ /^lasttime:($LONCAPA::match_domain\_$LONCAPA::match_courseid)/) {
                   4845:                 $lastaccess{$1} = $value;
                   4846:             } else {
                   4847:                 my $items = &Apache::lonnet::thaw_unescape($value);
                   4848:                 if (ref($items) eq 'HASH') {
                   4849:                     unless ($lastaccess{$unesc_key}) {
                   4850:                         $lastaccess{$unesc_key} = '';
                   4851:                     }
                   4852:                 } else {
                   4853:                     my @courseitems = split(':',$value);
                   4854:                     $lastaccess{$unesc_key} = pop(@courseitems);
                   4855:                 }
                   4856:             }
                   4857:         }
                   4858:         foreach my $cid (sort(keys(%lastaccess))) {
                   4859:             $qresult.=&escape($cid).'='.$lastaccess{$cid}.'&'; 
                   4860:         }
                   4861:         if (&untie_domain_hash($hashref)) {
                   4862:             if ($qresult) {
                   4863:                 chop($qresult);
                   4864:             }
                   4865:             &Reply($client, \$qresult, $userinput);
                   4866:         } else {
                   4867:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4868:                     "while attempting lastacourseaccess\n", $userinput);
                   4869:         }
                   4870:     } else {
                   4871:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4872:                 "while attempting lastcourseaccess\n", $userinput);
                   4873:     }
                   4874:     return 1;
                   4875: }
                   4876: &register_handler("courselastaccess",\&course_lastaccess_handler, 0, 1, 0);
                   4877: 
1.561     raeburn  4878: sub course_sessions_handler {
                   4879:     my ($cmd, $tail, $client) = @_;
                   4880:     my $userinput = "$cmd:$tail";
                   4881:     my ($cdom,$cnum,$lastactivity) = split(':',$tail);
                   4882:     my $dbsuffix = '_'.$cdom.'_'.$cnum.'.db';
                   4883:     my (%sessions,$qresult);
                   4884:     my $now=time;
                   4885:     if (opendir(DIR,$perlvar{'lonIDsDir'})) {
                   4886:         my $filename;
                   4887:         while ($filename=readdir(DIR)) {
                   4888:             next if ($filename=~/^\./);
                   4889:             next if ($filename=~/^publicuser_/);
                   4890:             next if ($filename=~/^[a-f0-9]+_(linked|lti_\d+)\.id$/);
1.562     raeburn  4891:             if ($filename =~ /^($LONCAPA::match_username)_\d+_($LONCAPA::match_domain)_/) {
1.561     raeburn  4892:                 my ($uname,$udom) = ($1,$2);
1.562     raeburn  4893:                 next unless (-e "$perlvar{'lonDaemons'}/tmp/$uname$dbsuffix");
1.561     raeburn  4894:                 my $mtime = (stat("$perlvar{'lonIDsDir'}/$filename"))[9];
                   4895:                 if ($lastactivity < 0) {
1.563     raeburn  4896:                     next if ($mtime-$now > $lastactivity);
1.561     raeburn  4897:                 } else {
1.563     raeburn  4898:                     next if ($now-$mtime > $lastactivity);
1.561     raeburn  4899:                 }
                   4900:                 $sessions{$uname.':'.$udom} = $mtime;
                   4901:             }
                   4902:         }
                   4903:         closedir(DIR); 
                   4904:     }
                   4905:     foreach my $user (keys(%sessions)) {
                   4906:         $qresult.=&escape($user).'='.$sessions{$user}.'&';
                   4907:     }
                   4908:     if ($qresult) {
                   4909:         chop($qresult);
                   4910:     }
                   4911:     &Reply($client, \$qresult, $userinput);
                   4912:     return 1;
                   4913: }
                   4914: &register_handler("coursesessions",\&course_sessions_handler, 0, 1, 0);
                   4915: 
1.238     foxr     4916: #
1.348     raeburn  4917: # Puts an unencrypted entry in a namespace db file at the domain level 
                   4918: #
                   4919: # Parameters:
                   4920: #    $cmd      - The command that got us here.
                   4921: #    $tail     - Tail of the command (remaining parameters).
                   4922: #    $client   - File descriptor connected to client.
                   4923: # Returns
                   4924: #     0        - Requested to exit, caller should shut down.
                   4925: #     1        - Continue processing.
                   4926: #  Side effects:
                   4927: #     reply is written to $client.
                   4928: #
                   4929: sub put_domain_handler {
                   4930:     my ($cmd,$tail,$client) = @_;
                   4931: 
                   4932:     my $userinput = "$cmd:$tail";
                   4933: 
                   4934:     my ($udom,$namespace,$what) =split(/:/,$tail,3);
                   4935:     chomp($what);
                   4936:     my @pairs=split(/\&/,$what);
                   4937:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_WRCREAT(),
                   4938:                                    "P", $what);
                   4939:     if ($hashref) {
                   4940:         foreach my $pair (@pairs) {
                   4941:             my ($key,$value)=split(/=/,$pair);
                   4942:             $hashref->{$key}=$value;
                   4943:         }
                   4944:         if (&untie_domain_hash($hashref)) {
                   4945:             &Reply($client, "ok\n", $userinput);
                   4946:         } else {
                   4947:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4948:                      "while attempting putdom\n", $userinput);
                   4949:         }
                   4950:     } else {
                   4951:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4952:                   "while attempting putdom\n", $userinput);
                   4953:     }
                   4954: 
                   4955:     return 1;
                   4956: }
                   4957: &register_handler("putdom", \&put_domain_handler, 0, 1, 0);
                   4958: 
1.517     raeburn  4959: # Updates one or more entries in clickers.db file at the domain level
                   4960: #
                   4961: # Parameters:
                   4962: #    $cmd      - The command that got us here.
                   4963: #    $tail     - Tail of the command (remaining parameters).
                   4964: #                In this case a colon separated list containing:
                   4965: #                (a) the domain for which we are updating the entries,
                   4966: #                (b) the action required -- add or del -- and
                   4967: #                (c) a &-separated list of entries to add or delete.
                   4968: #    $client   - File descriptor connected to client.
                   4969: # Returns
                   4970: #     1        - Continue processing.
                   4971: #     0        - Requested to exit, caller should shut down.
                   4972: #  Side effects:
                   4973: #     reply is written to $client.
                   4974: #
                   4975: 
                   4976: 
                   4977: sub update_clickers {
                   4978:     my ($cmd, $tail, $client)  = @_;
                   4979: 
                   4980:     my $userinput = "$cmd:$tail";
                   4981:     my ($udom,$action,$what) =split(/:/,$tail,3);
                   4982:     chomp($what);
                   4983: 
                   4984:     my $hashref = &tie_domain_hash($udom, "clickers", &GDBM_WRCREAT(),
                   4985:                                  "U","$action:$what");
                   4986: 
                   4987:     if (!$hashref) {
                   4988:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4989:                   "while attempting updateclickers\n", $userinput);
                   4990:         return 1;
                   4991:     }
                   4992: 
                   4993:     my @pairs=split(/\&/,$what);
                   4994:     foreach my $pair (@pairs) {
                   4995:         my ($key,$value)=split(/=/,$pair);
                   4996:         if ($action eq 'add') {
                   4997:             if (exists($hashref->{$key})) {
                   4998:                 my @newvals = split(/,/,&unescape($value));
                   4999:                 my @currvals = split(/,/,&unescape($hashref->{$key}));
                   5000:                 my @merged = sort(keys(%{{map { $_ => 1 } (@newvals,@currvals)}}));
                   5001:                 $hashref->{$key}=&escape(join(',',@merged));
                   5002:             } else {
                   5003:                 $hashref->{$key}=$value;
                   5004:             }
                   5005:         } elsif ($action eq 'del') {
                   5006:             if (exists($hashref->{$key})) {
                   5007:                 my %current;
                   5008:                 map { $current{$_} = 1; } split(/,/,&unescape($hashref->{$key}));
                   5009:                 map { delete($current{$_}); } split(/,/,&unescape($value));
                   5010:                 if (keys(%current)) {
                   5011:                     $hashref->{$key}=&escape(join(',',sort(keys(%current))));
                   5012:                 } else {
                   5013:                     delete($hashref->{$key});
                   5014:                 }
                   5015:             }
                   5016:         }
                   5017:     }
                   5018:     if (&untie_user_hash($hashref)) {
                   5019:         &Reply( $client, "ok\n", $userinput);
                   5020:     } else {
                   5021:         &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   5022:                  "while attempting put\n",
                   5023:                  $userinput);
                   5024:     }
                   5025:     return 1;
                   5026: }
                   5027: &register_handler("updateclickers", \&update_clickers, 0, 1, 0);
                   5028: 
                   5029: 
                   5030: # Deletes one or more entries in a namespace db file at the domain level
                   5031: #
                   5032: # Parameters:
                   5033: #    $cmd      - The command that got us here.
                   5034: #    $tail     - Tail of the command (remaining parameters).
                   5035: #                In this case a colon separated list containing:
                   5036: #                (a) the domain for which we are deleting the entries,
                   5037: #                (b) &-separated list of keys to delete.  
                   5038: #    $client   - File descriptor connected to client.
                   5039: # Returns
                   5040: #     1        - Continue processing.
                   5041: #     0        - Requested to exit, caller should shut down.
                   5042: #  Side effects:
                   5043: #     reply is written to $client.
                   5044: #
                   5045: 
                   5046: sub del_domain_handler {
                   5047:     my ($cmd,$tail,$client) = @_;
                   5048: 
                   5049:     my $userinput = "$cmd:$tail";
                   5050: 
                   5051:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   5052:     chomp($what);
                   5053:     my $hashref = &tie_domain_hash($udom,$namespace,&GDBM_WRCREAT(),
                   5054:                                    "D", $what);
                   5055:     if ($hashref) {
                   5056:         my @keys=split(/\&/,$what);
                   5057:         foreach my $key (@keys) {
                   5058:             delete($hashref->{$key});
                   5059:         }
                   5060:         if (&untie_user_hash($hashref)) {
                   5061:             &Reply($client, "ok\n", $userinput);
                   5062:         } else {
                   5063:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5064:                     "while attempting deldom\n", $userinput);
                   5065:         }
                   5066:     } else {
                   5067:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5068:                  "while attempting deldom\n", $userinput);
                   5069:     }
                   5070:     return 1;
                   5071: }
                   5072: &register_handler("deldom", \&del_domain_handler, 0, 1, 0);
                   5073: 
                   5074: 
1.348     raeburn  5075: # Unencrypted get from the namespace database file at the domain level.
                   5076: # This function retrieves a keyed item from a specific named database in the
                   5077: # domain directory.
                   5078: #
                   5079: # Parameters:
                   5080: #   $cmd             - Command request keyword (get).
                   5081: #   $tail            - Tail of the command.  This is a colon separated list
                   5082: #                      consisting of the domain and the 'namespace' 
                   5083: #                      which selects the gdbm file to do the lookup in,
                   5084: #                      & separated list of keys to lookup.  Note that
                   5085: #                      the values are returned as an & separated list too.
                   5086: #   $client          - File descriptor open on the client.
                   5087: # Returns:
                   5088: #   1       - Continue processing.
                   5089: #   0       - Exit.
                   5090: #  Side effects:
                   5091: #     reply is written to $client.
                   5092: #
                   5093: 
                   5094: sub get_domain_handler {
                   5095:     my ($cmd, $tail, $client) = @_;
                   5096: 
1.461     foxr     5097: 
1.536     raeburn  5098:     my $userinput = "$cmd:$tail";
                   5099: 
                   5100:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   5101:     chomp($what);
                   5102:     if ($namespace =~ /^enc/) {
                   5103:         &Failure( $client, "refused\n", $userinput);
                   5104:     } else {
                   5105:         my @queries=split(/\&/,$what);
                   5106:         my $qresult='';
                   5107:         my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_READER());
                   5108:         if ($hashref) {
                   5109:             for (my $i=0;$i<=$#queries;$i++) {
                   5110:                 $qresult.="$hashref->{$queries[$i]}&";
                   5111:             }
                   5112:             if (&untie_domain_hash($hashref)) {
                   5113:                 $qresult=~s/\&$//;
                   5114:                 &Reply($client, \$qresult, $userinput);
                   5115:             } else {
                   5116:                 &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5117:                           "while attempting getdom\n",$userinput);
                   5118:             }
                   5119:         } else {
                   5120:             &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5121:                      "while attempting getdom\n",$userinput);
                   5122:         }
                   5123:     }
                   5124: 
                   5125:     return 1;
                   5126: }
                   5127: &register_handler("getdom", \&get_domain_handler, 0, 1, 0);
                   5128: 
                   5129: sub encrypted_get_domain_handler {
                   5130:     my ($cmd, $tail, $client) = @_;
                   5131: 
                   5132:     my $userinput = "$cmd:$tail";
1.348     raeburn  5133: 
                   5134:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   5135:     chomp($what);
                   5136:     my @queries=split(/\&/,$what);
                   5137:     my $qresult='';
                   5138:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_READER());
                   5139:     if ($hashref) {
                   5140:         for (my $i=0;$i<=$#queries;$i++) {
                   5141:             $qresult.="$hashref->{$queries[$i]}&";
                   5142:         }
                   5143:         if (&untie_domain_hash($hashref)) {
                   5144:             $qresult=~s/\&$//;
1.536     raeburn  5145:             if ($cipher) {
                   5146:                 my $cmdlength=length($qresult);
                   5147:                 $qresult.="         ";
                   5148:                 my $encqresult='';
                   5149:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   5150:                     $encqresult.= unpack("H16",
                   5151:                                          $cipher->encrypt(substr($qresult,
                   5152:                                                                  $encidx,
                   5153:                                                                  8)));
                   5154:                 }
                   5155:                 &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
                   5156:             } else {
                   5157:                 &Failure( $client, "error:no_key\n", $userinput);
                   5158:             }
1.348     raeburn  5159:         } else {
                   5160:             &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
1.536     raeburn  5161:                       "while attempting egetdom\n",$userinput);
1.348     raeburn  5162:         }
                   5163:     } else {
                   5164:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
1.536     raeburn  5165:                  "while attempting egetdom\n",$userinput);
1.348     raeburn  5166:     }
                   5167:     return 1;
                   5168: }
1.536     raeburn  5169: &register_handler("egetdom", \&encrypted_get_domain_handler, 1, 1, 0);
1.348     raeburn  5170: 
1.420     raeburn  5171: #
1.238     foxr     5172: #  Puts an id to a domains id database. 
                   5173: #
                   5174: #  Parameters:
                   5175: #   $cmd     - The command that triggered us.
                   5176: #   $tail    - Remainder of the request other than the command. This is a 
                   5177: #              colon separated list containing:
                   5178: #              $domain  - The domain for which we are writing the id.
                   5179: #              $pairs  - The id info to write... this is and & separated list
                   5180: #                        of keyword=value.
                   5181: #   $client  - Socket open on the client.
                   5182: #  Returns:
                   5183: #    1   - Continue processing.
                   5184: #  Side effects:
                   5185: #     reply is written to $client.
                   5186: #
                   5187: sub put_id_handler {
                   5188:     my ($cmd,$tail,$client) = @_;
                   5189: 
                   5190: 
                   5191:     my $userinput = "$cmd:$tail";
                   5192: 
                   5193:     my ($udom,$what)=split(/:/,$tail);
                   5194:     chomp($what);
                   5195:     my @pairs=split(/\&/,$what);
                   5196:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   5197: 				   "P", $what);
                   5198:     if ($hashref) {
                   5199: 	foreach my $pair (@pairs) {
                   5200: 	    my ($key,$value)=split(/=/,$pair);
                   5201: 	    $hashref->{$key}=$value;
                   5202: 	}
1.311     albertel 5203: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     5204: 	    &Reply($client, "ok\n", $userinput);
                   5205: 	} else {
                   5206: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5207: 		     "while attempting idput\n", $userinput);
                   5208: 	}
                   5209:     } else {
                   5210: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5211: 		  "while attempting idput\n", $userinput);
                   5212:     }
                   5213: 
                   5214:     return 1;
                   5215: }
1.263     albertel 5216: &register_handler("idput", \&put_id_handler, 0, 1, 0);
1.238     foxr     5217: 
                   5218: #
                   5219: #  Retrieves a set of id values from the id database.
                   5220: #  Returns an & separated list of results, one for each requested id to the
                   5221: #  client.
                   5222: #
                   5223: # Parameters:
                   5224: #   $cmd       - Command keyword that caused us to be dispatched.
                   5225: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5226: #               domain - the domain whose id table we dump
                   5227: #               ids      Consists of an & separated list of
                   5228: #                        id keywords whose values will be fetched.
                   5229: #                        nonexisting keywords will have an empty value.
                   5230: #   $client    - Socket open on the client.
                   5231: #
                   5232: # Returns:
                   5233: #    1 - indicating processing should continue.
                   5234: # Side effects:
                   5235: #   An & separated list of results is written to $client.
                   5236: #
                   5237: sub get_id_handler {
                   5238:     my ($cmd, $tail, $client) = @_;
                   5239: 
                   5240:     
                   5241:     my $userinput = "$client:$tail";
                   5242:     
                   5243:     my ($udom,$what)=split(/:/,$tail);
                   5244:     chomp($what);
                   5245:     my @queries=split(/\&/,$what);
                   5246:     my $qresult='';
                   5247:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
                   5248:     if ($hashref) {
                   5249: 	for (my $i=0;$i<=$#queries;$i++) {
                   5250: 	    $qresult.="$hashref->{$queries[$i]}&";
                   5251: 	}
1.311     albertel 5252: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     5253: 	    $qresult=~s/\&$//;
1.387     albertel 5254: 	    &Reply($client, \$qresult, $userinput);
1.238     foxr     5255: 	} else {
                   5256: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5257: 		      "while attempting idget\n",$userinput);
                   5258: 	}
                   5259:     } else {
                   5260: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5261: 		 "while attempting idget\n",$userinput);
                   5262:     }
                   5263:     
                   5264:     return 1;
                   5265: }
1.263     albertel 5266: &register_handler("idget", \&get_id_handler, 0, 1, 0);
1.238     foxr     5267: 
1.501     raeburn  5268: #   Deletes one or more ids in a domain's id database.
                   5269: #
                   5270: #   Parameters:
                   5271: #       $cmd                  - Command keyword (iddel).
                   5272: #       $tail                 - Command tail.  In this case a colon
                   5273: #                               separated list containing:
                   5274: #                               The domain for which we are deleting the id(s).
                   5275: #                               &-separated list of id(s) to delete.
                   5276: #       $client               - File open on client socket.
                   5277: # Returns:
                   5278: #     1   - Continue processing
                   5279: #     0   - Exit server.
                   5280: #     
                   5281: #
                   5282: 
                   5283: sub del_id_handler {
                   5284:     my ($cmd,$tail,$client) = @_;
                   5285: 
                   5286:     my $userinput = "$cmd:$tail";
                   5287: 
                   5288:     my ($udom,$what)=split(/:/,$tail);
                   5289:     chomp($what);
                   5290:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   5291:                                    "D", $what);
                   5292:     if ($hashref) {
                   5293:         my @keys=split(/\&/,$what);
                   5294:         foreach my $key (@keys) {
                   5295:             delete($hashref->{$key});
                   5296:         }
                   5297:         if (&untie_user_hash($hashref)) {
                   5298:             &Reply($client, "ok\n", $userinput);
                   5299:         } else {
                   5300:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5301:                     "while attempting iddel\n", $userinput);
                   5302:         }
                   5303:     } else {
                   5304:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5305:                  "while attempting iddel\n", $userinput);
                   5306:     }
                   5307:     return 1;
                   5308: }
                   5309: &register_handler("iddel", \&del_id_handler, 0, 1, 0);
                   5310: 
1.238     foxr     5311: #
1.299     raeburn  5312: # Puts broadcast e-mail sent by Domain Coordinator in nohist_dcmail database 
                   5313: #
                   5314: # Parameters
                   5315: #   $cmd       - Command keyword that caused us to be dispatched.
                   5316: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5317: #               domain - the domain whose dcmail we are recording
                   5318: #               email    Consists of key=value pair 
                   5319: #                        where key is unique msgid
                   5320: #                        and value is message (in XML)
                   5321: #   $client    - Socket open on the client.
                   5322: #
                   5323: # Returns:
                   5324: #    1 - indicating processing should continue.
                   5325: # Side effects
                   5326: #     reply is written to $client.
                   5327: #
                   5328: sub put_dcmail_handler {
                   5329:     my ($cmd,$tail,$client) = @_;
                   5330:     my $userinput = "$cmd:$tail";
1.463     foxr     5331: 
                   5332: 
1.299     raeburn  5333:     my ($udom,$what)=split(/:/,$tail);
                   5334:     chomp($what);
                   5335:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   5336:     if ($hashref) {
                   5337:         my ($key,$value)=split(/=/,$what);
                   5338:         $hashref->{$key}=$value;
                   5339:     }
1.311     albertel 5340:     if (&untie_domain_hash($hashref)) {
1.299     raeburn  5341:         &Reply($client, "ok\n", $userinput);
                   5342:     } else {
                   5343:         &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5344:                  "while attempting dcmailput\n", $userinput);
                   5345:     }
                   5346:     return 1;
                   5347: }
                   5348: &register_handler("dcmailput", \&put_dcmail_handler, 0, 1, 0);
                   5349: 
                   5350: #
                   5351: # Retrieves broadcast e-mail from nohist_dcmail database
                   5352: # Returns to client an & separated list of key=value pairs,
                   5353: # where key is msgid and value is message information.
                   5354: #
                   5355: # Parameters
                   5356: #   $cmd       - Command keyword that caused us to be dispatched.
                   5357: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5358: #               domain - the domain whose dcmail table we dump
                   5359: #               startfilter - beginning of time window 
                   5360: #               endfilter - end of time window
                   5361: #               sendersfilter - & separated list of username:domain 
                   5362: #                 for senders to search for.
                   5363: #   $client    - Socket open on the client.
                   5364: #
                   5365: # Returns:
                   5366: #    1 - indicating processing should continue.
                   5367: # Side effects
                   5368: #     reply (& separated list of msgid=messageinfo pairs) is 
                   5369: #     written to $client.
                   5370: #
                   5371: sub dump_dcmail_handler {
                   5372:     my ($cmd, $tail, $client) = @_;
                   5373:                                                                                 
                   5374:     my $userinput = "$cmd:$tail";
                   5375:     my ($udom,$startfilter,$endfilter,$sendersfilter) = split(/:/,$tail);
                   5376:     chomp($sendersfilter);
                   5377:     my @senders = ();
                   5378:     if (defined($startfilter)) {
                   5379:         $startfilter=&unescape($startfilter);
                   5380:     } else {
                   5381:         $startfilter='.';
                   5382:     }
                   5383:     if (defined($endfilter)) {
                   5384:         $endfilter=&unescape($endfilter);
                   5385:     } else {
                   5386:         $endfilter='.';
                   5387:     }
                   5388:     if (defined($sendersfilter)) {
                   5389:         $sendersfilter=&unescape($sendersfilter);
1.300     albertel 5390: 	@senders = map { &unescape($_) } split(/\&/,$sendersfilter);
1.299     raeburn  5391:     }
                   5392: 
                   5393:     my $qresult='';
                   5394:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   5395:     if ($hashref) {
                   5396:         while (my ($key,$value) = each(%$hashref)) {
                   5397:             my $match = 1;
1.303     albertel 5398:             my ($timestamp,$subj,$uname,$udom) = 
                   5399: 		split(/:/,&unescape(&unescape($key)),5); # yes, twice really
1.299     raeburn  5400:             $subj = &unescape($subj);
                   5401:             unless ($startfilter eq '.' || !defined($startfilter)) {
                   5402:                 if ($timestamp < $startfilter) {
                   5403:                     $match = 0;
                   5404:                 }
                   5405:             }
                   5406:             unless ($endfilter eq '.' || !defined($endfilter)) {
                   5407:                 if ($timestamp > $endfilter) {
                   5408:                     $match = 0;
                   5409:                 }
                   5410:             }
                   5411:             unless (@senders < 1) {
                   5412:                 unless (grep/^$uname:$udom$/,@senders) {
                   5413:                     $match = 0;
                   5414:                 }
                   5415:             }
                   5416:             if ($match == 1) {
                   5417:                 $qresult.=$key.'='.$value.'&';
                   5418:             }
                   5419:         }
1.311     albertel 5420:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5421:             chop($qresult);
1.387     albertel 5422:             &Reply($client, \$qresult, $userinput);
1.299     raeburn  5423:         } else {
                   5424:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5425:                     "while attempting dcmaildump\n", $userinput);
                   5426:         }
                   5427:     } else {
                   5428:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5429:                 "while attempting dcmaildump\n", $userinput);
                   5430:     }
                   5431:     return 1;
                   5432: }
                   5433: 
                   5434: &register_handler("dcmaildump", \&dump_dcmail_handler, 0, 1, 0);
                   5435: 
                   5436: #
                   5437: # Puts domain roles in nohist_domainroles database
                   5438: #
                   5439: # Parameters
                   5440: #   $cmd       - Command keyword that caused us to be dispatched.
                   5441: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5442: #               domain - the domain whose roles we are recording  
                   5443: #               role -   Consists of key=value pair
                   5444: #                        where key is unique role
                   5445: #                        and value is start/end date information
                   5446: #   $client    - Socket open on the client.
                   5447: #
                   5448: # Returns:
                   5449: #    1 - indicating processing should continue.
                   5450: # Side effects
                   5451: #     reply is written to $client.
                   5452: #
                   5453: 
                   5454: sub put_domainroles_handler {
                   5455:     my ($cmd,$tail,$client) = @_;
                   5456: 
                   5457:     my $userinput = "$cmd:$tail";
                   5458:     my ($udom,$what)=split(/:/,$tail);
                   5459:     chomp($what);
                   5460:     my @pairs=split(/\&/,$what);
                   5461:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   5462:     if ($hashref) {
                   5463:         foreach my $pair (@pairs) {
                   5464:             my ($key,$value)=split(/=/,$pair);
                   5465:             $hashref->{$key}=$value;
                   5466:         }
1.311     albertel 5467:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5468:             &Reply($client, "ok\n", $userinput);
                   5469:         } else {
                   5470:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5471:                      "while attempting domroleput\n", $userinput);
                   5472:         }
                   5473:     } else {
                   5474:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5475:                   "while attempting domroleput\n", $userinput);
                   5476:     }
                   5477:                                                                                   
                   5478:     return 1;
                   5479: }
                   5480: 
                   5481: &register_handler("domroleput", \&put_domainroles_handler, 0, 1, 0);
                   5482: 
                   5483: #
                   5484: # Retrieves domain roles from nohist_domainroles database
                   5485: # Returns to client an & separated list of key=value pairs,
                   5486: # where key is role and value is start and end date information.
                   5487: #
                   5488: # Parameters
                   5489: #   $cmd       - Command keyword that caused us to be dispatched.
                   5490: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5491: #               domain - the domain whose domain roles table we dump
                   5492: #   $client    - Socket open on the client.
                   5493: #
                   5494: # Returns:
                   5495: #    1 - indicating processing should continue.
                   5496: # Side effects
                   5497: #     reply (& separated list of role=start/end info pairs) is
                   5498: #     written to $client.
                   5499: #
                   5500: sub dump_domainroles_handler {
                   5501:     my ($cmd, $tail, $client) = @_;
                   5502:                                                                                            
                   5503:     my $userinput = "$cmd:$tail";
                   5504:     my ($udom,$startfilter,$endfilter,$rolesfilter) = split(/:/,$tail);
                   5505:     chomp($rolesfilter);
                   5506:     my @roles = ();
                   5507:     if (defined($startfilter)) {
                   5508:         $startfilter=&unescape($startfilter);
                   5509:     } else {
                   5510:         $startfilter='.';
                   5511:     }
                   5512:     if (defined($endfilter)) {
                   5513:         $endfilter=&unescape($endfilter);
                   5514:     } else {
                   5515:         $endfilter='.';
                   5516:     }
                   5517:     if (defined($rolesfilter)) {
                   5518:         $rolesfilter=&unescape($rolesfilter);
1.300     albertel 5519: 	@roles = split(/\&/,$rolesfilter);
1.299     raeburn  5520:     }
1.421     raeburn  5521: 
1.299     raeburn  5522:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   5523:     if ($hashref) {
                   5524:         my $qresult = '';
                   5525:         while (my ($key,$value) = each(%$hashref)) {
                   5526:             my $match = 1;
1.421     raeburn  5527:             my ($end,$start) = split(/:/,&unescape($value));
1.299     raeburn  5528:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,&unescape($key));
1.421     raeburn  5529:             unless (@roles < 1) {
                   5530:                 unless (grep/^\Q$trole\E$/,@roles) {
                   5531:                     $match = 0;
                   5532:                     next;
                   5533:                 }
                   5534:             }
1.299     raeburn  5535:             unless ($startfilter eq '.' || !defined($startfilter)) {
1.415     raeburn  5536:                 if ((defined($start)) && ($start >= $startfilter)) {
1.299     raeburn  5537:                     $match = 0;
1.421     raeburn  5538:                     next;
1.299     raeburn  5539:                 }
                   5540:             }
                   5541:             unless ($endfilter eq '.' || !defined($endfilter)) {
1.421     raeburn  5542:                 if ((defined($end)) && (($end > 0) && ($end <= $endfilter))) {
1.299     raeburn  5543:                     $match = 0;
1.421     raeburn  5544:                     next;
1.299     raeburn  5545:                 }
                   5546:             }
                   5547:             if ($match == 1) {
                   5548:                 $qresult.=$key.'='.$value.'&';
                   5549:             }
                   5550:         }
1.311     albertel 5551:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5552:             chop($qresult);
1.387     albertel 5553:             &Reply($client, \$qresult, $userinput);
1.299     raeburn  5554:         } else {
                   5555:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5556:                     "while attempting domrolesdump\n", $userinput);
                   5557:         }
                   5558:     } else {
                   5559:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5560:                 "while attempting domrolesdump\n", $userinput);
                   5561:     }
                   5562:     return 1;
                   5563: }
                   5564: 
                   5565: &register_handler("domrolesdump", \&dump_domainroles_handler, 0, 1, 0);
                   5566: 
                   5567: 
1.238     foxr     5568: #  Process the tmpput command I'm not sure what this does.. Seems to
                   5569: #  create a file in the lonDaemons/tmp directory of the form $id.tmp
                   5570: # where Id is the client's ip concatenated with a sequence number.
                   5571: # The file will contain some value that is passed in.  Is this e.g.
                   5572: # a login token?
                   5573: #
                   5574: # Parameters:
                   5575: #    $cmd     - The command that got us dispatched.
                   5576: #    $tail    - The remainder of the request following $cmd:
                   5577: #               In this case this will be the contents of the file.
                   5578: #    $client  - Socket connected to the client.
                   5579: # Returns:
                   5580: #    1 indicating processing can continue.
                   5581: # Side effects:
                   5582: #   A file is created in the local filesystem.
                   5583: #   A reply is sent to the client.
                   5584: sub tmp_put_handler {
                   5585:     my ($cmd, $what, $client) = @_;
                   5586: 
                   5587:     my $userinput = "$cmd:$what";	# Reconstruct for logging.
                   5588: 
1.347     raeburn  5589:     my ($record,$context) = split(/:/,$what);
                   5590:     if ($context ne '') {
                   5591:         chomp($context);
                   5592:         $context = &unescape($context);
                   5593:     }
                   5594:     my ($id,$store);
1.238     foxr     5595:     $tmpsnum++;
1.454     raeburn  5596:     if (($context eq 'resetpw') || ($context eq 'createaccount')) {
1.347     raeburn  5597:         $id = &md5_hex(&md5_hex(time.{}.rand().$$));
                   5598:     } else {
                   5599:         $id = $$.'_'.$clientip.'_'.$tmpsnum;
                   5600:     }
1.238     foxr     5601:     $id=~s/\W/\_/g;
1.347     raeburn  5602:     $record=~s/\n//g;
1.238     foxr     5603:     my $execdir=$perlvar{'lonDaemons'};
                   5604:     if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
1.347     raeburn  5605: 	print $store $record;
1.238     foxr     5606: 	close $store;
1.387     albertel 5607: 	&Reply($client, \$id, $userinput);
1.238     foxr     5608:     } else {
                   5609: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   5610: 		  "while attempting tmpput\n", $userinput);
                   5611:     }
                   5612:     return 1;
                   5613:   
                   5614: }
                   5615: &register_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
1.263     albertel 5616: 
1.238     foxr     5617: #   Processes the tmpget command.  This command returns the contents
                   5618: #  of a temporary resource file(?) created via tmpput.
                   5619: #
                   5620: # Paramters:
                   5621: #    $cmd      - Command that got us dispatched.
                   5622: #    $id       - Tail of the command, contain the id of the resource
                   5623: #                we want to fetch.
                   5624: #    $client   - socket open on the client.
                   5625: # Return:
                   5626: #    1         - Inidcating processing can continue.
                   5627: # Side effects:
                   5628: #   A reply is sent to the client.
                   5629: #
                   5630: sub tmp_get_handler {
                   5631:     my ($cmd, $id, $client) = @_;
                   5632: 
                   5633:     my $userinput = "$cmd:$id"; 
                   5634:     
                   5635: 
                   5636:     $id=~s/\W/\_/g;
                   5637:     my $store;
                   5638:     my $execdir=$perlvar{'lonDaemons'};
                   5639:     if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
                   5640: 	my $reply=<$store>;
1.387     albertel 5641: 	&Reply( $client, \$reply, $userinput);
1.238     foxr     5642: 	close $store;
                   5643:     } else {
                   5644: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   5645: 		  "while attempting tmpget\n", $userinput);
                   5646:     }
                   5647: 
                   5648:     return 1;
                   5649: }
                   5650: &register_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
1.263     albertel 5651: 
1.238     foxr     5652: #
                   5653: #  Process the tmpdel command.  This command deletes a temp resource
                   5654: #  created by the tmpput command.
                   5655: #
                   5656: # Parameters:
                   5657: #   $cmd      - Command that got us here.
                   5658: #   $id       - Id of the temporary resource created.
                   5659: #   $client   - socket open on the client process.
                   5660: #
                   5661: # Returns:
                   5662: #   1     - Indicating processing should continue.
                   5663: # Side Effects:
                   5664: #   A file is deleted
                   5665: #   A reply is sent to the client.
                   5666: sub tmp_del_handler {
                   5667:     my ($cmd, $id, $client) = @_;
                   5668:     
                   5669:     my $userinput= "$cmd:$id";
                   5670:     
                   5671:     chomp($id);
                   5672:     $id=~s/\W/\_/g;
                   5673:     my $execdir=$perlvar{'lonDaemons'};
                   5674:     if (unlink("$execdir/tmp/$id.tmp")) {
                   5675: 	&Reply($client, "ok\n", $userinput);
                   5676:     } else {
                   5677: 	&Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
                   5678: 		  "while attempting tmpdel\n", $userinput);
                   5679:     }
                   5680:     
                   5681:     return 1;
                   5682: 
                   5683: }
                   5684: &register_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
1.263     albertel 5685: 
1.238     foxr     5686: #
1.564   ! raeburn  5687: #  Process the updatebalcookie command.  This command updates a
        !          5688: #  cookie in the lonBalancedir directory on a load balancer node.
        !          5689: #
        !          5690: # Parameters:
        !          5691: #   $cmd      - Command that got us here.
        !          5692: #   $tail     - Tail of the request (escaped cookie: escaped current entry)
        !          5693: #
        !          5694: #   $client   - socket open on the client process.
        !          5695: #
        !          5696: # Returns:
        !          5697: #   1     - Indicating processing should continue.
        !          5698: # Side Effects:
        !          5699: #   A cookie file is updated from the lonBalancedir directory
        !          5700: #   A reply is sent to the client.
        !          5701: #
        !          5702: sub update_balcookie_handler {
        !          5703:     my ($cmd, $tail, $client) = @_;
        !          5704: 
        !          5705:     my $userinput= "$cmd:$tail";
        !          5706:     chomp($tail);
        !          5707:     my ($cookie,$lastentry) = map { &unescape($_) } (split(/:/,$tail));
        !          5708: 
        !          5709:     my $updatedone;
        !          5710:     if ($cookie =~ /^$LONCAPA::match_domain\_$LONCAPA::match_username\_[a-f0-9]{32}$/) {
        !          5711:         my $execdir=$perlvar{'lonBalanceDir'};
        !          5712:         if (-e "$execdir/$cookie.id") {
        !          5713:             my $doupdate;
        !          5714:             if (open(my $fh,'<',"$execdir/$cookie.id")) {
        !          5715:                 while (my $line = <$fh>) {
        !          5716:                     chomp($line);
        !          5717:                     if ($line eq $lastentry) {
        !          5718:                         $doupdate = 1;
        !          5719:                         last;
        !          5720:                     }
        !          5721:                 }
        !          5722:                 close($fh);
        !          5723:             }
        !          5724:             if ($doupdate) {
        !          5725:                 if (open(my $fh,'>',"$execdir/$cookie.id")) {
        !          5726:                     print $fh $clientname;
        !          5727:                     close($fh);
        !          5728:                     $updatedone = 1;
        !          5729:                 }
        !          5730:             }
        !          5731:         }
        !          5732:     }
        !          5733:     if ($updatedone) {
        !          5734:         &Reply($client, "ok\n", $userinput);
        !          5735:     } else {
        !          5736:         &Failure( $client, "error: ".($!+0)."file update failed ".
        !          5737:                   "while attempting updatebalcookie\n", $userinput);
        !          5738:     }
        !          5739:     return 1;
        !          5740: }
        !          5741: &register_handler("updatebalcookie", \&update_balcookie_handler, 0, 1, 0);
        !          5742: 
        !          5743: #
1.551     raeburn  5744: #  Process the delbalcookie command. This command deletes a balancer
1.564   ! raeburn  5745: #  cookie in the lonBalancedir directory on a load balancer node.
1.551     raeburn  5746: #
                   5747: # Parameters:
                   5748: #   $cmd      - Command that got us here.
                   5749: #   $cookie   - Cookie to be deleted.
                   5750: #   $client   - socket open on the client process.
                   5751: #
                   5752: # Returns:
                   5753: #   1     - Indicating processing should continue.
                   5754: # Side Effects:
                   5755: #   A cookie file is deleted from the lonBalancedir directory
                   5756: #   A reply is sent to the client.
                   5757: sub del_balcookie_handler {
                   5758:     my ($cmd, $cookie, $client) = @_;
                   5759: 
                   5760:     my $userinput= "$cmd:$cookie";
                   5761: 
                   5762:     chomp($cookie);
1.564   ! raeburn  5763:     $cookie = &unescape($cookie);
1.551     raeburn  5764:     my $deleted = '';
                   5765:     if ($cookie =~ /^$LONCAPA::match_domain\_$LONCAPA::match_username\_[a-f0-9]{32}$/) {
                   5766:         my $execdir=$perlvar{'lonBalanceDir'};
                   5767:         if (-e "$execdir/$cookie.id") {
                   5768:             if (open(my $fh,'<',"$execdir/$cookie.id")) {
                   5769:                 my $dodelete;
                   5770:                 while (my $line = <$fh>) {
                   5771:                     chomp($line);
                   5772:                     if ($line eq $clientname) {
                   5773:                         $dodelete = 1;
1.554     raeburn  5774:                         last;
1.551     raeburn  5775:                     }
                   5776:                 }
1.554     raeburn  5777:                 close($fh);
1.551     raeburn  5778:                 if ($dodelete) {
                   5779:                     if (unlink("$execdir/$cookie.id")) {
                   5780:                         $deleted = 1;
                   5781:                     }
                   5782:                 }
                   5783:             }
                   5784:         }
                   5785:     }
                   5786:     if ($deleted) {
                   5787:         &Reply($client, "ok\n", $userinput);
                   5788:     } else {
                   5789:         &Failure( $client, "error: ".($!+0)."Unlinking cookie file Failed ".
                   5790:                   "while attempting delbalcookie\n", $userinput);
                   5791:     }
                   5792:     return 1;
                   5793: }
                   5794: &register_handler("delbalcookie", \&del_balcookie_handler, 0, 1, 0);
                   5795: 
                   5796: #
1.246     foxr     5797: #   Processes the setannounce command.  This command
                   5798: #   creates a file named announce.txt in the top directory of
                   5799: #   the documentn root and sets its contents.  The announce.txt file is
                   5800: #   printed in its entirety at the LonCAPA login page.  Note:
                   5801: #   once the announcement.txt fileis created it cannot be deleted.
                   5802: #   However, setting the contents of the file to empty removes the
                   5803: #   announcement from the login page of loncapa so who cares.
                   5804: #
                   5805: # Parameters:
                   5806: #    $cmd          - The command that got us dispatched.
                   5807: #    $announcement - The text of the announcement.
                   5808: #    $client       - Socket open on the client process.
                   5809: # Retunrns:
                   5810: #   1             - Indicating request processing should continue
                   5811: # Side Effects:
                   5812: #   The file {DocRoot}/announcement.txt is created.
                   5813: #   A reply is sent to $client.
                   5814: #
                   5815: sub set_announce_handler {
                   5816:     my ($cmd, $announcement, $client) = @_;
                   5817:   
                   5818:     my $userinput    = "$cmd:$announcement";
                   5819: 
                   5820:     chomp($announcement);
                   5821:     $announcement=&unescape($announcement);
                   5822:     if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
                   5823: 				'/announcement.txt')) {
                   5824: 	print $store $announcement;
                   5825: 	close $store;
                   5826: 	&Reply($client, "ok\n", $userinput);
                   5827:     } else {
                   5828: 	&Failure($client, "error: ".($!+0)."\n", $userinput);
                   5829:     }
                   5830: 
                   5831:     return 1;
                   5832: }
                   5833: &register_handler("setannounce", \&set_announce_handler, 0, 1, 0);
1.263     albertel 5834: 
1.246     foxr     5835: #
                   5836: #  Return the version of the daemon.  This can be used to determine
                   5837: #  the compatibility of cross version installations or, alternatively to
                   5838: #  simply know who's out of date and who isn't.  Note that the version
                   5839: #  is returned concatenated with the tail.
                   5840: # Parameters:
                   5841: #   $cmd        - the request that dispatched to us.
                   5842: #   $tail       - Tail of the request (client's version?).
                   5843: #   $client     - Socket open on the client.
                   5844: #Returns:
                   5845: #   1 - continue processing requests.
                   5846: # Side Effects:
                   5847: #   Replies with version to $client.
                   5848: sub get_version_handler {
                   5849:     my ($cmd, $tail, $client) = @_;
                   5850: 
                   5851:     my $userinput  = $cmd.$tail;
                   5852:     
                   5853:     &Reply($client, &version($userinput)."\n", $userinput);
                   5854: 
                   5855: 
                   5856:     return 1;
                   5857: }
                   5858: &register_handler("version", \&get_version_handler, 0, 1, 0);
1.263     albertel 5859: 
1.246     foxr     5860: #  Set the current host and domain.  This is used to support
                   5861: #  multihomed systems.  Each IP of the system, or even separate daemons
                   5862: #  on the same IP can be treated as handling a separate lonCAPA virtual
                   5863: #  machine.  This command selects the virtual lonCAPA.  The client always
                   5864: #  knows the right one since it is lonc and it is selecting the domain/system
                   5865: #  from the hosts.tab file.
                   5866: # Parameters:
                   5867: #    $cmd      - Command that dispatched us.
                   5868: #    $tail     - Tail of the command (domain/host requested).
                   5869: #    $socket   - Socket open on the client.
                   5870: #
                   5871: # Returns:
                   5872: #     1   - Indicates the program should continue to process requests.
                   5873: # Side-effects:
                   5874: #     The default domain/system context is modified for this daemon.
                   5875: #     a reply is sent to the client.
                   5876: #
                   5877: sub set_virtual_host_handler {
                   5878:     my ($cmd, $tail, $socket) = @_;
                   5879:   
                   5880:     my $userinput  ="$cmd:$tail";
                   5881: 
                   5882:     &Reply($client, &sethost($userinput)."\n", $userinput);
                   5883: 
                   5884: 
                   5885:     return 1;
                   5886: }
1.247     albertel 5887: &register_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
1.246     foxr     5888: 
                   5889: #  Process a request to exit:
                   5890: #   - "bye" is sent to the client.
                   5891: #   - The client socket is shutdown and closed.
                   5892: #   - We indicate to the caller that we should exit.
                   5893: # Formal Parameters:
                   5894: #   $cmd                - The command that got us here.
                   5895: #   $tail               - Tail of the command (empty).
                   5896: #   $client             - Socket open on the tail.
                   5897: # Returns:
                   5898: #   0      - Indicating the program should exit!!
                   5899: #
                   5900: sub exit_handler {
                   5901:     my ($cmd, $tail, $client) = @_;
                   5902: 
                   5903:     my $userinput = "$cmd:$tail";
                   5904: 
                   5905:     &logthis("Client $clientip ($clientname) hanging up: $userinput");
                   5906:     &Reply($client, "bye\n", $userinput);
                   5907:     $client->shutdown(2);        # shutdown the socket forcibly.
                   5908:     $client->close();
                   5909: 
                   5910:     return 0;
                   5911: }
1.248     foxr     5912: &register_handler("exit", \&exit_handler, 0,1,1);
                   5913: &register_handler("init", \&exit_handler, 0,1,1);
                   5914: &register_handler("quit", \&exit_handler, 0,1,1);
                   5915: 
                   5916: #  Determine if auto-enrollment is enabled.
                   5917: #  Note that the original had what I believe to be a defect.
                   5918: #  The original returned 0 if the requestor was not a registerd client.
                   5919: #  It should return "refused".
                   5920: # Formal Parameters:
                   5921: #   $cmd       - The command that invoked us.
                   5922: #   $tail      - The tail of the command (Extra command parameters.
                   5923: #   $client    - The socket open on the client that issued the request.
                   5924: # Returns:
                   5925: #    1         - Indicating processing should continue.
                   5926: #
                   5927: sub enrollment_enabled_handler {
                   5928:     my ($cmd, $tail, $client) = @_;
                   5929:     my $userinput = $cmd.":".$tail; # For logging purposes.
                   5930: 
                   5931:     
1.337     albertel 5932:     my ($cdom) = split(/:/, $tail, 2);   # Domain we're asking about.
                   5933: 
1.248     foxr     5934:     my $outcome  = &localenroll::run($cdom);
1.387     albertel 5935:     &Reply($client, \$outcome, $userinput);
1.248     foxr     5936: 
                   5937:     return 1;
                   5938: }
                   5939: &register_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
                   5940: 
1.417     raeburn  5941: #
1.423     raeburn  5942: #   Validate an institutional code used for a LON-CAPA course.          
1.417     raeburn  5943: #
                   5944: # Formal Parameters:
                   5945: #   $cmd          - The command request that got us dispatched.
                   5946: #   $tail         - The tail of the command.  In this case,
                   5947: #                   this is a colon separated set of words that will be split
                   5948: #                   into:
1.424     raeburn  5949: #                        $dom      - The domain for which the check of 
                   5950: #                                    institutional course code will occur.
                   5951: #
                   5952: #                        $instcode - The institutional code for the course
                   5953: #                                    being requested, or validated for rights
                   5954: #                                    to request.
                   5955: #
                   5956: #                        $owner    - The course requestor (who will be the
                   5957: #                                    course owner, in the form username:domain
                   5958: #
1.417     raeburn  5959: #   $client       - Socket open on the client.
                   5960: # Returns:
                   5961: #    1           - Indicating processing should continue.
                   5962: #
                   5963: sub validate_instcode_handler {
                   5964:     my ($cmd, $tail, $client) = @_;
                   5965:     my $userinput = "$cmd:$tail";
1.423     raeburn  5966:     my ($dom,$instcode,$owner) = split(/:/, $tail);
1.422     raeburn  5967:     $instcode = &unescape($instcode);
                   5968:     $owner = &unescape($owner);
1.498     raeburn  5969:     my ($outcome,$description,$credits) = 
1.426     raeburn  5970:         &localenroll::validate_instcode($dom,$instcode,$owner);
1.498     raeburn  5971:     my $result = &escape($outcome).'&'.&escape($description).'&'.
                   5972:                  &escape($credits);
1.426     raeburn  5973:     &Reply($client, \$result, $userinput);
1.417     raeburn  5974: 
                   5975:     return 1;
                   5976: }
                   5977: &register_handler("autovalidateinstcode", \&validate_instcode_handler, 0, 1, 0);
                   5978: 
1.248     foxr     5979: #   Get the official sections for which auto-enrollment is possible.
                   5980: #   Since the admin people won't know about 'unofficial sections' 
                   5981: #   we cannot auto-enroll on them.
                   5982: # Formal Parameters:
                   5983: #    $cmd     - The command request that got us dispatched here.
                   5984: #    $tail    - The remainder of the request.  In our case this
                   5985: #               will be split into:
                   5986: #               $coursecode   - The course name from the admin point of view.
                   5987: #               $cdom         - The course's domain(?).
                   5988: #    $client  - Socket open on the client.
                   5989: # Returns:
                   5990: #    1    - Indiciting processing should continue.
                   5991: #
                   5992: sub get_sections_handler {
                   5993:     my ($cmd, $tail, $client) = @_;
                   5994:     my $userinput = "$cmd:$tail";
                   5995: 
                   5996:     my ($coursecode, $cdom) = split(/:/, $tail);
                   5997:     my @secs = &localenroll::get_sections($coursecode,$cdom);
                   5998:     my $seclist = &escape(join(':',@secs));
                   5999: 
1.387     albertel 6000:     &Reply($client, \$seclist, $userinput);
1.248     foxr     6001:     
                   6002: 
                   6003:     return 1;
                   6004: }
                   6005: &register_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
                   6006: 
                   6007: #   Validate the owner of a new course section.  
                   6008: #
                   6009: # Formal Parameters:
                   6010: #   $cmd      - Command that got us dispatched.
                   6011: #   $tail     - the remainder of the command.  For us this consists of a
                   6012: #               colon separated string containing:
                   6013: #                  $inst    - Course Id from the institutions point of view.
                   6014: #                  $owner   - Proposed owner of the course.
                   6015: #                  $cdom    - Domain of the course (from the institutions
                   6016: #                             point of view?)..
                   6017: #   $client   - Socket open on the client.
                   6018: #
                   6019: # Returns:
                   6020: #   1        - Processing should continue.
                   6021: #
                   6022: sub validate_course_owner_handler {
                   6023:     my ($cmd, $tail, $client)  = @_;
                   6024:     my $userinput = "$cmd:$tail";
1.470     raeburn  6025:     my ($inst_course_id, $owner, $cdom, $coowners) = split(/:/, $tail);
                   6026:     
1.336     raeburn  6027:     $owner = &unescape($owner);
1.470     raeburn  6028:     $coowners = &unescape($coowners);
                   6029:     my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom,$coowners);
1.387     albertel 6030:     &Reply($client, \$outcome, $userinput);
1.248     foxr     6031: 
                   6032: 
                   6033: 
                   6034:     return 1;
                   6035: }
                   6036: &register_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
1.263     albertel 6037: 
1.248     foxr     6038: #
                   6039: #   Validate a course section in the official schedule of classes
                   6040: #   from the institutions point of view (part of autoenrollment).
                   6041: #
                   6042: # Formal Parameters:
                   6043: #   $cmd          - The command request that got us dispatched.
                   6044: #   $tail         - The tail of the command.  In this case,
                   6045: #                   this is a colon separated set of words that will be split
                   6046: #                   into:
                   6047: #                        $inst_course_id - The course/section id from the
                   6048: #                                          institutions point of view.
                   6049: #                        $cdom           - The domain from the institutions
                   6050: #                                          point of view.
                   6051: #   $client       - Socket open on the client.
                   6052: # Returns:
                   6053: #    1           - Indicating processing should continue.
                   6054: #
                   6055: sub validate_course_section_handler {
                   6056:     my ($cmd, $tail, $client) = @_;
                   6057:     my $userinput = "$cmd:$tail";
                   6058:     my ($inst_course_id, $cdom) = split(/:/, $tail);
                   6059: 
                   6060:     my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
1.387     albertel 6061:     &Reply($client, \$outcome, $userinput);
1.248     foxr     6062: 
                   6063: 
                   6064:     return 1;
                   6065: }
                   6066: &register_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
                   6067: 
                   6068: #
1.340     raeburn  6069: #   Validate course owner's access to enrollment data for specific class section. 
                   6070: #   
                   6071: #
                   6072: # Formal Parameters:
                   6073: #    $cmd     - The command request that got us dispatched.
                   6074: #    $tail    - The tail of the command.   In this case this is a colon separated
1.542     raeburn  6075: #               set of values that will be split into:
1.340     raeburn  6076: #               $inst_class  - Institutional code for the specific class section   
1.542     raeburn  6077: #               $ownerlist   - An escaped comma-separated list of username:domain 
                   6078: #                              of the course owner, and co-owner(s).
1.340     raeburn  6079: #               $cdom        - The domain of the course from the institution's
                   6080: #                              point of view.
                   6081: #    $client  - The socket open on the client.
                   6082: # Returns:
                   6083: #    1 - continue processing.
                   6084: #
                   6085: 
                   6086: sub validate_class_access_handler {
                   6087:     my ($cmd, $tail, $client) = @_;
                   6088:     my $userinput = "$cmd:$tail";
1.383     raeburn  6089:     my ($inst_class,$ownerlist,$cdom) = split(/:/, $tail);
1.392     raeburn  6090:     my $owners = &unescape($ownerlist);
1.341     albertel 6091:     my $outcome;
                   6092:     eval {
                   6093: 	local($SIG{__DIE__})='DEFAULT';
1.392     raeburn  6094: 	$outcome=&localenroll::check_section($inst_class,$owners,$cdom);
1.341     albertel 6095:     };
1.387     albertel 6096:     &Reply($client,\$outcome, $userinput);
1.340     raeburn  6097: 
                   6098:     return 1;
                   6099: }
                   6100: &register_handler("autovalidateclass_sec", \&validate_class_access_handler, 0, 1, 0);
                   6101: 
                   6102: #
1.542     raeburn  6103: #   Validate course owner or co-owners(s) access to enrollment data for all sections
                   6104: #   and crosslistings for a particular course.
                   6105: #
                   6106: #
                   6107: # Formal Parameters:
                   6108: #    $cmd     - The command request that got us dispatched.
                   6109: #    $tail    - The tail of the command.   In this case this is a colon separated
                   6110: #               set of values that will be split into:
                   6111: #               $ownerlist   - An escaped comma-separated list of username:domain
                   6112: #                              of the course owner, and co-owner(s).
                   6113: #               $cdom        - The domain of the course from the institution's
                   6114: #                              point of view.
                   6115: #               $classes     - Frozen hash of institutional course sections and
                   6116: #                              crosslistings.
                   6117: #    $client  - The socket open on the client.
                   6118: # Returns:
                   6119: #    1 - continue processing.
                   6120: #
                   6121: 
                   6122: sub validate_classes_handler {
                   6123:     my ($cmd, $tail, $client) = @_;
                   6124:     my $userinput = "$cmd:$tail";
                   6125:     my ($ownerlist,$cdom,$classes) = split(/:/, $tail);
                   6126:     my $classesref = &Apache::lonnet::thaw_unescape($classes);
                   6127:     my $owners = &unescape($ownerlist);
                   6128:     my $result;
                   6129:     eval {
                   6130:         local($SIG{__DIE__})='DEFAULT';
                   6131:         my %validations;
                   6132:         my $response = &localenroll::check_instclasses($owners,$cdom,$classesref,
                   6133:                                                        \%validations);
                   6134:         if ($response eq 'ok') {
                   6135:             foreach my $key (keys(%validations)) {
                   6136:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
                   6137:             }
                   6138:             $result =~ s/\&$//;
                   6139:         } else {
                   6140:             $result = 'error';
                   6141:         }
                   6142:     };
                   6143:     if (!$@) {
                   6144:         &Reply($client, \$result, $userinput);
                   6145:     } else {
                   6146:         &Failure($client,"unknown_cmd\n",$userinput);
                   6147:     }
                   6148:     return 1;
                   6149: }
                   6150: &register_handler("autovalidateinstclasses", \&validate_classes_handler, 0, 1, 0);
                   6151: 
                   6152: #
1.340     raeburn  6153: #   Create a password for a new LON-CAPA user added by auto-enrollment.
                   6154: #   Only used for case where authentication method for new user is localauth
1.248     foxr     6155: #
                   6156: # Formal Parameters:
                   6157: #    $cmd     - The command request that got us dispatched.
                   6158: #    $tail    - The tail of the command.   In this case this is a colon separated
                   6159: #               set of words that will be split into:
1.340     raeburn  6160: #               $authparam - An authentication parameter (localauth parameter).
1.248     foxr     6161: #               $cdom      - The domain of the course from the institution's
                   6162: #                            point of view.
                   6163: #    $client  - The socket open on the client.
                   6164: # Returns:
                   6165: #    1 - continue processing.
                   6166: #
                   6167: sub create_auto_enroll_password_handler {
                   6168:     my ($cmd, $tail, $client) = @_;
                   6169:     my $userinput = "$cmd:$tail";
                   6170: 
                   6171:     my ($authparam, $cdom) = split(/:/, $userinput);
                   6172: 
                   6173:     my ($create_passwd,$authchk);
                   6174:     ($authparam,
                   6175:      $create_passwd,
                   6176:      $authchk) = &localenroll::create_password($authparam,$cdom);
                   6177: 
                   6178:     &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
                   6179: 	   $userinput);
                   6180: 
                   6181: 
                   6182:     return 1;
                   6183: }
                   6184: &register_handler("autocreatepassword", \&create_auto_enroll_password_handler, 
                   6185: 		  0, 1, 0);
                   6186: 
1.522     raeburn  6187: sub auto_export_grades_handler {
                   6188:     my ($cmd, $tail, $client) = @_;
                   6189:     my $userinput = "$cmd:$tail";
                   6190:     my ($cdom,$cnum,$info,$data) = split(/:/,$tail);
                   6191:     my $inforef = &Apache::lonnet::thaw_unescape($info);
                   6192:     my $dataref = &Apache::lonnet::thaw_unescape($data);
                   6193:     my ($outcome,$result);;
                   6194:     eval {
                   6195:         local($SIG{__DIE__})='DEFAULT';
                   6196:         my %rtnhash;
                   6197:         $outcome=&localenroll::export_grades($cdom,$cnum,$inforef,$dataref,\%rtnhash);
                   6198:         if ($outcome eq 'ok') {
                   6199:             foreach my $key (keys(%rtnhash)) {
                   6200:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
                   6201:             }
                   6202:             $result =~ s/\&$//;
                   6203:         }
                   6204:     };
                   6205:     if (!$@) {
                   6206:         if ($outcome eq 'ok') {
                   6207:             if ($cipher) {
                   6208:                 my $cmdlength=length($result);
                   6209:                 $result.="         ";
                   6210:                 my $encresult='';
                   6211:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   6212:                     $encresult.= unpack("H16",
                   6213:                                         $cipher->encrypt(substr($result,
                   6214:                                                                 $encidx,
                   6215:                                                                 8)));
                   6216:                 }
                   6217:                 &Reply( $client, "enc:$cmdlength:$encresult\n", $userinput);
                   6218:             } else {
                   6219:                 &Failure( $client, "error:no_key\n", $userinput);
                   6220:             }
                   6221:         } else {
                   6222:             &Reply($client, "$outcome\n", $userinput);
                   6223:         }
                   6224:     } else {
                   6225:         &Failure($client,"export_error\n",$userinput);
                   6226:     }
                   6227:     return 1;
                   6228: }
                   6229: &register_handler("autoexportgrades", \&auto_export_grades_handler,
1.536     raeburn  6230:                   1, 1, 0);
1.522     raeburn  6231: 
1.248     foxr     6232: #   Retrieve and remove temporary files created by/during autoenrollment.
                   6233: #
                   6234: # Formal Parameters:
                   6235: #    $cmd      - The command that got us dispatched.
                   6236: #    $tail     - The tail of the command.  In our case this is a colon 
                   6237: #                separated list that will be split into:
1.526     raeburn  6238: #                $filename - The name of the file to retrieve.
1.248     foxr     6239: #                            The filename is given as a path relative to
                   6240: #                            the LonCAPA temp file directory.
                   6241: #    $client   - Socket open on the client.
                   6242: #
                   6243: # Returns:
                   6244: #   1     - Continue processing.
                   6245: sub retrieve_auto_file_handler {
                   6246:     my ($cmd, $tail, $client)    = @_;
                   6247:     my $userinput                = "cmd:$tail";
                   6248: 
                   6249:     my ($filename)   = split(/:/, $tail);
                   6250: 
                   6251:     my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
1.521     raeburn  6252: 
                   6253:     if ($filename =~m{/\.\./}) {
                   6254:         &Failure($client, "refused\n", $userinput);
1.526     raeburn  6255:     } elsif ($filename !~ /^$LONCAPA::match_domain\_$LONCAPA::match_courseid\_.+_classlist\.xml$/) {
                   6256:         &Failure($client, "refused\n", $userinput);
1.521     raeburn  6257:     } elsif ( (-e $source) && ($filename ne '') ) {
1.248     foxr     6258: 	my $reply = '';
                   6259: 	if (open(my $fh,$source)) {
                   6260: 	    while (<$fh>) {
                   6261: 		chomp($_);
                   6262: 		$_ =~ s/^\s+//g;
                   6263: 		$_ =~ s/\s+$//g;
                   6264: 		$reply .= $_;
                   6265: 	    }
                   6266: 	    close($fh);
                   6267: 	    &Reply($client, &escape($reply)."\n", $userinput);
                   6268: 
                   6269: #   Does this have to be uncommented??!?  (RF).
                   6270: #
                   6271: #                                unlink($source);
                   6272: 	} else {
                   6273: 	    &Failure($client, "error\n", $userinput);
                   6274: 	}
                   6275:     } else {
                   6276: 	&Failure($client, "error\n", $userinput);
                   6277:     }
                   6278:     
                   6279: 
                   6280:     return 1;
                   6281: }
                   6282: &register_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
                   6283: 
1.423     raeburn  6284: sub crsreq_checks_handler {
                   6285:     my ($cmd, $tail, $client) = @_;
                   6286:     my $userinput = "$cmd:$tail";
                   6287:     my $dom = $tail;
                   6288:     my $result;
1.519     raeburn  6289:     my @reqtypes = ('official','unofficial','community','textbook','placement');
1.423     raeburn  6290:     eval {
                   6291:         local($SIG{__DIE__})='DEFAULT';
                   6292:         my %validations;
1.424     raeburn  6293:         my $response = &localenroll::crsreq_checks($dom,\@reqtypes,
                   6294:                                                    \%validations);
1.423     raeburn  6295:         if ($response eq 'ok') { 
                   6296:             foreach my $key (keys(%validations)) {
                   6297:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
                   6298:             }
                   6299:             $result =~ s/\&$//;
                   6300:         } else {
                   6301:             $result = 'error';
                   6302:         }
                   6303:     };
                   6304:     if (!$@) {
                   6305:         &Reply($client, \$result, $userinput);
                   6306:     } else {
                   6307:         &Failure($client,"unknown_cmd\n",$userinput);
                   6308:     }
                   6309:     return 1;
                   6310: }
                   6311: &register_handler("autocrsreqchecks", \&crsreq_checks_handler, 0, 1, 0);
                   6312: 
                   6313: sub validate_crsreq_handler {
                   6314:     my ($cmd, $tail, $client) = @_;
                   6315:     my $userinput = "$cmd:$tail";
1.508     raeburn  6316:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$customdata) = split(/:/, $tail);
1.423     raeburn  6317:     $instcode = &unescape($instcode);
                   6318:     $owner = &unescape($owner);
                   6319:     $crstype = &unescape($crstype);
                   6320:     $inststatuslist = &unescape($inststatuslist);
                   6321:     $instcode = &unescape($instcode);
                   6322:     $instseclist = &unescape($instseclist);
1.508     raeburn  6323:     my $custominfo = &Apache::lonnet::thaw_unescape($customdata);
1.423     raeburn  6324:     my $outcome;
                   6325:     eval {
                   6326:         local($SIG{__DIE__})='DEFAULT';
                   6327:         $outcome = &localenroll::validate_crsreq($dom,$owner,$crstype,
                   6328:                                                  $inststatuslist,$instcode,
1.508     raeburn  6329:                                                  $instseclist,$custominfo);
1.423     raeburn  6330:     };
                   6331:     if (!$@) {
                   6332:         &Reply($client, \$outcome, $userinput);
                   6333:     } else {
                   6334:         &Failure($client,"unknown_cmd\n",$userinput);
                   6335:     }
                   6336:     return 1;
                   6337: }
                   6338: &register_handler("autocrsreqvalidation", \&validate_crsreq_handler, 0, 1, 0);
                   6339: 
1.506     raeburn  6340: sub crsreq_update_handler {
                   6341:     my ($cmd, $tail, $client) = @_;
                   6342:     my $userinput = "$cmd:$tail";
1.509     raeburn  6343:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,$code,
                   6344:         $accessstart,$accessend,$infohashref) =
1.506     raeburn  6345:         split(/:/, $tail);
                   6346:     $crstype = &unescape($crstype);
                   6347:     $action = &unescape($action);
                   6348:     $ownername = &unescape($ownername);
                   6349:     $ownerdomain = &unescape($ownerdomain);
                   6350:     $fullname = &unescape($fullname);
                   6351:     $title = &unescape($title);
                   6352:     $code = &unescape($code);
1.509     raeburn  6353:     $accessstart = &unescape($accessstart);
                   6354:     $accessend = &unescape($accessend);
1.506     raeburn  6355:     my $incoming = &Apache::lonnet::thaw_unescape($infohashref);
                   6356:     my ($result,$outcome);
                   6357:     eval {
                   6358:         local($SIG{__DIE__})='DEFAULT';
                   6359:         my %rtnhash;
                   6360:         $outcome = &localenroll::crsreq_updates($cdom,$cnum,$crstype,$action,
                   6361:                                                 $ownername,$ownerdomain,$fullname,
1.509     raeburn  6362:                                                 $title,$code,$accessstart,$accessend,
                   6363:                                                 $incoming,\%rtnhash);
1.506     raeburn  6364:         if ($outcome eq 'ok') {
1.515     raeburn  6365:             my @posskeys = qw(createdweb createdmsg createdcustomized createdactions queuedweb queuedmsg formitems reviewweb validationjs onload javascript);
1.506     raeburn  6366:             foreach my $key (keys(%rtnhash)) {
                   6367:                 if (grep(/^\Q$key\E/,@posskeys)) {
                   6368:                     $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
                   6369:                 }
                   6370:             }
                   6371:             $result =~ s/\&$//;
                   6372:         }
                   6373:     };
                   6374:     if (!$@) {
                   6375:         if ($outcome eq 'ok') {
                   6376:             &Reply($client, \$result, $userinput);
                   6377:         } else {
                   6378:             &Reply($client, "format_error\n", $userinput);
                   6379:         }
                   6380:     } else {
                   6381:         &Failure($client,"unknown_cmd\n",$userinput);
                   6382:     }
                   6383:     return 1;
                   6384: }
                   6385: &register_handler("autocrsrequpdate", \&crsreq_update_handler, 0, 1, 0);
                   6386: 
1.248     foxr     6387: #
                   6388: #   Read and retrieve institutional code format (for support form).
                   6389: # Formal Parameters:
                   6390: #    $cmd        - Command that dispatched us.
                   6391: #    $tail       - Tail of the command.  In this case it conatins 
                   6392: #                  the course domain and the coursename.
                   6393: #    $client     - Socket open on the client.
                   6394: # Returns:
                   6395: #    1     - Continue processing.
                   6396: #
                   6397: sub get_institutional_code_format_handler {
                   6398:     my ($cmd, $tail, $client)   = @_;
                   6399:     my $userinput               = "$cmd:$tail";
                   6400: 
                   6401:     my $reply;
                   6402:     my($cdom,$course) = split(/:/,$tail);
                   6403:     my @pairs = split/\&/,$course;
                   6404:     my %instcodes = ();
                   6405:     my %codes = ();
                   6406:     my @codetitles = ();
                   6407:     my %cat_titles = ();
                   6408:     my %cat_order = ();
                   6409:     foreach (@pairs) {
                   6410: 	my ($key,$value) = split/=/,$_;
                   6411: 	$instcodes{&unescape($key)} = &unescape($value);
                   6412:     }
                   6413:     my $formatreply = &localenroll::instcode_format($cdom,
                   6414: 						    \%instcodes,
                   6415: 						    \%codes,
                   6416: 						    \@codetitles,
                   6417: 						    \%cat_titles,
                   6418: 						    \%cat_order);
                   6419:     if ($formatreply eq 'ok') {
1.365     albertel 6420: 	my $codes_str = &Apache::lonnet::hash2str(%codes);
                   6421: 	my $codetitles_str = &Apache::lonnet::array2str(@codetitles);
                   6422: 	my $cat_titles_str = &Apache::lonnet::hash2str(%cat_titles);
                   6423: 	my $cat_order_str = &Apache::lonnet::hash2str(%cat_order);
1.248     foxr     6424: 	&Reply($client,
                   6425: 	       $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
                   6426: 	       .$cat_order_str."\n",
                   6427: 	       $userinput);
                   6428:     } else {
                   6429: 	# this else branch added by RF since if not ok, lonc will
                   6430: 	# hang waiting on reply until timeout.
                   6431: 	#
                   6432: 	&Reply($client, "format_error\n", $userinput);
                   6433:     }
                   6434:     
                   6435:     return 1;
                   6436: }
1.265     albertel 6437: &register_handler("autoinstcodeformat",
                   6438: 		  \&get_institutional_code_format_handler,0,1,0);
1.246     foxr     6439: 
1.345     raeburn  6440: sub get_institutional_defaults_handler {
                   6441:     my ($cmd, $tail, $client)   = @_;
                   6442:     my $userinput               = "$cmd:$tail";
                   6443: 
                   6444:     my $dom = $tail;
                   6445:     my %defaults_hash;
                   6446:     my @code_order;
                   6447:     my $outcome;
                   6448:     eval {
                   6449:         local($SIG{__DIE__})='DEFAULT';
                   6450:         $outcome = &localenroll::instcode_defaults($dom,\%defaults_hash,
                   6451:                                                    \@code_order);
                   6452:     };
                   6453:     if (!$@) {
                   6454:         if ($outcome eq 'ok') {
                   6455:             my $result='';
                   6456:             while (my ($key,$value) = each(%defaults_hash)) {
                   6457:                 $result.=&escape($key).'='.&escape($value).'&';
                   6458:             }
                   6459:             $result .= 'code_order='.&escape(join('&',@code_order));
1.387     albertel 6460:             &Reply($client,\$result,$userinput);
1.345     raeburn  6461:         } else {
                   6462:             &Reply($client,"error\n", $userinput);
                   6463:         }
                   6464:     } else {
                   6465:         &Failure($client,"unknown_cmd\n",$userinput);
                   6466:     }
                   6467: }
                   6468: &register_handler("autoinstcodedefaults",
                   6469:                   \&get_institutional_defaults_handler,0,1,0);
                   6470: 
1.416     raeburn  6471: sub get_possible_instcodes_handler {
                   6472:     my ($cmd, $tail, $client)   = @_;
                   6473:     my $userinput               = "$cmd:$tail";
                   6474: 
                   6475:     my $reply;
                   6476:     my $cdom = $tail;
1.417     raeburn  6477:     my (@codetitles,%cat_titles,%cat_order,@code_order);
1.416     raeburn  6478:     my $formatreply = &localenroll::possible_instcodes($cdom,
                   6479:                                                        \@codetitles,
                   6480:                                                        \%cat_titles,
1.417     raeburn  6481:                                                        \%cat_order,
                   6482:                                                        \@code_order);
1.416     raeburn  6483:     if ($formatreply eq 'ok') {
                   6484:         my $result = join('&',map {&escape($_);} (@codetitles)).':';
1.417     raeburn  6485:         $result .= join('&',map {&escape($_);} (@code_order)).':';
1.416     raeburn  6486:         foreach my $key (keys(%cat_titles)) {
                   6487:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_titles{$key}).'&';
                   6488:         }
                   6489:         $result =~ s/\&$//;
                   6490:         $result .= ':';
                   6491:         foreach my $key (keys(%cat_order)) {
                   6492:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_order{$key}).'&';
                   6493:         }
                   6494:         $result =~ s/\&$//;
                   6495:         &Reply($client,\$result,$userinput);
                   6496:     } else {
                   6497:         &Reply($client, "format_error\n", $userinput);
                   6498:     }
                   6499:     return 1;
                   6500: }
                   6501: &register_handler("autopossibleinstcodes",
                   6502:                   \&get_possible_instcodes_handler,0,1,0);
                   6503: 
1.381     raeburn  6504: sub get_institutional_user_rules {
                   6505:     my ($cmd, $tail, $client)   = @_;
                   6506:     my $userinput               = "$cmd:$tail";
                   6507:     my $dom = &unescape($tail);
                   6508:     my (%rules_hash,@rules_order);
                   6509:     my $outcome;
                   6510:     eval {
                   6511:         local($SIG{__DIE__})='DEFAULT';
                   6512:         $outcome = &localenroll::username_rules($dom,\%rules_hash,\@rules_order);
                   6513:     };
                   6514:     if (!$@) {
                   6515:         if ($outcome eq 'ok') {
                   6516:             my $result;
                   6517:             foreach my $key (keys(%rules_hash)) {
                   6518:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6519:             }
                   6520:             $result =~ s/\&$//;
                   6521:             $result .= ':';
                   6522:             if (@rules_order > 0) {
                   6523:                 foreach my $item (@rules_order) {
                   6524:                     $result .= &escape($item).'&';
                   6525:                 }
                   6526:             }
                   6527:             $result =~ s/\&$//;
1.387     albertel 6528:             &Reply($client,\$result,$userinput);
1.381     raeburn  6529:         } else {
                   6530:             &Reply($client,"error\n", $userinput);
                   6531:         }
                   6532:     } else {
                   6533:         &Failure($client,"unknown_cmd\n",$userinput);
                   6534:     }
                   6535: }
                   6536: &register_handler("instuserrules",\&get_institutional_user_rules,0,1,0);
                   6537: 
1.389     raeburn  6538: sub get_institutional_id_rules {
                   6539:     my ($cmd, $tail, $client)   = @_;
                   6540:     my $userinput               = "$cmd:$tail";
                   6541:     my $dom = &unescape($tail);
                   6542:     my (%rules_hash,@rules_order);
                   6543:     my $outcome;
                   6544:     eval {
                   6545:         local($SIG{__DIE__})='DEFAULT';
                   6546:         $outcome = &localenroll::id_rules($dom,\%rules_hash,\@rules_order);
                   6547:     };
                   6548:     if (!$@) {
                   6549:         if ($outcome eq 'ok') {
                   6550:             my $result;
                   6551:             foreach my $key (keys(%rules_hash)) {
                   6552:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6553:             }
                   6554:             $result =~ s/\&$//;
                   6555:             $result .= ':';
                   6556:             if (@rules_order > 0) {
                   6557:                 foreach my $item (@rules_order) {
                   6558:                     $result .= &escape($item).'&';
                   6559:                 }
                   6560:             }
                   6561:             $result =~ s/\&$//;
                   6562:             &Reply($client,\$result,$userinput);
                   6563:         } else {
                   6564:             &Reply($client,"error\n", $userinput);
                   6565:         }
                   6566:     } else {
                   6567:         &Failure($client,"unknown_cmd\n",$userinput);
                   6568:     }
                   6569: }
                   6570: &register_handler("instidrules",\&get_institutional_id_rules,0,1,0);
                   6571: 
1.397     raeburn  6572: sub get_institutional_selfcreate_rules {
1.396     raeburn  6573:     my ($cmd, $tail, $client)   = @_;
                   6574:     my $userinput               = "$cmd:$tail";
                   6575:     my $dom = &unescape($tail);
                   6576:     my (%rules_hash,@rules_order);
                   6577:     my $outcome;
                   6578:     eval {
                   6579:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  6580:         $outcome = &localenroll::selfcreate_rules($dom,\%rules_hash,\@rules_order);
1.396     raeburn  6581:     };
                   6582:     if (!$@) {
                   6583:         if ($outcome eq 'ok') {
                   6584:             my $result;
                   6585:             foreach my $key (keys(%rules_hash)) {
                   6586:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6587:             }
                   6588:             $result =~ s/\&$//;
                   6589:             $result .= ':';
                   6590:             if (@rules_order > 0) {
                   6591:                 foreach my $item (@rules_order) {
                   6592:                     $result .= &escape($item).'&';
                   6593:                 }
                   6594:             }
                   6595:             $result =~ s/\&$//;
                   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: }
1.397     raeburn  6604: &register_handler("instemailrules",\&get_institutional_selfcreate_rules,0,1,0);
1.396     raeburn  6605: 
1.381     raeburn  6606: 
                   6607: sub institutional_username_check {
                   6608:     my ($cmd, $tail, $client)   = @_;
                   6609:     my $userinput               = "$cmd:$tail";
                   6610:     my %rulecheck;
                   6611:     my $outcome;
                   6612:     my ($udom,$uname,@rules) = split(/:/,$tail);
                   6613:     $udom = &unescape($udom);
                   6614:     $uname = &unescape($uname);
                   6615:     @rules = map {&unescape($_);} (@rules);
                   6616:     eval {
                   6617:         local($SIG{__DIE__})='DEFAULT';
                   6618:         $outcome = &localenroll::username_check($udom,$uname,\@rules,\%rulecheck);
                   6619:     };
                   6620:     if (!$@) {
                   6621:         if ($outcome eq 'ok') {
                   6622:             my $result='';
                   6623:             foreach my $key (keys(%rulecheck)) {
                   6624:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6625:             }
1.387     albertel 6626:             &Reply($client,\$result,$userinput);
1.381     raeburn  6627:         } else {
                   6628:             &Reply($client,"error\n", $userinput);
                   6629:         }
                   6630:     } else {
                   6631:         &Failure($client,"unknown_cmd\n",$userinput);
                   6632:     }
                   6633: }
                   6634: &register_handler("instrulecheck",\&institutional_username_check,0,1,0);
                   6635: 
1.389     raeburn  6636: sub institutional_id_check {
                   6637:     my ($cmd, $tail, $client)   = @_;
                   6638:     my $userinput               = "$cmd:$tail";
                   6639:     my %rulecheck;
                   6640:     my $outcome;
                   6641:     my ($udom,$id,@rules) = split(/:/,$tail);
                   6642:     $udom = &unescape($udom);
                   6643:     $id = &unescape($id);
                   6644:     @rules = map {&unescape($_);} (@rules);
                   6645:     eval {
                   6646:         local($SIG{__DIE__})='DEFAULT';
                   6647:         $outcome = &localenroll::id_check($udom,$id,\@rules,\%rulecheck);
                   6648:     };
                   6649:     if (!$@) {
                   6650:         if ($outcome eq 'ok') {
                   6651:             my $result='';
                   6652:             foreach my $key (keys(%rulecheck)) {
                   6653:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6654:             }
                   6655:             &Reply($client,\$result,$userinput);
                   6656:         } else {
                   6657:             &Reply($client,"error\n", $userinput);
                   6658:         }
                   6659:     } else {
                   6660:         &Failure($client,"unknown_cmd\n",$userinput);
                   6661:     }
                   6662: }
                   6663: &register_handler("instidrulecheck",\&institutional_id_check,0,1,0);
1.345     raeburn  6664: 
1.397     raeburn  6665: sub institutional_selfcreate_check {
1.396     raeburn  6666:     my ($cmd, $tail, $client)   = @_;
                   6667:     my $userinput               = "$cmd:$tail";
                   6668:     my %rulecheck;
                   6669:     my $outcome;
                   6670:     my ($udom,$email,@rules) = split(/:/,$tail);
                   6671:     $udom = &unescape($udom);
                   6672:     $email = &unescape($email);
                   6673:     @rules = map {&unescape($_);} (@rules);
                   6674:     eval {
                   6675:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  6676:         $outcome = &localenroll::selfcreate_check($udom,$email,\@rules,\%rulecheck);
1.396     raeburn  6677:     };
                   6678:     if (!$@) {
                   6679:         if ($outcome eq 'ok') {
                   6680:             my $result='';
                   6681:             foreach my $key (keys(%rulecheck)) {
                   6682:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6683:             }
                   6684:             &Reply($client,\$result,$userinput);
                   6685:         } else {
                   6686:             &Reply($client,"error\n", $userinput);
                   6687:         }
                   6688:     } else {
                   6689:         &Failure($client,"unknown_cmd\n",$userinput);
                   6690:     }
                   6691: }
1.397     raeburn  6692: &register_handler("instselfcreatecheck",\&institutional_selfcreate_check,0,1,0);
1.396     raeburn  6693: 
1.317     raeburn  6694: # Get domain specific conditions for import of student photographs to a course
                   6695: #
                   6696: # Retrieves information from photo_permission subroutine in localenroll.
                   6697: # Returns outcome (ok) if no processing errors, and whether course owner is 
                   6698: # required to accept conditions of use (yes/no).
                   6699: #
                   6700: #    
                   6701: sub photo_permission_handler {
                   6702:     my ($cmd, $tail, $client)   = @_;
                   6703:     my $userinput               = "$cmd:$tail";
                   6704:     my $cdom = $tail;
                   6705:     my ($perm_reqd,$conditions);
1.320     albertel 6706:     my $outcome;
                   6707:     eval {
                   6708: 	local($SIG{__DIE__})='DEFAULT';
                   6709: 	$outcome = &localenroll::photo_permission($cdom,\$perm_reqd,
                   6710: 						  \$conditions);
                   6711:     };
                   6712:     if (!$@) {
                   6713: 	&Reply($client, &escape($outcome.':'.$perm_reqd.':'. $conditions)."\n",
                   6714: 	       $userinput);
                   6715:     } else {
                   6716: 	&Failure($client,"unknown_cmd\n",$userinput);
                   6717:     }
                   6718:     return 1;
1.317     raeburn  6719: }
                   6720: &register_handler("autophotopermission",\&photo_permission_handler,0,1,0);
                   6721: 
                   6722: #
                   6723: # Checks if student photo is available for a user in the domain, in the user's
                   6724: # directory (in /userfiles/internal/studentphoto.jpg).
                   6725: # Uses localstudentphoto:fetch() to ensure there is an up to date copy of
                   6726: # the student's photo.   
                   6727: 
                   6728: sub photo_check_handler {
                   6729:     my ($cmd, $tail, $client)   = @_;
                   6730:     my $userinput               = "$cmd:$tail";
                   6731:     my ($udom,$uname,$pid) = split(/:/,$tail);
                   6732:     $udom = &unescape($udom);
                   6733:     $uname = &unescape($uname);
                   6734:     $pid = &unescape($pid);
                   6735:     my $path=&propath($udom,$uname).'/userfiles/internal/';
                   6736:     if (!-e $path) {
                   6737:         &mkpath($path);
                   6738:     }
                   6739:     my $response;
                   6740:     my $result = &localstudentphoto::fetch($udom,$uname,$pid,\$response);
                   6741:     $result .= ':'.$response;
                   6742:     &Reply($client, &escape($result)."\n",$userinput);
1.320     albertel 6743:     return 1;
1.317     raeburn  6744: }
                   6745: &register_handler("autophotocheck",\&photo_check_handler,0,1,0);
                   6746: 
                   6747: #
                   6748: # Retrieve information from localenroll about whether to provide a button     
                   6749: # for users who have enbled import of student photos to initiate an 
                   6750: # update of photo files for registered students. Also include 
                   6751: # comment to display alongside button.  
                   6752: 
                   6753: sub photo_choice_handler {
                   6754:     my ($cmd, $tail, $client) = @_;
                   6755:     my $userinput             = "$cmd:$tail";
                   6756:     my $cdom                  = &unescape($tail);
1.320     albertel 6757:     my ($update,$comment);
                   6758:     eval {
                   6759: 	local($SIG{__DIE__})='DEFAULT';
                   6760: 	($update,$comment)    = &localenroll::manager_photo_update($cdom);
                   6761:     };
                   6762:     if (!$@) {
                   6763: 	&Reply($client,&escape($update).':'.&escape($comment)."\n",$userinput);
                   6764:     } else {
                   6765: 	&Failure($client,"unknown_cmd\n",$userinput);
                   6766:     }
                   6767:     return 1;
1.317     raeburn  6768: }
                   6769: &register_handler("autophotochoice",\&photo_choice_handler,0,1,0);
                   6770: 
1.265     albertel 6771: #
                   6772: # Gets a student's photo to exist (in the correct image type) in the user's 
                   6773: # directory.
                   6774: # Formal Parameters:
                   6775: #    $cmd     - The command request that got us dispatched.
                   6776: #    $tail    - A colon separated set of words that will be split into:
                   6777: #               $domain - student's domain
                   6778: #               $uname  - student username
                   6779: #               $type   - image type desired
                   6780: #    $client  - The socket open on the client.
                   6781: # Returns:
                   6782: #    1 - continue processing.
1.317     raeburn  6783: 
1.265     albertel 6784: sub student_photo_handler {
                   6785:     my ($cmd, $tail, $client) = @_;
1.317     raeburn  6786:     my ($domain,$uname,$ext,$type) = split(/:/, $tail);
1.265     albertel 6787: 
1.317     raeburn  6788:     my $path=&propath($domain,$uname). '/userfiles/internal/';
                   6789:     my $filename = 'studentphoto.'.$ext;
                   6790:     if ($type eq 'thumbnail') {
                   6791:         $filename = 'studentphoto_tn.'.$ext;
                   6792:     }
                   6793:     if (-e $path.$filename) {
1.265     albertel 6794: 	&Reply($client,"ok\n","$cmd:$tail");
                   6795: 	return 1;
                   6796:     }
                   6797:     &mkpath($path);
1.317     raeburn  6798:     my $file;
                   6799:     if ($type eq 'thumbnail') {
1.320     albertel 6800: 	eval {
                   6801: 	    local($SIG{__DIE__})='DEFAULT';
                   6802: 	    $file=&localstudentphoto::fetch_thumbnail($domain,$uname);
                   6803: 	};
1.317     raeburn  6804:     } else {
                   6805:         $file=&localstudentphoto::fetch($domain,$uname);
                   6806:     }
1.265     albertel 6807:     if (!$file) {
                   6808: 	&Failure($client,"unavailable\n","$cmd:$tail");
                   6809: 	return 1;
                   6810:     }
1.317     raeburn  6811:     if (!-e $path.$filename) { &convert_photo($file,$path.$filename); }
                   6812:     if (-e $path.$filename) {
1.265     albertel 6813: 	&Reply($client,"ok\n","$cmd:$tail");
                   6814: 	return 1;
                   6815:     }
                   6816:     &Failure($client,"unable_to_convert\n","$cmd:$tail");
                   6817:     return 1;
                   6818: }
                   6819: &register_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
1.246     foxr     6820: 
1.361     raeburn  6821: sub inst_usertypes_handler {
                   6822:     my ($cmd, $domain, $client) = @_;
                   6823:     my $res;
                   6824:     my $userinput = $cmd.":".$domain; # For logging purposes.
1.370     albertel 6825:     my (%typeshash,@order,$result);
                   6826:     eval {
                   6827: 	local($SIG{__DIE__})='DEFAULT';
                   6828: 	$result=&localenroll::inst_usertypes($domain,\%typeshash,\@order);
                   6829:     };
                   6830:     if ($result eq 'ok') {
1.361     raeburn  6831:         if (keys(%typeshash) > 0) {
                   6832:             foreach my $key (keys(%typeshash)) {
                   6833:                 $res.=&escape($key).'='.&escape($typeshash{$key}).'&';
                   6834:             }
                   6835:         }
                   6836:         $res=~s/\&$//;
                   6837:         $res .= ':';
                   6838:         if (@order > 0) {
                   6839:             foreach my $item (@order) {
                   6840:                 $res .= &escape($item).'&';
                   6841:             }
                   6842:         }
                   6843:         $res=~s/\&$//;
                   6844:     }
1.387     albertel 6845:     &Reply($client, \$res, $userinput);
1.361     raeburn  6846:     return 1;
                   6847: }
                   6848: &register_handler("inst_usertypes", \&inst_usertypes_handler, 0, 1, 0);
                   6849: 
1.264     albertel 6850: # mkpath makes all directories for a file, expects an absolute path with a
                   6851: # file or a trailing / if just a dir is passed
                   6852: # returns 1 on success 0 on failure
                   6853: sub mkpath {
                   6854:     my ($file)=@_;
                   6855:     my @parts=split(/\//,$file,-1);
                   6856:     my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
                   6857:     for (my $i=3;$i<= ($#parts-1);$i++) {
1.265     albertel 6858: 	$now.='/'.$parts[$i]; 
1.264     albertel 6859: 	if (!-e $now) {
                   6860: 	    if  (!mkdir($now,0770)) { return 0; }
                   6861: 	}
                   6862:     }
                   6863:     return 1;
                   6864: }
                   6865: 
1.207     foxr     6866: #---------------------------------------------------------------
                   6867: #
                   6868: #   Getting, decoding and dispatching requests:
                   6869: #
                   6870: #
                   6871: #   Get a Request:
                   6872: #   Gets a Request message from the client.  The transaction
                   6873: #   is defined as a 'line' of text.  We remove the new line
                   6874: #   from the text line.  
1.226     foxr     6875: #
1.211     albertel 6876: sub get_request {
1.207     foxr     6877:     my $input = <$client>;
                   6878:     chomp($input);
1.226     foxr     6879: 
1.234     foxr     6880:     &Debug("get_request: Request = $input\n");
1.207     foxr     6881: 
                   6882:     &status('Processing '.$clientname.':'.$input);
                   6883: 
                   6884:     return $input;
                   6885: }
1.212     foxr     6886: #---------------------------------------------------------------
                   6887: #
                   6888: #  Process a request.  This sub should shrink as each action
                   6889: #  gets farmed out into a separat sub that is registered 
                   6890: #  with the dispatch hash.  
                   6891: #
                   6892: # Parameters:
                   6893: #    user_input   - The request received from the client (lonc).
1.525     raeburn  6894: #
1.212     foxr     6895: # Returns:
                   6896: #    true to keep processing, false if caller should exit.
                   6897: #
                   6898: sub process_request {
1.525     raeburn  6899:     my ($userinput) = @_; # Easier for now to break style than to
                   6900:                           # fix all the userinput -> user_input.
1.212     foxr     6901:     my $wasenc    = 0;		# True if request was encrypted.
                   6902: # ------------------------------------------------------------ See if encrypted
1.322     albertel 6903:     # for command
                   6904:     # sethost:<server>
                   6905:     # <command>:<args>
                   6906:     #   we just send it to the processor
                   6907:     # for
                   6908:     # sethost:<server>:<command>:<args>
                   6909:     #  we do the implict set host and then do the command
                   6910:     if ($userinput =~ /^sethost:/) {
                   6911: 	(my $cmd,my $newid,$userinput) = split(':',$userinput,3);
                   6912: 	if (defined($userinput)) {
                   6913: 	    &sethost("$cmd:$newid");
                   6914: 	} else {
                   6915: 	    $userinput = "$cmd:$newid";
                   6916: 	}
                   6917:     }
                   6918: 
1.212     foxr     6919:     if ($userinput =~ /^enc/) {
                   6920: 	$userinput = decipher($userinput);
                   6921: 	$wasenc=1;
                   6922: 	if(!$userinput) {	# Cipher not defined.
1.251     foxr     6923: 	    &Failure($client, "error: Encrypted data without negotated key\n");
1.212     foxr     6924: 	    return 0;
                   6925: 	}
                   6926:     }
                   6927:     Debug("process_request: $userinput\n");
                   6928:     
1.213     foxr     6929:     #  
                   6930:     #   The 'correct way' to add a command to lond is now to
                   6931:     #   write a sub to execute it and Add it to the command dispatch
                   6932:     #   hash via a call to register_handler..  The comments to that
                   6933:     #   sub should give you enough to go on to show how to do this
                   6934:     #   along with the examples that are building up as this code
                   6935:     #   is getting refactored.   Until all branches of the
                   6936:     #   if/elseif monster below have been factored out into
                   6937:     #   separate procesor subs, if the dispatch hash is missing
                   6938:     #   the command keyword, we will fall through to the remainder
                   6939:     #   of the if/else chain below in order to keep this thing in 
                   6940:     #   working order throughout the transmogrification.
                   6941: 
                   6942:     my ($command, $tail) = split(/:/, $userinput, 2);
                   6943:     chomp($command);
                   6944:     chomp($tail);
                   6945:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
1.214     foxr     6946:     $command =~ s/(\r)//;	# And this too for parameterless commands.
                   6947:     if(!$tail) {
                   6948: 	$tail ="";		# defined but blank.
                   6949:     }
1.213     foxr     6950: 
                   6951:     &Debug("Command received: $command, encoded = $wasenc");
                   6952: 
                   6953:     if(defined $Dispatcher{$command}) {
                   6954: 
                   6955: 	my $dispatch_info = $Dispatcher{$command};
                   6956: 	my $handler       = $$dispatch_info[0];
                   6957: 	my $need_encode   = $$dispatch_info[1];
                   6958: 	my $client_types  = $$dispatch_info[2];
                   6959: 	Debug("Matched dispatch hash: mustencode: $need_encode "
                   6960: 	      ."ClientType $client_types");
                   6961:       
                   6962: 	#  Validate the request:
                   6963:       
                   6964: 	my $ok = 1;
                   6965: 	my $requesterprivs = 0;
                   6966: 	if(&isClient()) {
                   6967: 	    $requesterprivs |= $CLIENT_OK;
                   6968: 	}
                   6969: 	if(&isManager()) {
                   6970: 	    $requesterprivs |= $MANAGER_OK;
                   6971: 	}
                   6972: 	if($need_encode && (!$wasenc)) {
                   6973: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
                   6974: 	    $ok = 0;
                   6975: 	}
                   6976: 	if(($client_types & $requesterprivs) == 0) {
                   6977: 	    Debug("Client not privileged to do this operation");
                   6978: 	    $ok = 0;
                   6979: 	}
1.525     raeburn  6980:         if ($ok) {
1.535     raeburn  6981:             my $realcommand = $command;
                   6982:             if ($command eq 'querysend') {
                   6983:                 my ($query,$rest)=split(/\:/,$tail,2);
                   6984:                 $query=~s/\n*$//g;
                   6985:                 my @possqueries = 
                   6986:                     qw(userlog courselog fetchenrollment institutionalphotos usersearch instdirsearch getinstuser getmultinstusers);
                   6987:                 if (grep(/^\Q$query\E$/,@possqueries)) {
                   6988:                     $command .= '_'.$query;
                   6989:                 } elsif ($query eq 'prepare activity log') {
                   6990:                     $command .= '_activitylog';
                   6991:                 }
                   6992:             }
1.525     raeburn  6993:             if (ref($trust{$command}) eq 'HASH') {
                   6994:                 my $donechecks;
                   6995:                 if ($trust{$command}{'anywhere'}) {
                   6996:                    $donechecks = 1;
                   6997:                 } elsif ($trust{$command}{'manageronly'}) {
                   6998:                     unless (&isManager()) {
                   6999:                         $ok = 0;
                   7000:                     }
                   7001:                     $donechecks = 1;
                   7002:                 } elsif ($trust{$command}{'institutiononly'}) {
                   7003:                     unless ($clientsameinst) {
                   7004:                         $ok = 0;
                   7005:                     }
                   7006:                     $donechecks = 1;
                   7007:                 } elsif ($clientsameinst) {
                   7008:                     $donechecks = 1;
                   7009:                 }
                   7010:                 unless ($donechecks) {
                   7011:                     foreach my $rule (keys(%{$trust{$command}})) {
                   7012:                         next if ($rule eq 'remote');
                   7013:                         if ($trust{$command}{$rule}) {
                   7014:                             if ($clientprohibited{$rule}) {
                   7015:                                 $ok = 0;
                   7016:                             } else {
                   7017:                                 $ok = 1;
                   7018:                                 $donechecks = 1;
                   7019:                                 last;
                   7020:                             }
                   7021:                         }
                   7022:                     }
                   7023:                 }
                   7024:                 unless ($donechecks) {
                   7025:                     if ($trust{$command}{'remote'}) {
                   7026:                         if ($clientremoteok) {
                   7027:                             $ok = 1;
                   7028:                         } else {
                   7029:                             $ok = 0;
                   7030:                         } 
                   7031:                     }
                   7032:                 }
                   7033:             }
1.535     raeburn  7034:             $command = $realcommand;
1.525     raeburn  7035:         }
1.213     foxr     7036: 
                   7037: 	if($ok) {
                   7038: 	    Debug("Dispatching to handler $command $tail");
                   7039: 	    my $keep_going = &$handler($command, $tail, $client);
                   7040: 	    return $keep_going;
                   7041: 	} else {
                   7042: 	    Debug("Refusing to dispatch because client did not match requirements");
                   7043: 	    Failure($client, "refused\n", $userinput);
                   7044: 	    return 1;
                   7045: 	}
1.525     raeburn  7046:     }
1.213     foxr     7047: 
1.262     foxr     7048:     print $client "unknown_cmd\n";
1.212     foxr     7049: # -------------------------------------------------------------------- complete
                   7050:     Debug("process_request - returning 1");
                   7051:     return 1;
                   7052: }
1.207     foxr     7053: #
                   7054: #   Decipher encoded traffic
                   7055: #  Parameters:
                   7056: #     input      - Encoded data.
                   7057: #  Returns:
                   7058: #     Decoded data or undef if encryption key was not yet negotiated.
                   7059: #  Implicit input:
                   7060: #     cipher  - This global holds the negotiated encryption key.
                   7061: #
1.211     albertel 7062: sub decipher {
1.207     foxr     7063:     my ($input)  = @_;
                   7064:     my $output = '';
1.212     foxr     7065:     
                   7066:     
1.207     foxr     7067:     if($cipher) {
                   7068: 	my($enc, $enclength, $encinput) = split(/:/, $input);
                   7069: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
                   7070: 	    $output .= 
                   7071: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
                   7072: 	}
                   7073: 	return substr($output, 0, $enclength);
                   7074:     } else {
                   7075: 	return undef;
                   7076:     }
                   7077: }
                   7078: 
                   7079: #
                   7080: #   Register a command processor.  This function is invoked to register a sub
                   7081: #   to process a request.  Once registered, the ProcessRequest sub can automatically
                   7082: #   dispatch requests to an appropriate sub, and do the top level validity checking
                   7083: #   as well:
                   7084: #    - Is the keyword recognized.
                   7085: #    - Is the proper client type attempting the request.
                   7086: #    - Is the request encrypted if it has to be.
                   7087: #   Parameters:
                   7088: #    $request_name         - Name of the request being registered.
                   7089: #                           This is the command request that will match
                   7090: #                           against the hash keywords to lookup the information
                   7091: #                           associated with the dispatch information.
                   7092: #    $procedure           - Reference to a sub to call to process the request.
                   7093: #                           All subs get called as follows:
                   7094: #                             Procedure($cmd, $tail, $replyfd, $key)
                   7095: #                             $cmd    - the actual keyword that invoked us.
                   7096: #                             $tail   - the tail of the request that invoked us.
                   7097: #                             $replyfd- File descriptor connected to the client
                   7098: #    $must_encode          - True if the request must be encoded to be good.
                   7099: #    $client_ok            - True if it's ok for a client to request this.
                   7100: #    $manager_ok           - True if it's ok for a manager to request this.
                   7101: # Side effects:
                   7102: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
                   7103: #      - On failure, the program will die as it's a bad internal bug to try to 
                   7104: #        register a duplicate command handler.
                   7105: #
1.211     albertel 7106: sub register_handler {
1.212     foxr     7107:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
1.207     foxr     7108: 
                   7109:     #  Don't allow duplication#
                   7110:    
                   7111:     if (defined $Dispatcher{$request_name}) {
                   7112: 	die "Attempting to define a duplicate request handler for $request_name\n";
                   7113:     }
                   7114:     #   Build the client type mask:
                   7115:     
                   7116:     my $client_type_mask = 0;
                   7117:     if($client_ok) {
                   7118: 	$client_type_mask  |= $CLIENT_OK;
                   7119:     }
                   7120:     if($manager_ok) {
                   7121: 	$client_type_mask  |= $MANAGER_OK;
                   7122:     }
                   7123:    
                   7124:     #  Enter the hash:
                   7125:       
                   7126:     my @entry = ($procedure, $must_encode, $client_type_mask);
                   7127:    
                   7128:     $Dispatcher{$request_name} = \@entry;
                   7129:    
                   7130: }
                   7131: 
                   7132: 
                   7133: #------------------------------------------------------------------
                   7134: 
                   7135: 
                   7136: 
                   7137: 
1.141     foxr     7138: #
1.96      foxr     7139: #  Convert an error return code from lcpasswd to a string value.
                   7140: #
                   7141: sub lcpasswdstrerror {
                   7142:     my $ErrorCode = shift;
1.97      foxr     7143:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96      foxr     7144: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
                   7145:     } else {
1.98      foxr     7146: 	return $passwderrors[$ErrorCode];
1.96      foxr     7147:     }
                   7148: }
                   7149: 
1.23      harris41 7150: # grabs exception and records it to log before exiting
                   7151: sub catchexception {
1.27      albertel 7152:     my ($error)=@_;
1.25      www      7153:     $SIG{'QUIT'}='DEFAULT';
                   7154:     $SIG{__DIE__}='DEFAULT';
1.165     albertel 7155:     &status("Catching exception");
1.190     albertel 7156:     &logthis("<font color='red'>CRITICAL: "
1.373     albertel 7157:      ."ABNORMAL EXIT. Child $$ for server ".$perlvar{'lonHostID'}." died through "
1.27      albertel 7158:      ."a crash with this error msg->[$error]</font>");
1.57      www      7159:     &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27      albertel 7160:     if ($client) { print $client "error: $error\n"; }
1.59      www      7161:     $server->close();
1.27      albertel 7162:     die($error);
1.23      harris41 7163: }
1.63      www      7164: sub timeout {
1.165     albertel 7165:     &status("Handling Timeout");
1.190     albertel 7166:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
1.63      www      7167:     &catchexception('Timeout');
                   7168: }
1.22      harris41 7169: # -------------------------------- Set signal handlers to record abnormal exits
                   7170: 
1.226     foxr     7171: 
1.22      harris41 7172: $SIG{'QUIT'}=\&catchexception;
                   7173: $SIG{__DIE__}=\&catchexception;
                   7174: 
1.81      matthew  7175: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95      harris41 7176: &status("Read loncapa.conf and loncapa_apache.conf");
                   7177: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141     foxr     7178: %perlvar=%{$perlvarref};
1.80      harris41 7179: undef $perlvarref;
1.19      www      7180: 
1.35      harris41 7181: # ----------------------------- Make sure this process is running from user=www
                   7182: my $wwwid=getpwnam('www');
                   7183: if ($wwwid!=$<) {
1.134     albertel 7184:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   7185:    my $subj="LON: $currenthostid User ID mismatch";
1.550     raeburn  7186:    system("echo 'User ID mismatch.  lond must be run as user www.' |".
                   7187:           " mail -s '$subj' $emailto > /dev/null");
1.35      harris41 7188:    exit 1;
                   7189: }
                   7190: 
1.19      www      7191: # --------------------------------------------- Check if other instance running
                   7192: 
                   7193: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
                   7194: 
                   7195: if (-e $pidfile) {
                   7196:    my $lfh=IO::File->new("$pidfile");
                   7197:    my $pide=<$lfh>;
                   7198:    chomp($pide);
1.29      harris41 7199:    if (kill 0 => $pide) { die "already running"; }
1.19      www      7200: }
1.1       albertel 7201: 
                   7202: # ------------------------------------------------------------- Read hosts file
                   7203: 
                   7204: 
                   7205: 
                   7206: # establish SERVER socket, bind and listen.
                   7207: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
                   7208:                                 Type      => SOCK_STREAM,
                   7209:                                 Proto     => 'tcp',
1.469     foxr     7210:                                 ReuseAddr     => 1,
1.1       albertel 7211:                                 Listen    => 10 )
1.29      harris41 7212:   or die "making socket: $@\n";
1.1       albertel 7213: 
                   7214: # --------------------------------------------------------- Do global variables
                   7215: 
                   7216: # global variables
                   7217: 
1.134     albertel 7218: my %children               = ();       # keys are current child process IDs
1.1       albertel 7219: 
                   7220: sub REAPER {                        # takes care of dead children
                   7221:     $SIG{CHLD} = \&REAPER;
1.165     albertel 7222:     &status("Handling child death");
1.178     foxr     7223:     my $pid;
                   7224:     do {
                   7225: 	$pid = waitpid(-1,&WNOHANG());
                   7226: 	if (defined($children{$pid})) {
                   7227: 	    &logthis("Child $pid died");
                   7228: 	    delete($children{$pid});
1.183     albertel 7229: 	} elsif ($pid > 0) {
1.178     foxr     7230: 	    &logthis("Unknown Child $pid died");
                   7231: 	}
                   7232:     } while ( $pid > 0 );
                   7233:     foreach my $child (keys(%children)) {
                   7234: 	$pid = waitpid($child,&WNOHANG());
                   7235: 	if ($pid > 0) {
                   7236: 	    &logthis("Child $child - $pid looks like we missed it's death");
                   7237: 	    delete($children{$pid});
                   7238: 	}
1.176     albertel 7239:     }
1.165     albertel 7240:     &status("Finished Handling child death");
1.1       albertel 7241: }
                   7242: 
                   7243: sub HUNTSMAN {                      # signal handler for SIGINT
1.165     albertel 7244:     &status("Killing children (INT)");
1.1       albertel 7245:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
                   7246:     kill 'INT' => keys %children;
1.59      www      7247:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1       albertel 7248:     my $execdir=$perlvar{'lonDaemons'};
                   7249:     unlink("$execdir/logs/lond.pid");
1.190     albertel 7250:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.165     albertel 7251:     &status("Done killing children");
1.1       albertel 7252:     exit;                           # clean up with dignity
                   7253: }
                   7254: 
                   7255: sub HUPSMAN {                      # signal handler for SIGHUP
                   7256:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
1.165     albertel 7257:     &status("Killing children for restart (HUP)");
1.1       albertel 7258:     kill 'INT' => keys %children;
1.59      www      7259:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.190     albertel 7260:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.134     albertel 7261:     my $execdir=$perlvar{'lonDaemons'};
1.30      harris41 7262:     unlink("$execdir/logs/lond.pid");
1.165     albertel 7263:     &status("Restarting self (HUP)");
1.1       albertel 7264:     exec("$execdir/lond");         # here we go again
                   7265: }
                   7266: 
1.144     foxr     7267: #
1.148     foxr     7268: #  Reload the Apache daemon's state.
1.150     foxr     7269: #  This is done by invoking /home/httpd/perl/apachereload
                   7270: #  a setuid perl script that can be root for us to do this job.
1.148     foxr     7271: #
                   7272: sub ReloadApache {
1.473     raeburn  7273: # --------------------------- Handle case of another apachereload process (locking)
1.474     raeburn  7274:     if (&LONCAPA::try_to_lock('/tmp/lock_apachereload')) {
                   7275:         my $execdir = $perlvar{'lonDaemons'};
                   7276:         my $script  = $execdir."/apachereload";
                   7277:         system($script);
                   7278:         unlink('/tmp/lock_apachereload'); #  Remove the lock file.
                   7279:     }
1.148     foxr     7280: }
                   7281: 
                   7282: #
1.144     foxr     7283: #   Called in response to a USR2 signal.
                   7284: #   - Reread hosts.tab
                   7285: #   - All children connected to hosts that were removed from hosts.tab
                   7286: #     are killed via SIGINT
                   7287: #   - All children connected to previously existing hosts are sent SIGUSR1
                   7288: #   - Our internal hosts hash is updated to reflect the new contents of
                   7289: #     hosts.tab causing connections from hosts added to hosts.tab to
                   7290: #     now be honored.
                   7291: #
                   7292: sub UpdateHosts {
1.165     albertel 7293:     &status("Reload hosts.tab");
1.147     foxr     7294:     logthis('<font color="blue"> Updating connections </font>');
1.148     foxr     7295:     #
                   7296:     #  The %children hash has the set of IP's we currently have children
                   7297:     #  on.  These need to be matched against records in the hosts.tab
                   7298:     #  Any ip's no longer in the table get killed off they correspond to
                   7299:     #  either dropped or changed hosts.  Note that the re-read of the table
                   7300:     #  will take care of new and changed hosts as connections come into being.
                   7301: 
1.371     albertel 7302:     &Apache::lonnet::reset_hosts_info();
1.532     raeburn  7303:     my %active;
1.148     foxr     7304: 
1.368     albertel 7305:     foreach my $child (keys(%children)) {
1.148     foxr     7306: 	my $childip = $children{$child};
1.374     albertel 7307: 	if ($childip ne '127.0.0.1'
                   7308: 	    && !defined(&Apache::lonnet::get_hosts_from_ip($childip))) {
1.149     foxr     7309: 	    logthis('<font color="blue"> UpdateHosts killing child '
                   7310: 		    ." $child for ip $childip </font>");
1.148     foxr     7311: 	    kill('INT', $child);
1.149     foxr     7312: 	} else {
1.532     raeburn  7313:             $active{$child} = $childip;
1.149     foxr     7314: 	    logthis('<font color="green"> keeping child for ip '
                   7315: 		    ." $childip (pid=$child) </font>");
1.148     foxr     7316: 	}
                   7317:     }
1.532     raeburn  7318: 
                   7319:     my %oldconf = %secureconf;
                   7320:     my %connchange;
1.555     raeburn  7321:     if (lonssl::Read_Connect_Config(\%secureconf,\%perlvar,\%crlchecked) eq 'ok') {
1.545     raeburn  7322:         logthis('<font color="blue"> Reloaded SSL connection rules and cleared CRL checking history </font>');
1.532     raeburn  7323:     } else {
1.545     raeburn  7324:         logthis('<font color="yellow"> Failed to reload SSL connection rules and clear CRL checking history </font>');
1.532     raeburn  7325:     }
                   7326:     if ((ref($oldconf{'connfrom'}) eq 'HASH') && (ref($secureconf{'connfrom'}) eq 'HASH')) {
                   7327:         foreach my $type ('dom','intdom','other') {
                   7328:             if ((($oldconf{'connfrom'}{$type} eq 'no') && ($secureconf{'connfrom'}{$type} eq 'req')) ||
                   7329:                 (($oldconf{'connfrom'}{$type} eq 'req') && ($secureconf{'connfrom'}{$type} eq 'no'))) {
                   7330:                 $connchange{$type} = 1;
                   7331:             }
                   7332:         }
                   7333:     }
                   7334:     if (keys(%connchange)) {
                   7335:         foreach my $child (keys(%active)) {
                   7336:             my $childip = $active{$child};
                   7337:             if ($childip ne '127.0.0.1') {
                   7338:                 my $childhostname  = gethostbyaddr(Socket::inet_aton($childip),AF_INET);
                   7339:                 if ($childhostname ne '') {
                   7340:                     my $childlonhost = &Apache::lonnet::get_server_homeID($childhostname);
                   7341:                     my ($samedom,$sameinst) = &set_client_info($childlonhost);
                   7342:                     if ($samedom) {
                   7343:                         if ($connchange{'dom'}) {
                   7344:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7345:                                    ." $child for ip $childip </font>");
                   7346:                             kill('INT', $child);
                   7347:                         }
                   7348:                     } elsif ($sameinst) {
                   7349:                         if ($connchange{'intdom'}) {
                   7350:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7351:                                    ." $child for ip $childip </font>");
                   7352:                            kill('INT', $child);
                   7353:                         }
                   7354:                     } else {
                   7355:                         if ($connchange{'other'}) {
                   7356:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7357:                                    ." $child for ip $childip </font>");
                   7358:                             kill('INT', $child);
                   7359:                         }
                   7360:                     }
                   7361:                 }
                   7362:             }
                   7363:         }
                   7364:     }
1.148     foxr     7365:     ReloadApache;
1.165     albertel 7366:     &status("Finished reloading hosts.tab");
1.144     foxr     7367: }
                   7368: 
1.57      www      7369: sub checkchildren {
1.165     albertel 7370:     &status("Checking on the children (sending signals)");
1.57      www      7371:     &initnewstatus();
                   7372:     &logstatus();
                   7373:     &logthis('Going to check on the children');
1.134     albertel 7374:     my $docdir=$perlvar{'lonDocRoot'};
1.61      harris41 7375:     foreach (sort keys %children) {
1.221     albertel 7376: 	#sleep 1;
1.57      www      7377:         unless (kill 'USR1' => $_) {
                   7378: 	    &logthis ('Child '.$_.' is dead');
                   7379:             &logstatus($$.' is dead');
1.221     albertel 7380: 	    delete($children{$_});
1.57      www      7381:         } 
1.61      harris41 7382:     }
1.63      www      7383:     sleep 5;
1.212     foxr     7384:     $SIG{ALRM} = sub { Debug("timeout"); 
                   7385: 		       die "timeout";  };
1.113     albertel 7386:     $SIG{__DIE__} = 'DEFAULT';
1.165     albertel 7387:     &status("Checking on the children (waiting for reports)");
1.63      www      7388:     foreach (sort keys %children) {
                   7389:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113     albertel 7390:           eval {
                   7391:             alarm(300);
1.63      www      7392: 	    &logthis('Child '.$_.' did not respond');
1.67      albertel 7393: 	    kill 9 => $_;
1.131     albertel 7394: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   7395: 	    #$subj="LON: $currenthostid killed lond process $_";
                   7396: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
                   7397: 	    #$execdir=$perlvar{'lonDaemons'};
                   7398: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.221     albertel 7399: 	    delete($children{$_});
1.113     albertel 7400: 	    alarm(0);
                   7401: 	  }
1.63      www      7402:         }
                   7403:     }
1.113     albertel 7404:     $SIG{ALRM} = 'DEFAULT';
1.155     albertel 7405:     $SIG{__DIE__} = \&catchexception;
1.165     albertel 7406:     &status("Finished checking children");
1.221     albertel 7407:     &logthis('Finished Checking children');
1.57      www      7408: }
                   7409: 
1.1       albertel 7410: # --------------------------------------------------------------------- Logging
                   7411: 
                   7412: sub logthis {
                   7413:     my $message=shift;
                   7414:     my $execdir=$perlvar{'lonDaemons'};
                   7415:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
                   7416:     my $now=time;
                   7417:     my $local=localtime($now);
1.58      www      7418:     $lastlog=$local.': '.$message;
1.1       albertel 7419:     print $fh "$local ($$): $message\n";
                   7420: }
                   7421: 
1.77      foxr     7422: # ------------------------- Conditional log if $DEBUG true.
                   7423: sub Debug {
                   7424:     my $message = shift;
                   7425:     if($DEBUG) {
                   7426: 	&logthis($message);
                   7427:     }
                   7428: }
1.161     foxr     7429: 
                   7430: #
                   7431: #   Sub to do replies to client.. this gives a hook for some
                   7432: #   debug tracing too:
                   7433: #  Parameters:
                   7434: #     fd      - File open on client.
                   7435: #     reply   - Text to send to client.
                   7436: #     request - Original request from client.
                   7437: #
1.490     droeschl 7438: #NOTE $reply must be terminated by exactly *one* \n. If $reply is a reference
                   7439: #this is done automatically ($$reply must not contain any \n in this case). 
                   7440: #If $reply is a string the caller has to ensure this.
1.161     foxr     7441: sub Reply {
1.192     foxr     7442:     my ($fd, $reply, $request) = @_;
1.387     albertel 7443:     if (ref($reply)) {
                   7444: 	print $fd $$reply;
                   7445: 	print $fd "\n";
                   7446: 	if ($DEBUG) { Debug("Request was $request  Reply was $$reply"); }
                   7447:     } else {
                   7448: 	print $fd $reply;
                   7449: 	if ($DEBUG) { Debug("Request was $request  Reply was $reply"); }
                   7450:     }
1.212     foxr     7451:     $Transactions++;
                   7452: }
                   7453: 
                   7454: 
                   7455: #
                   7456: #    Sub to report a failure.
                   7457: #    This function:
                   7458: #     -   Increments the failure statistic counters.
                   7459: #     -   Invokes Reply to send the error message to the client.
                   7460: # Parameters:
                   7461: #    fd       - File descriptor open on the client
                   7462: #    reply    - Reply text to emit.
                   7463: #    request  - The original request message (used by Reply
                   7464: #               to debug if that's enabled.
                   7465: # Implicit outputs:
                   7466: #    $Failures- The number of failures is incremented.
                   7467: #    Reply (invoked here) sends a message to the 
                   7468: #    client:
                   7469: #
                   7470: sub Failure {
                   7471:     my $fd      = shift;
                   7472:     my $reply   = shift;
                   7473:     my $request = shift;
                   7474:    
                   7475:     $Failures++;
                   7476:     Reply($fd, $reply, $request);      # That's simple eh?
1.161     foxr     7477: }
1.57      www      7478: # ------------------------------------------------------------------ Log status
                   7479: 
                   7480: sub logstatus {
1.178     foxr     7481:     &status("Doing logging");
                   7482:     my $docdir=$perlvar{'lonDocRoot'};
                   7483:     {
                   7484: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
1.200     matthew  7485:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
1.178     foxr     7486:         $fh->close();
                   7487:     }
1.221     albertel 7488:     &status("Finished $$.txt");
                   7489:     {
                   7490: 	open(LOG,">>$docdir/lon-status/londstatus.txt");
                   7491: 	flock(LOG,LOCK_EX);
                   7492: 	print LOG $$."\t".$clientname."\t".$currenthostid."\t"
                   7493: 	    .$status."\t".$lastlog."\t $keymode\n";
1.275     albertel 7494: 	flock(LOG,LOCK_UN);
1.221     albertel 7495: 	close(LOG);
                   7496:     }
1.178     foxr     7497:     &status("Finished logging");
1.57      www      7498: }
                   7499: 
                   7500: sub initnewstatus {
                   7501:     my $docdir=$perlvar{'lonDocRoot'};
                   7502:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
1.460     foxr     7503:     my $now=time();
1.57      www      7504:     my $local=localtime($now);
                   7505:     print $fh "LOND status $local - parent $$\n\n";
1.64      www      7506:     opendir(DIR,"$docdir/lon-status/londchld");
1.134     albertel 7507:     while (my $filename=readdir(DIR)) {
1.64      www      7508:         unlink("$docdir/lon-status/londchld/$filename");
                   7509:     }
                   7510:     closedir(DIR);
1.57      www      7511: }
                   7512: 
                   7513: # -------------------------------------------------------------- Status setting
                   7514: 
                   7515: sub status {
                   7516:     my $what=shift;
                   7517:     my $now=time;
                   7518:     my $local=localtime($now);
1.178     foxr     7519:     $status=$local.': '.$what;
                   7520:     $0='lond: '.$what.' '.$local;
1.57      www      7521: }
1.11      www      7522: 
1.13      www      7523: # -------------------------------------------------------------- Talk to lonsql
                   7524: 
1.234     foxr     7525: sub sql_reply {
1.12      harris41 7526:     my ($cmd)=@_;
1.234     foxr     7527:     my $answer=&sub_sql_reply($cmd);
                   7528:     if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
1.12      harris41 7529:     return $answer;
                   7530: }
                   7531: 
1.234     foxr     7532: sub sub_sql_reply {
1.12      harris41 7533:     my ($cmd)=@_;
                   7534:     my $unixsock="mysqlsock";
                   7535:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
                   7536:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                   7537:                                       Type    => SOCK_STREAM,
                   7538:                                       Timeout => 10)
                   7539:        or return "con_lost";
1.319     www      7540:     print $sclient "$cmd:$currentdomainid\n";
1.12      harris41 7541:     my $answer=<$sclient>;
                   7542:     chomp($answer);
                   7543:     if (!$answer) { $answer="con_lost"; }
                   7544:     return $answer;
                   7545: }
                   7546: 
1.1       albertel 7547: # --------------------------------------- Is this the home server of an author?
1.11      www      7548: 
1.1       albertel 7549: sub ishome {
                   7550:     my $author=shift;
                   7551:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   7552:     my ($udom,$uname)=split(/\//,$author);
                   7553:     my $proname=propath($udom,$uname);
                   7554:     if (-e $proname) {
                   7555: 	return 'owner';
                   7556:     } else {
                   7557:         return 'not_owner';
                   7558:     }
                   7559: }
                   7560: 
                   7561: # ======================================================= Continue main program
                   7562: # ---------------------------------------------------- Fork once and dissociate
                   7563: 
1.134     albertel 7564: my $fpid=fork;
1.1       albertel 7565: exit if $fpid;
1.29      harris41 7566: die "Couldn't fork: $!" unless defined ($fpid);
1.1       albertel 7567: 
1.29      harris41 7568: POSIX::setsid() or die "Can't start new session: $!";
1.1       albertel 7569: 
                   7570: # ------------------------------------------------------- Write our PID on disk
                   7571: 
1.134     albertel 7572: my $execdir=$perlvar{'lonDaemons'};
1.1       albertel 7573: open (PIDSAVE,">$execdir/logs/lond.pid");
                   7574: print PIDSAVE "$$\n";
                   7575: close(PIDSAVE);
1.190     albertel 7576: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.57      www      7577: &status('Starting');
1.1       albertel 7578: 
1.106     foxr     7579: 
1.1       albertel 7580: 
                   7581: # ----------------------------------------------------- Install signal handlers
                   7582: 
1.57      www      7583: 
1.1       albertel 7584: $SIG{CHLD} = \&REAPER;
                   7585: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   7586: $SIG{HUP}  = \&HUPSMAN;
1.57      www      7587: $SIG{USR1} = \&checkchildren;
1.144     foxr     7588: $SIG{USR2} = \&UpdateHosts;
1.106     foxr     7589: 
1.148     foxr     7590: #  Read the host hashes:
1.368     albertel 7591: &Apache::lonnet::load_hosts_tab();
1.447     raeburn  7592: my %iphost = &Apache::lonnet::get_iphost(1);
1.106     foxr     7593: 
1.480     raeburn  7594: $dist=`$perlvar{'lonDaemons'}/distprobe`;
1.286     albertel 7595: 
1.471     raeburn  7596: my $arch = `uname -i`;
1.475     raeburn  7597: chomp($arch);
1.471     raeburn  7598: if ($arch eq 'unknown') {
                   7599:     $arch = `uname -m`;
1.475     raeburn  7600:     chomp($arch);
1.471     raeburn  7601: }
                   7602: 
1.555     raeburn  7603: unless (lonssl::Read_Connect_Config(\%secureconf,\%perlvar,\%crlchecked) eq 'ok') {
1.532     raeburn  7604:     &logthis('<font color="blue">No connectionrules table. Will fallback to loncapa.conf</font>');
                   7605: }
                   7606: 
1.106     foxr     7607: # --------------------------------------------------------------
                   7608: #   Accept connections.  When a connection comes in, it is validated
                   7609: #   and if good, a child process is created to process transactions
                   7610: #   along the connection.
                   7611: 
1.1       albertel 7612: while (1) {
1.165     albertel 7613:     &status('Starting accept');
1.106     foxr     7614:     $client = $server->accept() or next;
1.165     albertel 7615:     &status('Accepted '.$client.' off to spawn');
1.386     albertel 7616:     make_new_child($client);
1.165     albertel 7617:     &status('Finished spawning');
1.1       albertel 7618: }
                   7619: 
1.212     foxr     7620: sub make_new_child {
                   7621:     my $pid;
                   7622: #    my $cipher;     # Now global
                   7623:     my $sigset;
1.178     foxr     7624: 
1.212     foxr     7625:     $client = shift;
                   7626:     &status('Starting new child '.$client);
                   7627:     &logthis('<font color="green"> Attempting to start child ('.$client.
                   7628: 	     ")</font>");    
                   7629:     # block signal for fork
                   7630:     $sigset = POSIX::SigSet->new(SIGINT);
                   7631:     sigprocmask(SIG_BLOCK, $sigset)
                   7632:         or die "Can't block SIGINT for fork: $!\n";
1.178     foxr     7633: 
1.212     foxr     7634:     die "fork: $!" unless defined ($pid = fork);
1.178     foxr     7635: 
1.212     foxr     7636:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
                   7637: 	                               # connection liveness.
1.178     foxr     7638: 
1.212     foxr     7639:     #
                   7640:     #  Figure out who we're talking to so we can record the peer in 
                   7641:     #  the pid hash.
                   7642:     #
                   7643:     my $caller = getpeername($client);
                   7644:     my ($port,$iaddr);
                   7645:     if (defined($caller) && length($caller) > 0) {
                   7646: 	($port,$iaddr)=unpack_sockaddr_in($caller);
                   7647:     } else {
                   7648: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
                   7649:     }
                   7650:     if (defined($iaddr)) {
                   7651: 	$clientip  = inet_ntoa($iaddr);
                   7652: 	Debug("Connected with $clientip");
                   7653:     } else {
                   7654: 	&logthis("Unable to determine clientip");
                   7655: 	$clientip='Unavailable';
                   7656:     }
                   7657:     
                   7658:     if ($pid) {
                   7659:         # Parent records the child's birth and returns.
                   7660:         sigprocmask(SIG_UNBLOCK, $sigset)
                   7661:             or die "Can't unblock SIGINT for fork: $!\n";
                   7662:         $children{$pid} = $clientip;
                   7663:         &status('Started child '.$pid);
1.462     foxr     7664: 	close($client);
1.212     foxr     7665:         return;
                   7666:     } else {
                   7667:         # Child can *not* return from this subroutine.
                   7668:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
                   7669:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
                   7670:                                 #don't get intercepted
                   7671:         $SIG{USR1}= \&logstatus;
                   7672:         $SIG{ALRM}= \&timeout;
1.468     foxr     7673: 	#
                   7674: 	# Block sigpipe as it gets thrownon socket disconnect and we want to 
                   7675: 	# deal with that as a read faiure instead.
                   7676: 	#
                   7677: 	my $blockset = POSIX::SigSet->new(SIGPIPE);
                   7678: 	sigprocmask(SIG_BLOCK, $blockset);
                   7679: 
1.212     foxr     7680:         $lastlog='Forked ';
                   7681:         $status='Forked';
1.178     foxr     7682: 
1.212     foxr     7683:         # unblock signals
                   7684:         sigprocmask(SIG_UNBLOCK, $sigset)
                   7685:             or die "Can't unblock SIGINT for fork: $!\n";
1.178     foxr     7686: 
1.212     foxr     7687: #        my $tmpsnum=0;            # Now global
                   7688: #---------------------------------------------------- kerberos 5 initialization
                   7689:         &Authen::Krb5::init_context();
1.511     raeburn  7690: 
                   7691:         my $no_ets;
1.559     raeburn  7692:         if ($dist =~ /^(?:centos|rhes|scientific|oracle)(\d+)$/) {
1.511     raeburn  7693:             if ($1 >= 7) {
                   7694:                 $no_ets = 1;
                   7695:             }
                   7696:         } elsif ($dist =~ /^suse(\d+\.\d+)$/) {
                   7697:             if (($1 eq '9.3') || ($1 >= 12.2)) {
                   7698:                 $no_ets = 1; 
                   7699:             }
1.514     raeburn  7700:         } elsif ($dist =~ /^sles(\d+)$/) {
                   7701:             if ($1 > 11) {
                   7702:                 $no_ets = 1;
                   7703:             }
1.511     raeburn  7704:         } elsif ($dist =~ /^fedora(\d+)$/) {
                   7705:             if ($1 < 7) {
                   7706:                 $no_ets = 1;
                   7707:             }
                   7708:         }
                   7709:         unless ($no_ets) {
1.286     albertel 7710: 	    &Authen::Krb5::init_ets();
                   7711: 	}
1.209     albertel 7712: 
1.212     foxr     7713: 	&status('Accepted connection');
                   7714: # =============================================================================
                   7715:             # do something with the connection
                   7716: # -----------------------------------------------------------------------------
                   7717: 	# see if we know client and 'check' for spoof IP by ineffective challenge
1.178     foxr     7718: 
1.278     albertel 7719: 	my $outsideip=$clientip;
                   7720: 	if ($clientip eq '127.0.0.1') {
1.368     albertel 7721: 	    $outsideip=&Apache::lonnet::get_host_ip($perlvar{'lonHostID'});
1.278     albertel 7722: 	}
1.412     foxr     7723: 	&ReadManagerTable();
1.368     albertel 7724: 	my $clientrec=defined(&Apache::lonnet::get_hosts_from_ip($outsideip));
1.278     albertel 7725: 	my $ismanager=($managers{$outsideip}    ne undef);
1.432     raeburn  7726: 	$clientname  = "[unknown]";
1.212     foxr     7727: 	if($clientrec) {	# Establish client type.
                   7728: 	    $ConnectionType = "client";
1.368     albertel 7729: 	    $clientname = (&Apache::lonnet::get_hosts_from_ip($outsideip))[-1];
1.212     foxr     7730: 	    if($ismanager) {
                   7731: 		$ConnectionType = "both";
                   7732: 	    }
                   7733: 	} else {
                   7734: 	    $ConnectionType = "manager";
1.278     albertel 7735: 	    $clientname = $managers{$outsideip};
1.212     foxr     7736: 	}
1.556     raeburn  7737: 	my $clientok;
1.178     foxr     7738: 
1.212     foxr     7739: 	if ($clientrec || $ismanager) {
                   7740: 	    &status("Waiting for init from $clientip $clientname");
                   7741: 	    &logthis('<font color="yellow">INFO: Connection, '.
                   7742: 		     $clientip.
                   7743: 		  " ($clientname) connection type = $ConnectionType </font>" );
                   7744: 	    &status("Connecting $clientip  ($clientname))"); 
                   7745: 	    my $remotereq=<$client>;
                   7746: 	    chomp($remotereq);
                   7747: 	    Debug("Got init: $remotereq");
1.337     albertel 7748: 
1.212     foxr     7749: 	    if ($remotereq =~ /^init/) {
                   7750: 		&sethost("sethost:$perlvar{'lonHostID'}");
                   7751: 		#
                   7752: 		#  If the remote is attempting a local init... give that a try:
                   7753: 		#
1.432     raeburn  7754: 		(my $i, my $inittype, $clientversion) = split(/:/, $remotereq);
1.492     droeschl 7755:         # For LON-CAPA 2.9, the  client session will have sent its LON-CAPA
                   7756:         # version when initiating the connection. For LON-CAPA 2.8 and older,
                   7757:         # the version is retrieved from the global %loncaparevs in lonnet.pm.            
1.494     droeschl 7758:         # $clientversion contains path to keyfile if $inittype eq 'local'
                   7759:         # it's overridden below in this case
1.492     droeschl 7760:         $clientversion ||= $Apache::lonnet::loncaparevs{$clientname};
1.209     albertel 7761: 
1.212     foxr     7762: 		# If the connection type is ssl, but I didn't get my
                   7763: 		# certificate files yet, then I'll drop  back to 
                   7764: 		# insecure (if allowed).
1.532     raeburn  7765: 
                   7766:                 if ($inittype eq "ssl") {
                   7767:                     my $context;
                   7768:                     if ($clientsamedom) {
                   7769:                         $context = 'dom';
                   7770:                         if ($secureconf{'connfrom'}{'dom'} eq 'no') {
                   7771:                             $inittype = "";
                   7772:                         }
                   7773:                     } elsif ($clientsameinst) {
                   7774:                         $context = 'intdom';
                   7775:                         if ($secureconf{'connfrom'}{'intdom'} eq 'no') {
                   7776:                             $inittype = "";
                   7777:                         }
                   7778:                     } else {
                   7779:                         $context = 'other';
                   7780:                         if ($secureconf{'connfrom'}{'other'} eq 'no') {
                   7781:                             $inittype = "";
                   7782:                         }
                   7783:                     }
                   7784:                     if ($inittype eq '') {
                   7785:                         &logthis("<font color=\"blue\"> Domain config set "
                   7786:                                 ."to no ssl for $clientname (context: $context)"
                   7787:                                 ." -- trying insecure auth</font>");
                   7788:                     }
                   7789:                 }
                   7790: 
1.212     foxr     7791: 		if($inittype eq "ssl") {
                   7792: 		    my ($ca, $cert) = lonssl::CertificateFile;
                   7793: 		    my $kfile       = lonssl::KeyFile;
                   7794: 		    if((!$ca)   || 
                   7795: 		       (!$cert) || 
                   7796: 		       (!$kfile)) {
                   7797: 			$inittype = ""; # This forces insecure attempt.
                   7798: 			&logthis("<font color=\"blue\"> Certificates not "
                   7799: 				 ."installed -- trying insecure auth</font>");
1.224     foxr     7800: 		    } else {	# SSL certificates are in place so
1.212     foxr     7801: 		    }		# Leave the inittype alone.
                   7802: 		}
                   7803: 
                   7804: 		if($inittype eq "local") {
1.432     raeburn  7805:                     $clientversion = $perlvar{'lonVersion'};
1.212     foxr     7806: 		    my $key = LocalConnection($client, $remotereq);
                   7807: 		    if($key) {
                   7808: 			Debug("Got local key $key");
                   7809: 			$clientok     = 1;
                   7810: 			my $cipherkey = pack("H32", $key);
                   7811: 			$cipher       = new IDEA($cipherkey);
                   7812: 			print $client "ok:local\n";
1.442     www      7813: 			&logthis('<font color="green">'
1.212     foxr     7814: 				 . "Successful local authentication </font>");
                   7815: 			$keymode = "local"
1.178     foxr     7816: 		    } else {
1.212     foxr     7817: 			Debug("Failed to get local key");
                   7818: 			$clientok = 0;
                   7819: 			shutdown($client, 3);
                   7820: 			close $client;
1.178     foxr     7821: 		    }
1.212     foxr     7822: 		} elsif ($inittype eq "ssl") {
1.532     raeburn  7823: 		    my $key = SSLConnection($client,$clientname);
1.212     foxr     7824: 		    if ($key) {
                   7825: 			$clientok = 1;
                   7826: 			my $cipherkey = pack("H32", $key);
                   7827: 			$cipher       = new IDEA($cipherkey);
                   7828: 			&logthis('<font color="green">'
                   7829: 				 ."Successfull ssl authentication with $clientname </font>");
                   7830: 			$keymode = "ssl";
                   7831: 	     
1.178     foxr     7832: 		    } else {
1.212     foxr     7833: 			$clientok = 0;
                   7834: 			close $client;
1.178     foxr     7835: 		    }
1.212     foxr     7836: 	   
                   7837: 		} else {
                   7838: 		    my $ok = InsecureConnection($client);
                   7839: 		    if($ok) {
                   7840: 			$clientok = 1;
                   7841: 			&logthis('<font color="green">'
                   7842: 				 ."Successful insecure authentication with $clientname </font>");
                   7843: 			print $client "ok\n";
                   7844: 			$keymode = "insecure";
1.178     foxr     7845: 		    } else {
1.212     foxr     7846: 			&logthis('<font color="yellow">'
                   7847: 				  ."Attempted insecure connection disallowed </font>");
                   7848: 			close $client;
                   7849: 			$clientok = 0;
1.178     foxr     7850: 		    }
                   7851: 		}
1.212     foxr     7852: 	    } else {
                   7853: 		&logthis(
                   7854: 			 "<font color='blue'>WARNING: "
                   7855: 			 ."$clientip failed to initialize: >$remotereq< </font>");
                   7856: 		&status('No init '.$clientip);
                   7857: 	    }
                   7858: 	} else {
                   7859: 	    &logthis(
                   7860: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
                   7861: 	    &status('Hung up on '.$clientip);
                   7862: 	}
                   7863:  
                   7864: 	if ($clientok) {
                   7865: # ---------------- New known client connecting, could mean machine online again
1.368     albertel 7866: 	    if (&Apache::lonnet::get_host_ip($currenthostid) ne $clientip 
1.367     albertel 7867: 		&& $clientip ne '127.0.0.1') {
1.375     albertel 7868: 		&Apache::lonnet::reconlonc($clientname);
1.212     foxr     7869: 	    }
                   7870: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
                   7871: 	    &status('Will listen to '.$clientname);
                   7872: # ------------------------------------------------------------ Process requests
                   7873: 	    my $keep_going = 1;
                   7874: 	    my $user_input;
1.556     raeburn  7875: 
1.212     foxr     7876: 	    while(($user_input = get_request) && $keep_going) {
                   7877: 		alarm(120);
                   7878: 		Debug("Main: Got $user_input\n");
                   7879: 		$keep_going = &process_request($user_input);
1.178     foxr     7880: 		alarm(0);
1.212     foxr     7881: 		&status('Listening to '.$clientname." ($keymode)");	   
1.161     foxr     7882: 	    }
1.212     foxr     7883: 
1.59      www      7884: # --------------------------------------------- client unknown or fishy, refuse
1.212     foxr     7885: 	}  else {
1.161     foxr     7886: 	    print $client "refused\n";
                   7887: 	    $client->close();
1.190     albertel 7888: 	    &logthis("<font color='blue'>WARNING: "
1.161     foxr     7889: 		     ."Rejected client $clientip, closing connection</font>");
                   7890: 	}
1.525     raeburn  7891:     }
1.161     foxr     7892:     
1.1       albertel 7893: # =============================================================================
1.161     foxr     7894:     
1.190     albertel 7895:     &logthis("<font color='red'>CRITICAL: "
1.161     foxr     7896: 	     ."Disconnect from $clientip ($clientname)</font>");    
                   7897:     
                   7898:     
                   7899:     # this exit is VERY important, otherwise the child will become
                   7900:     # a producer of more and more children, forking yourself into
                   7901:     # process death.
                   7902:     exit;
1.106     foxr     7903:     
1.78      foxr     7904: }
1.532     raeburn  7905: 
                   7906: #
                   7907: #  Used to determine if a particular client is from the same domain
1.556     raeburn  7908: #  as the current server, or from the same internet domain, and
                   7909: #  also if the client can host sessions for the domain's users.
                   7910: #  A hash is populated with keys set to commands sent by the client
                   7911: #  which may not be executed for this domain.
1.532     raeburn  7912: #
                   7913: #  Optional input -- the client to check for domain and internet domain.
                   7914: #  If not specified, defaults to the package variable: $clientname
                   7915: #
                   7916: #  If called in array context will not set package variables, but will
                   7917: #  instead return an array of two values - (a) true if client is in the
1.556     raeburn  7918: #  same domain as the server, and (b) true if client is in the same 
                   7919: #  internet domain.
1.532     raeburn  7920: #
                   7921: #  If called in scalar context, sets package variables for current client:
                   7922: #
1.556     raeburn  7923: #  $clienthomedom    - LonCAPA domain of homeID for client.
                   7924: #  $clientsamedom    - LonCAPA domain same for this host and client.
                   7925: #  $clientintdom     - LonCAPA "internet domain" for client.
                   7926: #  $clientsameinst   - LonCAPA "internet domain" same for this host & client.
                   7927: #  $clientremoteok   - If current domain permits hosting on this client: 1
                   7928: #  %clientprohibited - Commands prohibited for domain's users for this client.
                   7929: #
                   7930: #  if the host and client have the same "internet domain", then the value
                   7931: #  of $clientremoteok is not used, and no commands are prohibited.
1.532     raeburn  7932: #
                   7933: #  returns 1 to indicate package variables have been set for current client.
                   7934: #
                   7935: 
                   7936: sub set_client_info {
                   7937:     my ($lonhost) = @_;
                   7938:     $lonhost ||= $clientname;
                   7939:     my $clienthost = &Apache::lonnet::hostname($lonhost);
                   7940:     my $clientserverhomeID = &Apache::lonnet::get_server_homeID($clienthost);
                   7941:     my $homedom = &Apache::lonnet::host_domain($clientserverhomeID);
                   7942:     my $samedom = 0;
1.557     raeburn  7943:     if ($perlvar{'lonDefDomain'} eq $homedom) {
1.532     raeburn  7944:         $samedom = 1;
                   7945:     }
                   7946:     my $intdom = &Apache::lonnet::internet_dom($clientserverhomeID);
                   7947:     my $sameinst = 0;
                   7948:     if ($intdom ne '') {
                   7949:         my $internet_names = &Apache::lonnet::get_internet_names($currenthostid);
                   7950:         if (ref($internet_names) eq 'ARRAY') {
                   7951:             if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   7952:                 $sameinst = 1;
                   7953:             }
                   7954:         }
                   7955:     }
                   7956:     if (wantarray) {
                   7957:         return ($samedom,$sameinst);
                   7958:     } else {
                   7959:         $clienthomedom = $homedom;
                   7960:         $clientsamedom = $samedom;
                   7961:         $clientintdom = $intdom;
                   7962:         $clientsameinst = $sameinst;
1.556     raeburn  7963:         if ($clientsameinst) {
                   7964:             undef($clientremoteok);
                   7965:             undef(%clientprohibited);
                   7966:         } else {
                   7967:             $clientremoteok = &get_remote_hostable($currentdomainid);
                   7968:             %clientprohibited = &get_prohibited($currentdomainid);
                   7969:         }
1.532     raeburn  7970:         return 1;
                   7971:     }
                   7972: }
                   7973: 
1.261     foxr     7974: #
                   7975: #   Determine if a user is an author for the indicated domain.
                   7976: #
                   7977: # Parameters:
                   7978: #    domain          - domain to check in .
                   7979: #    user            - Name of user to check.
                   7980: #
                   7981: # Return:
                   7982: #     1             - User is an author for domain.
                   7983: #     0             - User is not an author for domain.
                   7984: sub is_author {
                   7985:     my ($domain, $user) = @_;
                   7986: 
                   7987:     &Debug("is_author: $user @ $domain");
                   7988: 
                   7989:     my $hashref = &tie_user_hash($domain, $user, "roles",
                   7990: 				 &GDBM_READER());
                   7991: 
                   7992:     #  Author role should show up as a key /domain/_au
1.78      foxr     7993: 
1.321     albertel 7994:     my $value;
1.487     foxr     7995:     if ($hashref) {
1.78      foxr     7996: 
1.487     foxr     7997: 	my $key    = "/$domain/_au";
                   7998: 	if (defined($hashref)) {
                   7999: 	    $value = $hashref->{$key};
                   8000: 	    if(!untie_user_hash($hashref)) {
                   8001: 		return 'error: ' .  ($!+0)." untie (GDBM) Failed";
                   8002: 	    }
                   8003: 	}
                   8004: 	
                   8005: 	if(defined($value)) {
                   8006: 	    &Debug("$user @ $domain is an author");
                   8007: 	}
                   8008:     } else {
                   8009: 	return 'error: '.($!+0)." tie (GDBM) Failed";
1.261     foxr     8010:     }
                   8011: 
                   8012:     return defined($value);
                   8013: }
1.78      foxr     8014: #
                   8015: #   Checks to see if the input roleput request was to set
1.482     www      8016: # an author role.  If so, creates construction space 
1.78      foxr     8017: # Parameters:
                   8018: #    request   - The request sent to the rolesput subchunk.
                   8019: #                We're looking for  /domain/_au
                   8020: #    domain    - The domain in which the user is having roles doctored.
                   8021: #    user      - Name of the user for which the role is being put.
                   8022: #    authtype  - The authentication type associated with the user.
                   8023: #
1.289     albertel 8024: sub manage_permissions {
1.192     foxr     8025:     my ($request, $domain, $user, $authtype) = @_;
1.78      foxr     8026:     # See if the request is of the form /$domain/_au
1.289     albertel 8027:     if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
1.484     raeburn  8028:         my $path=$perlvar{'lonDocRoot'}."/priv/$domain";
1.482     www      8029:         unless (-e $path) {        
                   8030:            mkdir($path);
                   8031:         }
                   8032:         unless (-e $path.'/'.$user) {
                   8033:            mkdir($path.'/'.$user);
                   8034:         }
1.78      foxr     8035:     }
                   8036: }
1.222     foxr     8037: 
                   8038: 
                   8039: #
                   8040: #  Return the full path of a user password file, whether it exists or not.
                   8041: # Parameters:
                   8042: #   domain     - Domain in which the password file lives.
                   8043: #   user       - name of the user.
                   8044: # Returns:
                   8045: #    Full passwd path:
                   8046: #
                   8047: sub password_path {
                   8048:     my ($domain, $user) = @_;
1.264     albertel 8049:     return &propath($domain, $user).'/passwd';
1.222     foxr     8050: }
                   8051: 
                   8052: #   Password Filename
                   8053: #   Returns the path to a passwd file given domain and user... only if
                   8054: #  it exists.
                   8055: # Parameters:
                   8056: #   domain    - Domain in which to search.
                   8057: #   user      - username.
                   8058: # Returns:
                   8059: #   - If the password file exists returns its path.
                   8060: #   - If the password file does not exist, returns undefined.
                   8061: #
                   8062: sub password_filename {
                   8063:     my ($domain, $user) = @_;
                   8064: 
                   8065:     Debug ("PasswordFilename called: dom = $domain user = $user");
                   8066: 
                   8067:     my $path  = &password_path($domain, $user);
                   8068:     Debug("PasswordFilename got path: $path");
                   8069:     if(-e $path) {
                   8070: 	return $path;
                   8071:     } else {
                   8072: 	return undef;
                   8073:     }
                   8074: }
                   8075: 
                   8076: #
                   8077: #   Rewrite the contents of the user's passwd file.
                   8078: #  Parameters:
                   8079: #    domain    - domain of the user.
                   8080: #    name      - User's name.
                   8081: #    contents  - New contents of the file.
1.533     raeburn  8082: #    saveold   - (optional). If true save old file in a passwd.bak file.
1.222     foxr     8083: # Returns:
                   8084: #   0    - Failed.
                   8085: #   1    - Success.
                   8086: #
                   8087: sub rewrite_password_file {
1.533     raeburn  8088:     my ($domain, $user, $contents, $saveold) = @_;
1.222     foxr     8089: 
                   8090:     my $file = &password_filename($domain, $user);
                   8091:     if (defined $file) {
1.533     raeburn  8092:         if ($saveold) {
                   8093:             my $bakfile = $file.'.bak';
                   8094:             if (CopyFile($file,$bakfile)) {
                   8095:                 chmod(0400,$bakfile);
                   8096:                 &logthis("Old password saved in passwd.bak for internally authenticated user: $user:$domain");
                   8097:             } else {
                   8098:                 &logthis("Failed to save old password in passwd.bak for internally authenticated user: $user:$domain");
                   8099:             }
                   8100:         }
1.222     foxr     8101: 	my $pf = IO::File->new(">$file");
                   8102: 	if($pf) {
                   8103: 	    print $pf "$contents\n";
                   8104: 	    return 1;
                   8105: 	} else {
                   8106: 	    return 0;
                   8107: 	}
                   8108:     } else {
                   8109: 	return 0;
                   8110:     }
                   8111: 
                   8112: }
                   8113: 
1.78      foxr     8114: #
1.222     foxr     8115: #   get_auth_type - Determines the authorization type of a user in a domain.
1.78      foxr     8116: 
                   8117: #     Returns the authorization type or nouser if there is no such user.
                   8118: #
1.436     raeburn  8119: sub get_auth_type {
1.192     foxr     8120:     my ($domain, $user)  = @_;
1.78      foxr     8121: 
1.222     foxr     8122:     Debug("get_auth_type( $domain, $user ) \n");
1.78      foxr     8123:     my $proname    = &propath($domain, $user); 
                   8124:     my $passwdfile = "$proname/passwd";
                   8125:     if( -e $passwdfile ) {
                   8126: 	my $pf = IO::File->new($passwdfile);
                   8127: 	my $realpassword = <$pf>;
                   8128: 	chomp($realpassword);
1.79      foxr     8129: 	Debug("Password info = $realpassword\n");
1.78      foxr     8130: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79      foxr     8131: 	Debug("Authtype = $authtype, content = $contentpwd\n");
1.259     raeburn  8132: 	return "$authtype:$contentpwd";     
1.224     foxr     8133:     } else {
1.79      foxr     8134: 	Debug("Returning nouser");
1.78      foxr     8135: 	return "nouser";
                   8136:     }
1.1       albertel 8137: }
                   8138: 
1.220     foxr     8139: #
                   8140: #  Validate a user given their domain, name and password.  This utility
                   8141: #  function is used by both  AuthenticateHandler and ChangePasswordHandler
                   8142: #  to validate the login credentials of a user.
                   8143: # Parameters:
                   8144: #    $domain    - The domain being logged into (this is required due to
                   8145: #                 the capability for multihomed systems.
                   8146: #    $user      - The name of the user being validated.
                   8147: #    $password  - The user's propoposed password.
                   8148: #
                   8149: # Returns:
                   8150: #     1        - The domain,user,pasword triplet corresponds to a valid
                   8151: #                user.
                   8152: #     0        - The domain,user,password triplet is not a valid user.
                   8153: #
                   8154: sub validate_user {
1.396     raeburn  8155:     my ($domain, $user, $password, $checkdefauth) = @_;
1.220     foxr     8156: 
                   8157:     # Why negative ~pi you may well ask?  Well this function is about
                   8158:     # authentication, and therefore very important to get right.
                   8159:     # I've initialized the flag that determines whether or not I've 
                   8160:     # validated correctly to a value it's not supposed to get.
                   8161:     # At the end of this function. I'll ensure that it's not still that
                   8162:     # value so we don't just wind up returning some accidental value
                   8163:     # as a result of executing an unforseen code path that
1.249     foxr     8164:     # did not set $validated.  At the end of valid execution paths,
                   8165:     # validated shoule be 1 for success or 0 for failuer.
1.220     foxr     8166: 
                   8167:     my $validated = -3.14159;
                   8168: 
                   8169:     #  How we authenticate is determined by the type of authentication
                   8170:     #  the user has been assigned.  If the authentication type is
                   8171:     #  "nouser", the user does not exist so we will return 0.
                   8172: 
1.222     foxr     8173:     my $contents = &get_auth_type($domain, $user);
1.220     foxr     8174:     my ($howpwd, $contentpwd) = split(/:/, $contents);
                   8175: 
                   8176:     my $null = pack("C",0);	# Used by kerberos auth types.
                   8177: 
1.395     raeburn  8178:     if ($howpwd eq 'nouser') {
1.396     raeburn  8179:         if ($checkdefauth) {
                   8180:             my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   8181:             if ($domdefaults{'auth_def'} eq 'localauth') {
                   8182:                 $howpwd = $domdefaults{'auth_def'};
                   8183:                 $contentpwd = $domdefaults{'auth_arg_def'};
                   8184:             } elsif ((($domdefaults{'auth_def'} eq 'krb4') || 
                   8185:                       ($domdefaults{'auth_def'} eq 'krb5')) &&
                   8186:                      ($domdefaults{'auth_arg_def'} ne '')) {
                   8187:                 $howpwd = $domdefaults{'auth_def'};
                   8188:                 $contentpwd = $domdefaults{'auth_arg_def'}; 
                   8189:             }
1.395     raeburn  8190:         }
1.533     raeburn  8191:     }
1.220     foxr     8192:     if ($howpwd ne 'nouser') {
                   8193: 	if($howpwd eq "internal") { # Encrypted is in local password file.
1.518     raeburn  8194:             if (length($contentpwd) == 13) {
                   8195:                 $validated = (crypt($password,$contentpwd) eq $contentpwd);
                   8196:                 if ($validated) {
1.533     raeburn  8197:                     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   8198:                     if ($domdefaults{'intauth_switch'}) {
                   8199:                         my $ncpass = &hash_passwd($domain,$password);
                   8200:                         my $saveold;
                   8201:                         if ($domdefaults{'intauth_switch'} == 2) {
                   8202:                             $saveold = 1;
                   8203:                         }
                   8204:                         if (&rewrite_password_file($domain,$user,"$howpwd:$ncpass",$saveold)) {
                   8205:                             &update_passwd_history($user,$domain,$howpwd,'conversion');
                   8206:                             &logthis("Validated password hashed with bcrypt for $user:$domain");
                   8207:                         }
1.518     raeburn  8208:                     }
                   8209:                 }
                   8210:             } else {
1.533     raeburn  8211:                 $validated = &check_internal_passwd($password,$contentpwd,$domain,$user);
1.518     raeburn  8212:             }
1.220     foxr     8213: 	}
                   8214: 	elsif ($howpwd eq "unix") { # User is a normal unix user.
                   8215: 	    $contentpwd = (getpwnam($user))[1];
                   8216: 	    if($contentpwd) {
                   8217: 		if($contentpwd eq 'x') { # Shadow password file...
                   8218: 		    my $pwauth_path = "/usr/local/sbin/pwauth";
                   8219: 		    open PWAUTH,  "|$pwauth_path" or
                   8220: 			die "Cannot invoke authentication";
                   8221: 		    print PWAUTH "$user\n$password\n";
                   8222: 		    close PWAUTH;
                   8223: 		    $validated = ! $?;
                   8224: 
                   8225: 		} else { 	         # Passwords in /etc/passwd. 
                   8226: 		    $validated = (crypt($password,
                   8227: 					$contentpwd) eq $contentpwd);
                   8228: 		}
                   8229: 	    } else {
                   8230: 		$validated = 0;
                   8231: 	    }
1.439     raeburn  8232: 	} elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
                   8233:             my $checkwithkrb5 = 0;
                   8234:             if ($dist =~/^fedora(\d+)$/) {
                   8235:                 if ($1 > 11) {
                   8236:                     $checkwithkrb5 = 1;
                   8237:                 }
                   8238:             } elsif ($dist =~ /^suse([\d.]+)$/) {
                   8239:                 if ($1 > 11.1) {
                   8240:                     $checkwithkrb5 = 1; 
                   8241:                 }
                   8242:             }
                   8243:             if ($checkwithkrb5) {
                   8244:                 $validated = &krb5_authen($password,$null,$user,$contentpwd);
                   8245:             } else {
                   8246:                 $validated = &krb4_authen($password,$null,$user,$contentpwd);
                   8247:             }
1.224     foxr     8248: 	} elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
1.439     raeburn  8249:             $validated = &krb5_authen($password,$null,$user,$contentpwd);
1.224     foxr     8250: 	} elsif ($howpwd eq "localauth") { 
1.220     foxr     8251: 	    #  Authenticate via installation specific authentcation method:
                   8252: 	    $validated = &localauth::localauth($user, 
                   8253: 					       $password, 
1.353     albertel 8254: 					       $contentpwd,
                   8255: 					       $domain);
1.358     albertel 8256: 	    if ($validated < 0) {
1.357     albertel 8257: 		&logthis("localauth for $contentpwd $user:$domain returned a $validated");
                   8258: 		$validated = 0;
                   8259: 	    }
1.224     foxr     8260: 	} else {			# Unrecognized auth is also bad.
1.220     foxr     8261: 	    $validated = 0;
                   8262: 	}
                   8263:     } else {
                   8264: 	$validated = 0;
                   8265:     }
                   8266:     #
                   8267:     #  $validated has the correct stat of the authentication:
                   8268:     #
                   8269: 
                   8270:     unless ($validated != -3.14159) {
1.249     foxr     8271: 	#  I >really really< want to know if this happens.
                   8272: 	#  since it indicates that user authentication is badly
                   8273: 	#  broken in some code path.
                   8274:         #
                   8275: 	die "ValidateUser - failed to set the value of validated $domain, $user $password";
1.220     foxr     8276:     }
                   8277:     return $validated;
                   8278: }
                   8279: 
1.518     raeburn  8280: sub check_internal_passwd {
1.533     raeburn  8281:     my ($plainpass,$stored,$domain,$user) = @_;
1.518     raeburn  8282:     my (undef,$method,@rest) = split(/!/,$stored);
1.533     raeburn  8283:     if ($method eq 'bcrypt') {
1.518     raeburn  8284:         my $result = &hash_passwd($domain,$plainpass,@rest);
                   8285:         if ($result ne $stored) {
                   8286:             return 0;
                   8287:         }
1.533     raeburn  8288:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   8289:         if ($domdefaults{'intauth_check'}) {
                   8290:             # Upgrade to a larger number of rounds if necessary
                   8291:             my $defaultcost = $domdefaults{'intauth_cost'};
                   8292:             if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
                   8293:                 $defaultcost = 10;
                   8294:             }
                   8295:             if (int($rest[0])<int($defaultcost)) {
                   8296:                 if ($domdefaults{'intauth_check'} == 1) { 
                   8297:                     my $ncpass = &hash_passwd($domain,$plainpass);
                   8298:                     if (&rewrite_password_file($domain,$user,"internal:$ncpass")) {
                   8299:                         &update_passwd_history($user,$domain,'internal','update cost');
                   8300:                         &logthis("Validated password hashed with bcrypt for $user:$domain");
                   8301:                     }
                   8302:                     return 1;
                   8303:                 } elsif ($domdefaults{'intauth_check'} == 2) {
                   8304:                     return 0;
                   8305:                 }
                   8306:             }
                   8307:         } else {
                   8308:             return 1;
1.518     raeburn  8309:         }
                   8310:     }
                   8311:     return 0;
                   8312: }
                   8313: 
                   8314: sub get_last_authchg {
                   8315:     my ($domain,$user) = @_;
                   8316:     my $lastmod;
                   8317:     my $logname = &propath($domain,$user).'/passwd.log';
                   8318:     if (-e "$logname") {
                   8319:         $lastmod = (stat("$logname"))[9];
                   8320:     }
                   8321:     return $lastmod;
                   8322: }
                   8323: 
1.439     raeburn  8324: sub krb4_authen {
                   8325:     my ($password,$null,$user,$contentpwd) = @_;
                   8326:     my $validated = 0;
                   8327:     if (!($password =~ /$null/) ) {  # Null password not allowed.
                   8328:         eval {
                   8329:             require Authen::Krb4;
                   8330:         };
                   8331:         if (!$@) {
                   8332:             my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
                   8333:                                                        "",
                   8334:                                                        $contentpwd,,
                   8335:                                                        'krbtgt',
                   8336:                                                        $contentpwd,
                   8337:                                                        1,
                   8338:                                                        $password);
                   8339:             if(!$k4error) {
                   8340:                 $validated = 1;
                   8341:             } else {
                   8342:                 $validated = 0;
                   8343:                 &logthis('krb4: '.$user.', '.$contentpwd.', '.
                   8344:                           &Authen::Krb4::get_err_txt($Authen::Krb4::error));
                   8345:             }
                   8346:         } else {
                   8347:             $validated = krb5_authen($password,$null,$user,$contentpwd);
                   8348:         }
                   8349:     }
                   8350:     return $validated;
                   8351: }
                   8352: 
                   8353: sub krb5_authen {
                   8354:     my ($password,$null,$user,$contentpwd) = @_;
                   8355:     my $validated = 0;
                   8356:     if(!($password =~ /$null/)) { # Null password not allowed.
                   8357:         my $krbclient = &Authen::Krb5::parse_name($user.'@'
                   8358:                                                   .$contentpwd);
                   8359:         my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
                   8360:         my $krbserver  = &Authen::Krb5::parse_name($krbservice);
                   8361:         my $credentials= &Authen::Krb5::cc_default();
                   8362:         $credentials->initialize(&Authen::Krb5::parse_name($user.'@'
                   8363:                                                             .$contentpwd));
                   8364:         my $krbreturn;
                   8365:         if (exists(&Authen::Krb5::get_init_creds_password)) {
                   8366:             $krbreturn =
                   8367:                 &Authen::Krb5::get_init_creds_password($krbclient,$password,
                   8368:                                                           $krbservice);
                   8369:             $validated = (ref($krbreturn) eq 'Authen::Krb5::Creds');
                   8370:         } else {
                   8371:             $krbreturn  =
                   8372:                 &Authen::Krb5::get_in_tkt_with_password($krbclient,$krbserver,
                   8373:                                                          $password,$credentials);
                   8374:             $validated = ($krbreturn == 1);
                   8375:         }
                   8376:         if (!$validated) {
                   8377:             &logthis('krb5: '.$user.', '.$contentpwd.', '.
                   8378:                      &Authen::Krb5::error());
                   8379:         }
                   8380:     }
                   8381:     return $validated;
                   8382: }
1.220     foxr     8383: 
1.84      albertel 8384: sub addline {
                   8385:     my ($fname,$hostid,$ip,$newline)=@_;
                   8386:     my $contents;
                   8387:     my $found=0;
1.355     albertel 8388:     my $expr='^'.quotemeta($hostid).':'.quotemeta($ip).':';
1.134     albertel 8389:     my $sh;
1.84      albertel 8390:     if ($sh=IO::File->new("$fname.subscription")) {
                   8391: 	while (my $subline=<$sh>) {
                   8392: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
                   8393: 	}
                   8394: 	$sh->close();
                   8395:     }
                   8396:     $sh=IO::File->new(">$fname.subscription");
                   8397:     if ($contents) { print $sh $contents; }
                   8398:     if ($newline) { print $sh $newline; }
                   8399:     $sh->close();
                   8400:     return $found;
1.86      www      8401: }
                   8402: 
1.234     foxr     8403: sub get_chat {
1.324     raeburn  8404:     my ($cdom,$cname,$udom,$uname,$group)=@_;
1.310     albertel 8405: 
1.87      www      8406:     my @entries=();
1.324     raeburn  8407:     my $namespace = 'nohist_chatroom';
                   8408:     my $namespace_inroom = 'nohist_inchatroom';
1.335     albertel 8409:     if ($group ne '') {
1.324     raeburn  8410:         $namespace .= '_'.$group;
                   8411:         $namespace_inroom .= '_'.$group;
                   8412:     }
                   8413:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 8414: 				 &GDBM_READER());
                   8415:     if ($hashref) {
                   8416: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.311     albertel 8417: 	&untie_user_hash($hashref);
1.123     www      8418:     }
1.124     www      8419:     my @participants=();
1.134     albertel 8420:     my $cutoff=time-60;
1.324     raeburn  8421:     $hashref = &tie_user_hash($cdom, $cname, $namespace_inroom,
1.310     albertel 8422: 			      &GDBM_WRCREAT());
                   8423:     if ($hashref) {
                   8424:         $hashref->{$uname.':'.$udom}=time;
                   8425:         foreach my $user (sort(keys(%$hashref))) {
                   8426: 	    if ($hashref->{$user}>$cutoff) {
                   8427: 		push(@participants, 'active_participant:'.$user);
1.123     www      8428:             }
                   8429:         }
1.311     albertel 8430:         &untie_user_hash($hashref);
1.86      www      8431:     }
1.124     www      8432:     return (@participants,@entries);
1.86      www      8433: }
                   8434: 
1.234     foxr     8435: sub chat_add {
1.324     raeburn  8436:     my ($cdom,$cname,$newchat,$group)=@_;
1.88      albertel 8437:     my @entries=();
1.142     www      8438:     my $time=time;
1.324     raeburn  8439:     my $namespace = 'nohist_chatroom';
                   8440:     my $logfile = 'chatroom.log';
1.335     albertel 8441:     if ($group ne '') {
1.324     raeburn  8442:         $namespace .= '_'.$group;
                   8443:         $logfile = 'chatroom_'.$group.'.log';
                   8444:     }
                   8445:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 8446: 				 &GDBM_WRCREAT());
                   8447:     if ($hashref) {
                   8448: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.88      albertel 8449: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
                   8450: 	my ($thentime,$idnum)=split(/\_/,$lastid);
                   8451: 	my $newid=$time.'_000000';
                   8452: 	if ($thentime==$time) {
                   8453: 	    $idnum=~s/^0+//;
                   8454: 	    $idnum++;
                   8455: 	    $idnum=substr('000000'.$idnum,-6,6);
                   8456: 	    $newid=$time.'_'.$idnum;
                   8457: 	}
1.310     albertel 8458: 	$hashref->{$newid}=$newchat;
1.88      albertel 8459: 	my $expired=$time-3600;
1.310     albertel 8460: 	foreach my $comment (keys(%$hashref)) {
                   8461: 	    my ($thistime) = ($comment=~/(\d+)\_/);
1.88      albertel 8462: 	    if ($thistime<$expired) {
1.310     albertel 8463: 		delete $hashref->{$comment};
1.88      albertel 8464: 	    }
                   8465: 	}
1.310     albertel 8466: 	{
                   8467: 	    my $proname=&propath($cdom,$cname);
1.324     raeburn  8468: 	    if (open(CHATLOG,">>$proname/$logfile")) { 
1.310     albertel 8469: 		print CHATLOG ("$time:".&unescape($newchat)."\n");
                   8470: 	    }
                   8471: 	    close(CHATLOG);
1.142     www      8472: 	}
1.311     albertel 8473: 	&untie_user_hash($hashref);
1.86      www      8474:     }
1.84      albertel 8475: }
                   8476: 
                   8477: sub unsub {
                   8478:     my ($fname,$clientip)=@_;
                   8479:     my $result;
1.188     foxr     8480:     my $unsubs = 0;		# Number of successful unsubscribes:
                   8481: 
                   8482: 
                   8483:     # An old way subscriptions were handled was to have a 
                   8484:     # subscription marker file:
                   8485: 
                   8486:     Debug("Attempting unlink of $fname.$clientname");
1.161     foxr     8487:     if (unlink("$fname.$clientname")) {
1.188     foxr     8488: 	$unsubs++;		# Successful unsub via marker file.
                   8489:     } 
                   8490: 
                   8491:     # The more modern way to do it is to have a subscription list
                   8492:     # file:
                   8493: 
1.84      albertel 8494:     if (-e "$fname.subscription") {
1.161     foxr     8495: 	my $found=&addline($fname,$clientname,$clientip,'');
1.188     foxr     8496: 	if ($found) { 
                   8497: 	    $unsubs++;
                   8498: 	}
                   8499:     } 
                   8500: 
                   8501:     #  If either or both of these mechanisms succeeded in unsubscribing a 
                   8502:     #  resource we can return ok:
                   8503: 
                   8504:     if($unsubs) {
                   8505: 	$result = "ok\n";
1.84      albertel 8506:     } else {
1.188     foxr     8507: 	$result = "not_subscribed\n";
1.84      albertel 8508:     }
1.188     foxr     8509: 
1.84      albertel 8510:     return $result;
                   8511: }
                   8512: 
1.101     www      8513: sub currentversion {
                   8514:     my $fname=shift;
                   8515:     my $version=-1;
                   8516:     my $ulsdir='';
                   8517:     if ($fname=~/^(.+)\/[^\/]+$/) {
                   8518:        $ulsdir=$1;
                   8519:     }
1.114     albertel 8520:     my ($fnamere1,$fnamere2);
                   8521:     # remove version if already specified
1.101     www      8522:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114     albertel 8523:     # get the bits that go before and after the version number
                   8524:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
                   8525: 	$fnamere1=$1;
                   8526: 	$fnamere2='.'.$2;
                   8527:     }
1.101     www      8528:     if (-e $fname) { $version=1; }
                   8529:     if (-e $ulsdir) {
1.134     albertel 8530: 	if(-d $ulsdir) {
                   8531: 	    if (opendir(LSDIR,$ulsdir)) {
                   8532: 		my $ulsfn;
                   8533: 		while ($ulsfn=readdir(LSDIR)) {
1.101     www      8534: # see if this is a regular file (ignore links produced earlier)
1.134     albertel 8535: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
                   8536: 		    unless (-l $thisfile) {
1.160     www      8537: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134     albertel 8538: 			    if ($1>$version) { $version=$1; }
                   8539: 			}
                   8540: 		    }
                   8541: 		}
                   8542: 		closedir(LSDIR);
                   8543: 		$version++;
                   8544: 	    }
                   8545: 	}
                   8546:     }
                   8547:     return $version;
1.101     www      8548: }
                   8549: 
                   8550: sub thisversion {
                   8551:     my $fname=shift;
                   8552:     my $version=-1;
                   8553:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
                   8554: 	$version=$1;
                   8555:     }
                   8556:     return $version;
                   8557: }
                   8558: 
1.84      albertel 8559: sub subscribe {
                   8560:     my ($userinput,$clientip)=@_;
                   8561:     my $result;
1.293     albertel 8562:     my ($cmd,$fname)=split(/:/,$userinput,2);
1.84      albertel 8563:     my $ownership=&ishome($fname);
                   8564:     if ($ownership eq 'owner') {
1.101     www      8565: # explitly asking for the current version?
                   8566:         unless (-e $fname) {
                   8567:             my $currentversion=&currentversion($fname);
                   8568: 	    if (&thisversion($fname)==$currentversion) {
                   8569:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
                   8570: 		    my $root=$1;
                   8571:                     my $extension=$2;
                   8572:                     symlink($root.'.'.$extension,
                   8573:                             $root.'.'.$currentversion.'.'.$extension);
1.102     www      8574:                     unless ($extension=~/\.meta$/) {
                   8575:                        symlink($root.'.'.$extension.'.meta',
                   8576:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
                   8577: 		    }
1.101     www      8578:                 }
                   8579:             }
                   8580:         }
1.84      albertel 8581: 	if (-e $fname) {
                   8582: 	    if (-d $fname) {
                   8583: 		$result="directory\n";
                   8584: 	    } else {
1.161     foxr     8585: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134     albertel 8586: 		my $now=time;
1.161     foxr     8587: 		my $found=&addline($fname,$clientname,$clientip,
                   8588: 				   "$clientname:$clientip:$now\n");
1.84      albertel 8589: 		if ($found) { $result="$fname\n"; }
                   8590: 		# if they were subscribed to only meta data, delete that
                   8591:                 # subscription, when you subscribe to a file you also get
                   8592:                 # the metadata
                   8593: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
                   8594: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
1.476     raeburn  8595:                 my $protocol = $Apache::lonnet::protocol{$perlvar{'lonHostID'}};
                   8596:                 $protocol = 'http' if ($protocol ne 'https');
                   8597: 		$fname=$protocol.'://'.&Apache::lonnet::hostname($perlvar{'lonHostID'})."/".$fname;
1.84      albertel 8598: 		$result="$fname\n";
                   8599: 	    }
                   8600: 	} else {
                   8601: 	    $result="not_found\n";
                   8602: 	}
                   8603:     } else {
                   8604: 	$result="rejected\n";
                   8605:     }
                   8606:     return $result;
                   8607: }
1.287     foxr     8608: #  Change the passwd of a unix user.  The caller must have
                   8609: #  first verified that the user is a loncapa user.
                   8610: #
                   8611: # Parameters:
                   8612: #    user      - Unix user name to change.
                   8613: #    pass      - New password for the user.
                   8614: # Returns:
                   8615: #    ok    - if success
                   8616: #    other - Some meaningfule error message string.
                   8617: # NOTE:
                   8618: #    invokes a setuid script to change the passwd.
                   8619: sub change_unix_password {
                   8620:     my ($user, $pass) = @_;
                   8621: 
                   8622:     &Debug("change_unix_password");
                   8623:     my $execdir=$perlvar{'lonDaemons'};
                   8624:     &Debug("Opening lcpasswd pipeline");
                   8625:     my $pf = IO::File->new("|$execdir/lcpasswd > "
                   8626: 			   ."$perlvar{'lonDaemons'}"
                   8627: 			   ."/logs/lcpasswd.log");
                   8628:     print $pf "$user\n$pass\n$pass\n";
                   8629:     close $pf;
                   8630:     my $err = $?;
                   8631:     return ($err < @passwderrors) ? $passwderrors[$err] : 
                   8632: 	"pwchange_falure - unknown error";
                   8633: 
                   8634:     
                   8635: }
                   8636: 
1.91      albertel 8637: 
                   8638: sub make_passwd_file {
1.518     raeburn  8639:     my ($uname,$udom,$umode,$npass,$passfilename,$action)=@_;
1.390     raeburn  8640:     my $result="ok";
1.91      albertel 8641:     if ($umode eq 'krb4' or $umode eq 'krb5') {
                   8642: 	{
                   8643: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8644: 	    if ($pf) {
                   8645: 		print $pf "$umode:$npass\n";
1.518     raeburn  8646:                 &update_passwd_history($uname,$udom,$umode,$action);
1.261     foxr     8647: 	    } else {
                   8648: 		$result = "pass_file_failed_error";
                   8649: 	    }
1.91      albertel 8650: 	}
                   8651:     } elsif ($umode eq 'internal') {
1.518     raeburn  8652:         my $ncpass = &hash_passwd($udom,$npass);
1.91      albertel 8653: 	{
                   8654: 	    &Debug("Creating internal auth");
                   8655: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8656: 	    if($pf) {
1.518     raeburn  8657: 		print $pf "internal:$ncpass\n";
                   8658:                 &update_passwd_history($uname,$udom,$umode,$action); 
1.261     foxr     8659: 	    } else {
                   8660: 		$result = "pass_file_failed_error";
                   8661: 	    }
1.91      albertel 8662: 	}
                   8663:     } elsif ($umode eq 'localauth') {
                   8664: 	{
                   8665: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8666: 	    if($pf) {
                   8667: 		print $pf "localauth:$npass\n";
1.524     raeburn  8668:                 &update_passwd_history($uname,$udom,$umode,$action);
1.261     foxr     8669: 	    } else {
                   8670: 		$result = "pass_file_failed_error";
                   8671: 	    }
1.91      albertel 8672: 	}
                   8673:     } elsif ($umode eq 'unix') {
1.502     raeburn  8674: 	&logthis(">>>Attempt to create unix account blocked -- unix auth not available for new users.");
                   8675: 	$result="no_new_unix_accounts";
1.91      albertel 8676:     } elsif ($umode eq 'none') {
                   8677: 	{
1.223     foxr     8678: 	    my $pf = IO::File->new("> $passfilename");
1.261     foxr     8679: 	    if($pf) {
                   8680: 		print $pf "none:\n";
                   8681: 	    } else {
                   8682: 		$result = "pass_file_failed_error";
                   8683: 	    }
1.91      albertel 8684: 	}
1.543     raeburn  8685:     } elsif ($umode eq 'lti') {
                   8686:         my $pf = IO::File->new(">$passfilename");
                   8687:         if($pf) {
                   8688:             print $pf "lti:\n";
                   8689:             &update_passwd_history($uname,$udom,$umode,$action);
                   8690:         } else {
                   8691:             $result = "pass_file_failed_error";
                   8692:         }
1.91      albertel 8693:     } else {
1.390     raeburn  8694: 	$result="auth_mode_error";
1.91      albertel 8695:     }
                   8696:     return $result;
1.121     albertel 8697: }
                   8698: 
1.265     albertel 8699: sub convert_photo {
                   8700:     my ($start,$dest)=@_;
                   8701:     system("convert $start $dest");
                   8702: }
                   8703: 
1.121     albertel 8704: sub sethost {
                   8705:     my ($remotereq) = @_;
                   8706:     my (undef,$hostid)=split(/:/,$remotereq);
1.322     albertel 8707:     # ignore sethost if we are already correct
                   8708:     if ($hostid eq $currenthostid) {
                   8709: 	return 'ok';
                   8710:     }
                   8711: 
1.121     albertel 8712:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
1.368     albertel 8713:     if (&Apache::lonnet::get_host_ip($perlvar{'lonHostID'}) 
                   8714: 	eq &Apache::lonnet::get_host_ip($hostid)) {
1.200     matthew  8715: 	$currenthostid  =$hostid;
1.369     albertel 8716: 	$currentdomainid=&Apache::lonnet::host_domain($hostid);
1.556     raeburn  8717:         &set_client_info();
1.443     www      8718: #	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
1.121     albertel 8719:     } else {
                   8720: 	&logthis("Requested host id $hostid not an alias of ".
                   8721: 		 $perlvar{'lonHostID'}." refusing connection");
                   8722: 	return 'unable_to_set';
                   8723:     }
                   8724:     return 'ok';
                   8725: }
                   8726: 
                   8727: sub version {
                   8728:     my ($userinput)=@_;
                   8729:     $remoteVERSION=(split(/:/,$userinput))[1];
                   8730:     return "version:$VERSION";
1.127     albertel 8731: }
1.178     foxr     8732: 
1.447     raeburn  8733: sub get_usersession_config {
                   8734:     my ($dom,$name) = @_;
                   8735:     my ($usersessionconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8736:     if (defined($cached)) {
                   8737:         return $usersessionconf;
                   8738:     } else {
                   8739:         my %domconfig = &Apache::lonnet::get_dom('configuration',['usersessions'],$dom);
1.525     raeburn  8740:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'usersessions'},3600);
                   8741:         return $domconfig{'usersessions'};
1.447     raeburn  8742:     }
                   8743:     return;
                   8744: }
1.200     matthew  8745: 
1.534     raeburn  8746: sub get_usersearch_config {
                   8747:     my ($dom,$name) = @_;
                   8748:     my ($usersearchconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8749:     if (defined($cached)) {
                   8750:         return $usersearchconf;
                   8751:     } else {
                   8752:         my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$dom);
                   8753:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'directorysrch'},600);
                   8754:         return $domconfig{'directorysrch'};
                   8755:     }
                   8756:     return;
                   8757: }
                   8758: 
1.525     raeburn  8759: sub get_prohibited {
                   8760:     my ($dom) = @_;
                   8761:     my $name = 'trust';
                   8762:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8763:     unless (defined($cached)) {
                   8764:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$dom);
                   8765:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'trust'},3600);
                   8766:         $trustconfig = $domconfig{'trust'};
                   8767:     }
                   8768:     my %prohibited;
                   8769:     if (ref($trustconfig)) {
                   8770:         foreach my $prefix (keys(%{$trustconfig})) {
                   8771:             if (ref($trustconfig->{$prefix}) eq 'HASH') {
                   8772:                 my $reject;
                   8773:                 if (ref($trustconfig->{$prefix}->{'exc'}) eq 'ARRAY') {
                   8774:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'exc'}})) {
                   8775:                         $reject = 1;
                   8776:                     }
                   8777:                 }
                   8778:                 if (ref($trustconfig->{$prefix}->{'inc'}) eq 'ARRAY') {
                   8779:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'inc'}})) {
                   8780:                         $reject = 0;
                   8781:                     } else {
                   8782:                         $reject = 1;
                   8783:                     }
                   8784:                 }
                   8785:                 if ($reject) {
                   8786:                     $prohibited{$prefix} = 1;
                   8787:                 }
                   8788:             }
                   8789:         }
                   8790:     }
                   8791:     return %prohibited;
                   8792: }
1.450     raeburn  8793: 
1.556     raeburn  8794: sub get_remote_hostable {
                   8795:     my ($dom) = @_;
                   8796:     my $result;
                   8797:     if ($clientintdom) {
                   8798:         $result = 1;
                   8799:         my $remsessconf = &get_usersession_config($dom,'remotesession');
                   8800:         if (ref($remsessconf) eq 'HASH') {
                   8801:             if (ref($remsessconf->{'remote'}) eq 'HASH') {
                   8802:                 if (ref($remsessconf->{'remote'}->{'excludedomain'}) eq 'ARRAY') {
                   8803:                     if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'excludedomain'}})) {
                   8804:                         $result = 0;
                   8805:                     }
                   8806:                 }
                   8807:                 if (ref($remsessconf->{'remote'}->{'includedomain'}) eq 'ARRAY') {
                   8808:                     if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'includedomain'}})) {
                   8809:                         $result = 1;
                   8810:                     } else {
                   8811:                         $result = 0;
                   8812:                     }
                   8813:                 }
                   8814:             }
                   8815:         }
                   8816:     }
                   8817:     return $result;
                   8818: }
                   8819: 
1.471     raeburn  8820: sub distro_and_arch {
                   8821:     return $dist.':'.$arch;
                   8822: }
                   8823: 
1.61      harris41 8824: # ----------------------------------- POD (plain old documentation, CPAN style)
                   8825: 
                   8826: =head1 NAME
                   8827: 
                   8828: lond - "LON Daemon" Server (port "LOND" 5663)
                   8829: 
                   8830: =head1 SYNOPSIS
                   8831: 
1.74      harris41 8832: Usage: B<lond>
                   8833: 
                   8834: Should only be run as user=www.  This is a command-line script which
                   8835: is invoked by B<loncron>.  There is no expectation that a typical user
                   8836: will manually start B<lond> from the command-line.  (In other words,
                   8837: DO NOT START B<lond> YOURSELF.)
1.61      harris41 8838: 
                   8839: =head1 DESCRIPTION
                   8840: 
1.74      harris41 8841: There are two characteristics associated with the running of B<lond>,
                   8842: PROCESS MANAGEMENT (starting, stopping, handling child processes)
                   8843: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
                   8844: subscriptions, etc).  These are described in two large
                   8845: sections below.
                   8846: 
                   8847: B<PROCESS MANAGEMENT>
                   8848: 
1.61      harris41 8849: Preforker - server who forks first. Runs as a daemon. HUPs.
                   8850: Uses IDEA encryption
                   8851: 
1.74      harris41 8852: B<lond> forks off children processes that correspond to the other servers
                   8853: in the network.  Management of these processes can be done at the
                   8854: parent process level or the child process level.
                   8855: 
                   8856: B<logs/lond.log> is the location of log messages.
                   8857: 
                   8858: The process management is now explained in terms of linux shell commands,
                   8859: subroutines internal to this code, and signal assignments:
                   8860: 
                   8861: =over 4
                   8862: 
                   8863: =item *
                   8864: 
                   8865: PID is stored in B<logs/lond.pid>
                   8866: 
                   8867: This is the process id number of the parent B<lond> process.
                   8868: 
                   8869: =item *
                   8870: 
                   8871: SIGTERM and SIGINT
                   8872: 
                   8873: Parent signal assignment:
                   8874:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   8875: 
                   8876: Child signal assignment:
                   8877:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
                   8878: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
                   8879:  to restart a new child.)
                   8880: 
                   8881: Command-line invocations:
                   8882:  B<kill> B<-s> SIGTERM I<PID>
                   8883:  B<kill> B<-s> SIGINT I<PID>
                   8884: 
                   8885: Subroutine B<HUNTSMAN>:
                   8886:  This is only invoked for the B<lond> parent I<PID>.
                   8887: This kills all the children, and then the parent.
                   8888: The B<lonc.pid> file is cleared.
                   8889: 
                   8890: =item *
                   8891: 
                   8892: SIGHUP
                   8893: 
                   8894: Current bug:
                   8895:  This signal can only be processed the first time
                   8896: on the parent process.  Subsequent SIGHUP signals
                   8897: have no effect.
                   8898: 
                   8899: Parent signal assignment:
                   8900:  $SIG{HUP}  = \&HUPSMAN;
                   8901: 
                   8902: Child signal assignment:
                   8903:  none (nothing happens)
                   8904: 
                   8905: Command-line invocations:
                   8906:  B<kill> B<-s> SIGHUP I<PID>
                   8907: 
                   8908: Subroutine B<HUPSMAN>:
                   8909:  This is only invoked for the B<lond> parent I<PID>,
                   8910: This kills all the children, and then the parent.
                   8911: The B<lond.pid> file is cleared.
                   8912: 
                   8913: =item *
                   8914: 
                   8915: SIGUSR1
                   8916: 
                   8917: Parent signal assignment:
                   8918:  $SIG{USR1} = \&USRMAN;
                   8919: 
                   8920: Child signal assignment:
                   8921:  $SIG{USR1}= \&logstatus;
                   8922: 
                   8923: Command-line invocations:
                   8924:  B<kill> B<-s> SIGUSR1 I<PID>
                   8925: 
                   8926: Subroutine B<USRMAN>:
                   8927:  When invoked for the B<lond> parent I<PID>,
                   8928: SIGUSR1 is sent to all the children, and the status of
                   8929: each connection is logged.
1.144     foxr     8930: 
                   8931: =item *
                   8932: 
                   8933: SIGUSR2
                   8934: 
                   8935: Parent Signal assignment:
                   8936:     $SIG{USR2} = \&UpdateHosts
                   8937: 
                   8938: Child signal assignment:
                   8939:     NONE
                   8940: 
1.74      harris41 8941: 
                   8942: =item *
                   8943: 
                   8944: SIGCHLD
                   8945: 
                   8946: Parent signal assignment:
                   8947:  $SIG{CHLD} = \&REAPER;
                   8948: 
                   8949: Child signal assignment:
                   8950:  none
                   8951: 
                   8952: Command-line invocations:
                   8953:  B<kill> B<-s> SIGCHLD I<PID>
                   8954: 
                   8955: Subroutine B<REAPER>:
                   8956:  This is only invoked for the B<lond> parent I<PID>.
                   8957: Information pertaining to the child is removed.
                   8958: The socket port is cleaned up.
                   8959: 
                   8960: =back
                   8961: 
                   8962: B<SERVER-SIDE ACTIVITIES>
                   8963: 
                   8964: Server-side information can be accepted in an encrypted or non-encrypted
                   8965: method.
                   8966: 
                   8967: =over 4
                   8968: 
                   8969: =item ping
                   8970: 
                   8971: Query a client in the hosts.tab table; "Are you there?"
                   8972: 
                   8973: =item pong
                   8974: 
                   8975: Respond to a ping query.
                   8976: 
                   8977: =item ekey
                   8978: 
                   8979: Read in encrypted key, make cipher.  Respond with a buildkey.
                   8980: 
                   8981: =item load
                   8982: 
                   8983: Respond with CPU load based on a computation upon /proc/loadavg.
                   8984: 
                   8985: =item currentauth
                   8986: 
                   8987: Reply with current authentication information (only over an
                   8988: encrypted channel).
                   8989: 
                   8990: =item auth
                   8991: 
                   8992: Only over an encrypted channel, reply as to whether a user's
                   8993: authentication information can be validated.
                   8994: 
                   8995: =item passwd
                   8996: 
                   8997: Allow for a password to be set.
                   8998: 
                   8999: =item makeuser
                   9000: 
                   9001: Make a user.
                   9002: 
1.517     raeburn  9003: =item changeuserauth
1.74      harris41 9004: 
                   9005: Allow for authentication mechanism and password to be changed.
                   9006: 
                   9007: =item home
1.61      harris41 9008: 
1.74      harris41 9009: Respond to a question "are you the home for a given user?"
                   9010: 
                   9011: =item update
                   9012: 
                   9013: Update contents of a subscribed resource.
                   9014: 
                   9015: =item unsubscribe
                   9016: 
                   9017: The server is unsubscribing from a resource.
                   9018: 
                   9019: =item subscribe
                   9020: 
                   9021: The server is subscribing to a resource.
                   9022: 
                   9023: =item log
                   9024: 
                   9025: Place in B<logs/lond.log>
                   9026: 
                   9027: =item put
                   9028: 
                   9029: stores hash in namespace
                   9030: 
1.496     raeburn  9031: =item rolesput
1.74      harris41 9032: 
                   9033: put a role into a user's environment
                   9034: 
                   9035: =item get
                   9036: 
                   9037: returns hash with keys from array
                   9038: reference filled in from namespace
                   9039: 
                   9040: =item eget
                   9041: 
                   9042: returns hash with keys from array
                   9043: reference filled in from namesp (encrypts the return communication)
                   9044: 
                   9045: =item rolesget
                   9046: 
                   9047: get a role from a user's environment
                   9048: 
                   9049: =item del
                   9050: 
                   9051: deletes keys out of array from namespace
                   9052: 
                   9053: =item keys
                   9054: 
                   9055: returns namespace keys
                   9056: 
                   9057: =item dump
                   9058: 
                   9059: dumps the complete (or key matching regexp) namespace into a hash
                   9060: 
                   9061: =item store
                   9062: 
                   9063: stores hash permanently
                   9064: for this url; hashref needs to be given and should be a \%hashname; the
                   9065: remaining args aren't required and if they aren't passed or are '' they will
                   9066: be derived from the ENV
                   9067: 
                   9068: =item restore
                   9069: 
                   9070: returns a hash for a given url
                   9071: 
                   9072: =item querysend
                   9073: 
                   9074: Tells client about the lonsql process that has been launched in response
                   9075: to a sent query.
                   9076: 
                   9077: =item queryreply
                   9078: 
                   9079: Accept information from lonsql and make appropriate storage in temporary
                   9080: file space.
                   9081: 
                   9082: =item idput
                   9083: 
                   9084: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
                   9085: for each student, defined perhaps by the institutional Registrar.)
                   9086: 
                   9087: =item idget
                   9088: 
                   9089: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
                   9090: for each student, defined perhaps by the institutional Registrar.)
                   9091: 
1.517     raeburn  9092: =item iddel
                   9093: 
                   9094: Deletes one or more ids in a domain's id database.
                   9095: 
1.74      harris41 9096: =item tmpput
                   9097: 
                   9098: Accept and store information in temporary space.
                   9099: 
                   9100: =item tmpget
                   9101: 
                   9102: Send along temporarily stored information.
                   9103: 
                   9104: =item ls
                   9105: 
                   9106: List part of a user's directory.
                   9107: 
1.135     foxr     9108: =item pushtable
                   9109: 
                   9110: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
                   9111: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
                   9112: must be restored manually in case of a problem with the new table file.
                   9113: pushtable requires that the request be encrypted and validated via
                   9114: ValidateManager.  The form of the command is:
                   9115: enc:pushtable tablename <tablecontents> \n
                   9116: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
                   9117: cleartext newline.
                   9118: 
1.74      harris41 9119: =item Hanging up (exit or init)
                   9120: 
                   9121: What to do when a client tells the server that they (the client)
                   9122: are leaving the network.
                   9123: 
                   9124: =item unknown command
                   9125: 
                   9126: If B<lond> is sent an unknown command (not in the list above),
                   9127: it replys to the client "unknown_cmd".
1.135     foxr     9128: 
1.74      harris41 9129: 
                   9130: =item UNKNOWN CLIENT
                   9131: 
                   9132: If the anti-spoofing algorithm cannot verify the client,
                   9133: the client is rejected (with a "refused" message sent
                   9134: to the client, and the connection is closed.
                   9135: 
                   9136: =back
1.61      harris41 9137: 
                   9138: =head1 PREREQUISITES
                   9139: 
                   9140: IO::Socket
                   9141: IO::File
                   9142: Apache::File
                   9143: POSIX
                   9144: Crypt::IDEA
                   9145: GDBM_File
                   9146: Authen::Krb4
1.91      albertel 9147: Authen::Krb5
1.61      harris41 9148: 
                   9149: =head1 COREQUISITES
                   9150: 
1.490     droeschl 9151: none
                   9152: 
1.61      harris41 9153: =head1 OSNAMES
                   9154: 
                   9155: linux
                   9156: 
                   9157: =head1 SCRIPT CATEGORIES
                   9158: 
                   9159: Server/Process
                   9160: 
                   9161: =cut
1.409     foxr     9162: 
                   9163: 
                   9164: =pod
                   9165: 
                   9166: =head1 LOG MESSAGES
                   9167: 
                   9168: The messages below can be emitted in the lond log.  This log is located
                   9169: in ~httpd/perl/logs/lond.log  Many log messages have HTML encapsulation
                   9170: to provide coloring if examined from inside a web page. Some do not.
                   9171: Where color is used, the colors are; Red for sometihhng to get excited
                   9172: about and to follow up on. Yellow for something to keep an eye on to
                   9173: be sure it does not get worse, Green,and Blue for informational items.
                   9174: 
                   9175: In the discussions below, sometimes reference is made to ~httpd
                   9176: when describing file locations.  There isn't really an httpd 
                   9177: user, however there is an httpd directory that gets installed in the
                   9178: place that user home directories go.  On linux, this is usually
                   9179: (always?) /home/httpd.
                   9180: 
                   9181: 
                   9182: Some messages are colorless.  These are usually (not always)
                   9183: Green/Blue color level messages.
                   9184: 
                   9185: =over 2
                   9186: 
                   9187: =item (Red)  LocalConnection rejecting non local: <ip> ne 127.0.0.1
                   9188: 
                   9189: A local connection negotiation was attempted by
                   9190: a host whose IP address was not 127.0.0.1.
                   9191: The socket is closed and the child will exit.
                   9192: lond has three ways to establish an encyrption
                   9193: key with a client:
                   9194: 
                   9195: =over 2
                   9196: 
                   9197: =item local 
                   9198: 
                   9199: The key is written and read from a file.
                   9200: This is only valid for connections from localhost.
                   9201: 
                   9202: =item insecure 
                   9203: 
                   9204: The key is generated by the server and
                   9205: transmitted to the client.
                   9206: 
                   9207: =item  ssl (secure)
                   9208: 
                   9209: An ssl connection is negotiated with the client,
                   9210: the key is generated by the server and sent to the 
                   9211: client across this ssl connection before the
                   9212: ssl connectionis terminated and clear text
                   9213: transmission resumes.
                   9214: 
                   9215: =back
                   9216: 
                   9217: =item (Red) LocalConnection: caller is insane! init = <init> and type = <type>
                   9218: 
                   9219: The client is local but has not sent an initialization
                   9220: string that is the literal "init:local"  The connection
                   9221: is closed and the child exits.
                   9222: 
                   9223: =item Red CRITICAL Can't get key file <error>        
                   9224: 
                   9225: SSL key negotiation is being attempted but the call to
1.549     raeburn  9226: lonssl::KeyFile failed.  This usually means that the
1.409     foxr     9227: configuration file is not correctly defining or protecting
                   9228: the directories/files lonCertificateDirectory or
                   9229: lonnetPrivateKey
                   9230: <error> is a string that describes the reason that
                   9231: the key file could not be located.
                   9232: 
                   9233: =item (Red) CRITICAL  Can't get certificates <error>  
                   9234: 
                   9235: SSL key negotiation failed because we were not able to retrives our certificate
                   9236: or the CA's certificate in the call to lonssl::CertificateFile
                   9237: <error> is the textual reason this failed.  Usual reasons:
                   9238: 
                   9239: =over 2
1.490     droeschl 9240: 
1.409     foxr     9241: =item Apache config file for loncapa  incorrect:
1.490     droeschl 9242: 
1.409     foxr     9243: one of the variables 
                   9244: lonCertificateDirectory, lonnetCertificateAuthority, or lonnetCertificate
                   9245: undefined or incorrect
                   9246: 
                   9247: =item Permission error:
                   9248: 
                   9249: The directory pointed to by lonCertificateDirectory is not readable by lond
                   9250: 
                   9251: =item Permission error:
                   9252: 
                   9253: Files in the directory pointed to by lonCertificateDirectory are not readable by lond.
                   9254: 
                   9255: =item Installation error:                         
                   9256: 
                   9257: Either the certificate authority file or the certificate have not
                   9258: been installed in lonCertificateDirectory.
                   9259: 
                   9260: =item (Red) CRITICAL SSL Socket promotion failed:  <err> 
                   9261: 
                   9262: The promotion of the connection from plaintext to SSL failed
                   9263: <err> is the reason for the failure.  There are two
                   9264: system calls involved in the promotion (one of which failed), 
                   9265: a dup to produce
                   9266: a second fd on the raw socket over which the encrypted data
                   9267: will flow and IO::SOcket::SSL->new_from_fd which creates
                   9268: the SSL connection on the duped fd.
                   9269: 
                   9270: =item (Blue)   WARNING client did not respond to challenge 
                   9271: 
                   9272: This occurs on an insecure (non SSL) connection negotiation request.
                   9273: lond generates some number from the time, the PID and sends it to
                   9274: the client.  The client must respond by echoing this information back.
                   9275: If the client does not do so, that's a violation of the challenge
                   9276: protocols and the connection will be failed.
                   9277: 
                   9278: =item (Red) No manager table. Nobody can manage!!    
                   9279: 
                   9280: lond has the concept of privileged hosts that
                   9281: can perform remote management function such
                   9282: as update the hosts.tab.   The manager hosts
                   9283: are described in the 
                   9284: ~httpd/lonTabs/managers.tab file.
                   9285: this message is logged if this file is missing.
                   9286: 
                   9287: 
                   9288: =item (Green) Registering manager <dnsname> as <cluster_name> with <ipaddress>
                   9289: 
                   9290: Reports the successful parse and registration
                   9291: of a specific manager. 
                   9292: 
                   9293: =item Green existing host <clustername:dnsname>  
                   9294: 
                   9295: The manager host is already defined in the hosts.tab
                   9296: the information in that table, rather than the info in the
                   9297: manager table will be used to determine the manager's ip.
                   9298: 
                   9299: =item (Red) Unable to craete <filename>                 
                   9300: 
                   9301: lond has been asked to create new versions of an administrative
                   9302: file (by a manager).  When this is done, the new file is created
                   9303: in a temp file and then renamed into place so that there are always
                   9304: usable administrative files, even if the update fails.  This failure
                   9305: message means that the temp file could not be created.
                   9306: The update is abandoned, and the old file is available for use.
                   9307: 
                   9308: =item (Green) CopyFile from <oldname> to <newname> failed
                   9309: 
                   9310: In an update of administrative files, the copy of the existing file to a
                   9311: backup file failed.  The installation of the new file may still succeed,
                   9312: but there will not be a back up file to rever to (this should probably
                   9313: be yellow).
                   9314: 
                   9315: =item (Green) Pushfile: backed up <oldname> to <newname>
                   9316: 
                   9317: See above, the backup of the old administrative file succeeded.
                   9318: 
                   9319: =item (Red)  Pushfile: Unable to install <filename> <reason>
                   9320: 
                   9321: The new administrative file could not be installed.  In this case,
                   9322: the old administrative file is still in use.
                   9323: 
                   9324: =item (Green) Installed new < filename>.                      
                   9325: 
                   9326: The new administrative file was successfullly installed.                                               
                   9327: 
                   9328: =item (Red) Reinitializing lond pid=<pid>                    
                   9329: 
                   9330: The lonc child process <pid> will be sent a USR2 
                   9331: signal.
                   9332: 
                   9333: =item (Red) Reinitializing self                                    
                   9334: 
                   9335: We've been asked to re-read our administrative files,and
                   9336: are doing so.
                   9337: 
                   9338: =item (Yellow) error:Invalid process identifier <ident>  
                   9339: 
                   9340: A reinit command was received, but the target part of the 
                   9341: command was not valid.  It must be either
                   9342: 'lond' or 'lonc' but was <ident>
                   9343: 
                   9344: =item (Green) isValideditCommand checking: Command = <command> Key = <key> newline = <newline>
                   9345: 
                   9346: Checking to see if lond has been handed a valid edit
                   9347: command.  It is possible the edit command is not valid
                   9348: in that case there are no log messages to indicate that.
                   9349: 
                   9350: =item Result of password change for  <username> pwchange_success
                   9351: 
                   9352: The password for <username> was
                   9353: successfully changed.
                   9354: 
                   9355: =item Unable to open <user> passwd to change password
                   9356: 
                   9357: Could not rewrite the 
                   9358: internal password file for a user
                   9359: 
                   9360: =item Result of password change for <user> : <result>
1.490     droeschl 9361: 
1.409     foxr     9362: A unix password change for <user> was attempted 
                   9363: and the pipe returned <result>  
                   9364: 
                   9365: =item LWP GET: <message> for <fname> (<remoteurl>)
                   9366: 
                   9367: The lightweight process fetch for a resource failed
                   9368: with <message> the local filename that should
                   9369: have existed/been created was  <fname> the
                   9370: corresponding URI: <remoteurl>  This is emitted in several
                   9371: places.
                   9372: 
                   9373: =item Unable to move <transname> to <destname>     
                   9374: 
                   9375: From fetch_user_file_handler - the user file was replicated but could not
                   9376: be mv'd to its final location.
                   9377: 
                   9378: =item Looking for <domain> <username>              
                   9379: 
                   9380: From user_has_session_handler - This should be a Debug call instead
                   9381: it indicates lond is about to check whether the specified user has a 
                   9382: session active on the specified domain on the local host.
                   9383: 
                   9384: =item Client <ip> (<name>) hanging up: <input>     
                   9385: 
                   9386: lond has been asked to exit by its client.  The <ip> and <name> identify the
                   9387: client systemand <input> is the full exit command sent to the server.
                   9388: 
                   9389: =item Red CRITICAL: ABNORMAL EXIT. child <pid> for server <hostname> died through a crass with this error->[<message>].
1.490     droeschl 9390: 
1.409     foxr     9391: A lond child terminated.  NOte that this termination can also occur when the
                   9392: child receives the QUIT or DIE signals.  <pid> is the process id of the child,
                   9393: <hostname> the host lond is working for, and <message> the reason the child died
                   9394: to the best of our ability to get it (I would guess that any numeric value
                   9395: represents and errno value).  This is immediately followed by
                   9396: 
                   9397: =item  Famous last words: Catching exception - <log> 
                   9398: 
                   9399: Where log is some recent information about the state of the child.
                   9400: 
                   9401: =item Red CRITICAL: TIME OUT <pid>                     
                   9402: 
                   9403: Some timeout occured for server <pid>.  THis is normally a timeout on an LWP
                   9404: doing an HTTP::GET.
                   9405: 
                   9406: =item child <pid> died                              
                   9407: 
                   9408: The reaper caught a SIGCHILD for the lond child process <pid>
                   9409: This should be modified to also display the IP of the dying child
                   9410: $children{$pid}
                   9411: 
                   9412: =item Unknown child 0 died                           
                   9413: A child died but the wait for it returned a pid of zero which really should not
                   9414: ever happen. 
                   9415: 
                   9416: =item Child <which> - <pid> looks like we missed it's death 
                   9417: 
                   9418: When a sigchild is received, the reaper process checks all children to see if they are
                   9419: alive.  If children are dying quite quickly, the lack of signal queuing can mean
                   9420: that a signal hearalds the death of more than one child.  If so this message indicates
                   9421: which other one died. <which> is the ip of a dead child
                   9422: 
                   9423: =item Free socket: <shutdownretval>                
                   9424: 
                   9425: The HUNTSMAN sub was called due to a SIGINT in a child process.  The socket is being shutdown.
                   9426: for whatever reason, <shutdownretval> is printed but in fact shutdown() is not documented
                   9427: to return anything. This is followed by: 
                   9428: 
                   9429: =item Red CRITICAL: Shutting down                       
                   9430: 
                   9431: Just prior to exit.
                   9432: 
                   9433: =item Free socket: <shutdownretval>                 
                   9434: 
                   9435: The HUPSMAN sub was called due to a SIGHUP.  all children get killsed, and lond execs itself.
                   9436: This is followed by:
                   9437: 
                   9438: =item (Red) CRITICAL: Restarting                         
                   9439: 
                   9440: lond is about to exec itself to restart.
                   9441: 
                   9442: =item (Blue) Updating connections                        
                   9443: 
                   9444: (In response to a USR2).  All the children (except the one for localhost)
                   9445: are about to be killed, the hosts tab reread, and Apache reloaded via apachereload.
                   9446: 
                   9447: =item (Blue) UpdateHosts killing child <pid> for ip <ip>   
                   9448: 
                   9449: Due to USR2 as above.
                   9450: 
                   9451: =item (Green) keeping child for ip <ip> (pid = <pid>)    
                   9452: 
                   9453: In response to USR2 as above, the child indicated is not being restarted because
                   9454: it's assumed that we'll always need a child for the localhost.
                   9455: 
                   9456: 
                   9457: =item Going to check on the children                
                   9458: 
                   9459: Parent is about to check on the health of the child processes.
                   9460: Note that this is in response to a USR1 sent to the parent lond.
                   9461: there may be one or more of the next two messages:
                   9462: 
                   9463: =item <pid> is dead                                 
                   9464: 
                   9465: A child that we have in our child hash as alive has evidently died.
                   9466: 
                   9467: =item  Child <pid> did not respond                   
                   9468: 
                   9469: In the health check the child <pid> did not update/produce a pid_.txt
                   9470: file when sent it's USR1 signal.  That process is killed with a 9 signal, as it's
                   9471: assumed to be hung in some un-fixable way.
                   9472: 
                   9473: =item Finished checking children                   
1.490     droeschl 9474: 
1.409     foxr     9475: Master processs's USR1 processing is cojmplete.
                   9476: 
                   9477: =item (Red) CRITICAL: ------- Starting ------            
                   9478: 
                   9479: (There are more '-'s on either side).  Lond has forked itself off to 
                   9480: form a new session and is about to start actual initialization.
                   9481: 
                   9482: =item (Green) Attempting to start child (<client>)       
                   9483: 
                   9484: Started a new child process for <client>.  Client is IO::Socket object
                   9485: connected to the child.  This was as a result of a TCP/IP connection from a client.
                   9486: 
                   9487: =item Unable to determine who caller was, getpeername returned nothing
1.490     droeschl 9488: 
1.409     foxr     9489: In child process initialization.  either getpeername returned undef or
                   9490: a zero sized object was returned.  Processing continues, but in my opinion,
                   9491: this should be cause for the child to exit.
                   9492: 
                   9493: =item Unable to determine clientip                  
                   9494: 
                   9495: In child process initialization.  The peer address from getpeername was not defined.
                   9496: The client address is stored as "Unavailable" and processing continues.
                   9497: 
                   9498: =item (Yellow) INFO: Connection <ip> <name> connection type = <type>
1.490     droeschl 9499: 
1.409     foxr     9500: In child initialization.  A good connectionw as received from <ip>.
                   9501: 
                   9502: =over 2
                   9503: 
                   9504: =item <name> 
                   9505: 
                   9506: is the name of the client from hosts.tab.
                   9507: 
                   9508: =item <type> 
                   9509: 
                   9510: Is the connection type which is either 
                   9511: 
                   9512: =over 2
                   9513: 
                   9514: =item manager 
                   9515: 
                   9516: The connection is from a manager node, not in hosts.tab
                   9517: 
                   9518: =item client  
                   9519: 
                   9520: the connection is from a non-manager in the hosts.tab
                   9521: 
                   9522: =item both
                   9523: 
                   9524: The connection is from a manager in the hosts.tab.
                   9525: 
                   9526: =back
                   9527: 
                   9528: =back
                   9529: 
                   9530: =item (Blue) Certificates not installed -- trying insecure auth
                   9531: 
                   9532: One of the certificate file, key file or
                   9533: certificate authority file could not be found for a client attempting
                   9534: SSL connection intiation.  COnnection will be attemptied in in-secure mode.
                   9535: (this would be a system with an up to date lond that has not gotten a 
                   9536: certificate from us).
                   9537: 
                   9538: =item (Green)  Successful local authentication            
                   9539: 
                   9540: A local connection successfully negotiated the encryption key. 
                   9541: In this case the IDEA key is in a file (that is hopefully well protected).
                   9542: 
                   9543: =item (Green) Successful ssl authentication with <client>  
                   9544: 
                   9545: The client (<client> is the peer's name in hosts.tab), has successfully
                   9546: negotiated an SSL connection with this child process.
                   9547: 
                   9548: =item (Green) Successful insecure authentication with <client>
1.490     droeschl 9549: 
1.409     foxr     9550: 
                   9551: The client has successfully negotiated an  insecure connection withthe child process.
                   9552: 
                   9553: =item (Yellow) Attempted insecure connection disallowed    
                   9554: 
                   9555: The client attempted and failed to successfully negotiate a successful insecure
                   9556: connection.  This can happen either because the variable londAllowInsecure is false
                   9557: or undefined, or becuse the child did not successfully echo back the challenge
                   9558: string.
                   9559: 
                   9560: 
                   9561: =back
                   9562: 
1.441     raeburn  9563: =back
                   9564: 
1.409     foxr     9565: 
                   9566: =cut

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