Annotation of loncom/lond, revision 1.565

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

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