Annotation of loncom/lond, revision 1.575

1.1       albertel    1: #!/usr/bin/perl
                      2: # The LearningOnline Network
                      3: # lond "LON Daemon" Server (port "LOND" 5663)
1.60      www         4: #
1.575   ! raeburn     5: # $Id: lond,v 1.574 2022/02/25 09:38:47 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.575   ! raeburn    68: my $VERSION='$Revision: 1.574 $'; #' 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},
1.566     raeburn   216:                autovalidateinstcrosslist => {remote => 1, enroll => 1},
1.567     raeburn   217:                autoinstsecreformat => {remote => 1, enroll => 1},
1.525     raeburn   218:                changeuserauth => {remote => 1, domroles => 1},
                    219:                chatretr => {remote => 1, enroll => 1},
                    220:                chatsend => {remote => 1, enroll => 1},
                    221:                courseiddump => {remote => 1, domroles => 1, enroll => 1},
                    222:                courseidput => {remote => 1, domroles => 1, enroll => 1},
                    223:                courseidputhash => {remote => 1, domroles => 1, enroll => 1},
                    224:                courselastaccess => {remote => 1, domroles => 1, enroll => 1},
1.561     raeburn   225:                coursesessions => {institutiononly => 1},
1.525     raeburn   226:                currentauth => {remote => 1, domroles => 1, enroll => 1},
                    227:                currentdump => {remote => 1, enroll => 1},
                    228:                currentversion => {remote=> 1, content => 1},
                    229:                dcmaildump => {remote => 1, domroles => 1},
                    230:                dcmailput => {remote => 1, domroles => 1},
                    231:                del => {remote => 1, domroles => 1, enroll => 1, content => 1},
1.551     raeburn   232:                delbalcookie => {institutiononly => 1},
1.560     raeburn   233:                delusersession => {institutiononly => 1},
1.525     raeburn   234:                deldom => {remote => 1, domroles => 1}, # not currently used
                    235:                devalidatecache => {institutiononly => 1},
                    236:                domroleput => {remote => 1, enroll => 1},
                    237:                domrolesdump => {remote => 1, catalog => 1},
                    238:                du => {remote => 1, enroll => 1},
                    239:                du2 => {remote => 1, enroll => 1},
                    240:                dump => {remote => 1, enroll => 1, domroles => 1},
                    241:                edit => {institutiononly => 1},  #not used currently
1.568     raeburn   242:                edump => {remote => 1, enroll => 1, domroles => 1},
1.525     raeburn   243:                eget => {remote => 1, domroles => 1, enroll => 1}, #not used currently
1.536     raeburn   244:                egetdom => {remote => 1, domroles => 1, enroll => 1, },
1.553     raeburn   245:                ekey => {anywhere => 1},
1.525     raeburn   246:                exit => {anywhere => 1},
                    247:                fetchuserfile => {remote => 1, enroll => 1},
                    248:                get => {remote => 1, domroles => 1, enroll => 1},
                    249:                getdom => {anywhere => 1},
                    250:                home => {anywhere => 1},
                    251:                iddel => {remote => 1, enroll => 1},
                    252:                idget => {remote => 1, enroll => 1},
                    253:                idput => {remote => 1, domroles => 1, enroll => 1},
                    254:                inc => {remote => 1, enroll => 1},
                    255:                init => {anywhere => 1},
                    256:                inst_usertypes => {remote => 1, domroles => 1, enroll => 1},
                    257:                instemailrules => {remote => 1, domroles => 1},
                    258:                instidrulecheck => {remote => 1, domroles => 1,},
                    259:                instidrules => {remote => 1, domroles => 1,},
                    260:                instrulecheck => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1},
                    261:                instselfcreatecheck => {institutiononly => 1},
1.575   ! raeburn   262:                instunamemapcheck => {remote => 1,},  
1.525     raeburn   263:                instuserrules => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1},
                    264:                keys => {remote => 1,},
                    265:                load => {anywhere => 1},
                    266:                log => {anywhere => 1},
                    267:                ls => {remote => 1, enroll => 1, content => 1,},
                    268:                ls2 => {remote => 1, enroll => 1, content => 1,},
                    269:                ls3 => {remote => 1, enroll => 1, content => 1,},
1.572     raeburn   270:                lti => {institutiononly => 1},
1.525     raeburn   271:                makeuser => {remote => 1, enroll => 1, domroles => 1,},
                    272:                mkdiruserfile => {remote => 1, enroll => 1,},
                    273:                newput => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1,},
                    274:                passwd => {remote => 1},
                    275:                ping => {anywhere => 1},
                    276:                pong => {anywhere => 1},
                    277:                pushfile => {manageronly => 1},
                    278:                put => {remote => 1, enroll => 1, domroles => 1, msg => 1, content => 1, shared => 1},
                    279:                putdom => {remote => 1, domroles => 1,},
                    280:                putstore => {remote => 1, enroll => 1},
                    281:                queryreply => {anywhere => 1},
                    282:                querysend => {anywhere => 1},
1.535     raeburn   283:                querysend_activitylog => {remote => 1},
                    284:                querysend_allusers => {remote => 1, domroles => 1},
                    285:                querysend_courselog => {remote => 1},
                    286:                querysend_fetchenrollment => {remote => 1},
                    287:                querysend_getinstuser => {remote => 1},
                    288:                querysend_getmultinstusers => {remote => 1},
                    289:                querysend_instdirsearch => {remote => 1, domroles => 1, coaurem => 1},
                    290:                querysend_institutionalphotos => {remote => 1},
                    291:                querysend_portfolio_metadata => {remote => 1, content => 1},
                    292:                querysend_userlog => {remote => 1, domroles => 1},
                    293:                querysend_usersearch => {remote => 1, enroll => 1, coaurem => 1},
1.525     raeburn   294:                quit => {anywhere => 1},
                    295:                readlonnetglobal => {institutiononly => 1},
                    296:                reinit => {manageronly => 1}, #not used currently
                    297:                removeuserfile => {remote => 1, enroll => 1},
                    298:                renameuserfile => {remote => 1,},
                    299:                restore => {remote => 1, enroll => 1, reqcrs => 1,},
                    300:                rolesdel => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
                    301:                rolesput => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
1.527     raeburn   302:                servercerts => {institutiononly => 1},
1.528     raeburn   303:                serverdistarch => {anywhere => 1},
1.525     raeburn   304:                serverhomeID => {anywhere => 1},
                    305:                serverloncaparev => {anywhere => 1},
                    306:                servertimezone => {remote => 1, enroll => 1},
                    307:                setannounce => {remote => 1, domroles => 1},
                    308:                sethost => {anywhere => 1},
                    309:                store => {remote => 1, enroll => 1, reqcrs => 1,},
                    310:                studentphoto => {remote => 1, enroll => 1},
                    311:                sub => {content => 1,},
1.552     raeburn   312:                tmpdel => {institutiononly => 1},
                    313:                tmpget => {institutiononly => 1},
                    314:                tmpput => {remote => 1, othcoau => 1},
1.525     raeburn   315:                tokenauthuserfile => {anywhere => 1},
1.575   ! raeburn   316:                unamemaprules => {remote => 1,},
1.525     raeburn   317:                unsub => {content => 1,},
                    318:                update => {shared => 1},
1.564     raeburn   319:                updatebalcookie => {institutiononly => 1},
1.525     raeburn   320:                updateclickers => {remote => 1},
                    321:                userhassession => {anywhere => 1},
                    322:                userload => {anywhere => 1},
                    323:                version => {anywhere => 1}, #not used
                    324:             );
                    325: 
                    326: #
1.207     foxr      327: #   Statistics that are maintained and dislayed in the status line.
                    328: #
1.212     foxr      329: my $Transactions = 0;		# Number of attempted transactions.
                    330: my $Failures     = 0;		# Number of transcations failed.
1.207     foxr      331: 
                    332: #   ResetStatistics: 
                    333: #      Resets the statistics counters:
                    334: #
                    335: sub ResetStatistics {
                    336:     $Transactions = 0;
                    337:     $Failures     = 0;
                    338: }
                    339: 
1.200     matthew   340: #------------------------------------------------------------------------
                    341: #
                    342: #   LocalConnection
                    343: #     Completes the formation of a locally authenticated connection.
                    344: #     This function will ensure that the 'remote' client is really the
                    345: #     local host.  If not, the connection is closed, and the function fails.
                    346: #     If so, initcmd is parsed for the name of a file containing the
                    347: #     IDEA session key.  The fie is opened, read, deleted and the session
                    348: #     key returned to the caller.
                    349: #
                    350: # Parameters:
                    351: #   $Socket      - Socket open on client.
                    352: #   $initcmd     - The full text of the init command.
                    353: #
                    354: # Returns:
                    355: #     IDEA session key on success.
                    356: #     undef on failure.
                    357: #
                    358: sub LocalConnection {
                    359:     my ($Socket, $initcmd) = @_;
1.373     albertel  360:     Debug("Attempting local connection: $initcmd client: $clientip");
1.277     albertel  361:     if($clientip ne "127.0.0.1") {
1.200     matthew   362: 	&logthis('<font color="red"> LocalConnection rejecting non local: '
1.373     albertel  363: 		 ."$clientip ne 127.0.0.1 </font>");
1.200     matthew   364: 	close $Socket;
                    365: 	return undef;
1.224     foxr      366:     }  else {
1.200     matthew   367: 	chomp($initcmd);	# Get rid of \n in filename.
                    368: 	my ($init, $type, $name) = split(/:/, $initcmd);
                    369: 	Debug(" Init command: $init $type $name ");
                    370: 
                    371: 	# Require that $init = init, and $type = local:  Otherwise
                    372: 	# the caller is insane:
                    373: 
                    374: 	if(($init ne "init") && ($type ne "local")) {
                    375: 	    &logthis('<font color = "red"> LocalConnection: caller is insane! '
                    376: 		     ."init = $init, and type = $type </font>");
                    377: 	    close($Socket);;
                    378: 	    return undef;
                    379: 		
                    380: 	}
                    381: 	#  Now get the key filename:
                    382: 
                    383: 	my $IDEAKey = lonlocal::ReadKeyFile($name);
                    384: 	return $IDEAKey;
                    385:     }
                    386: }
                    387: #------------------------------------------------------------------------------
                    388: #
                    389: #  SSLConnection
                    390: #   Completes the formation of an ssh authenticated connection. The
                    391: #   socket is promoted to an ssl socket.  If this promotion and the associated
                    392: #   certificate exchange are successful, the IDEA key is generated and sent
                    393: #   to the remote peer via the SSL tunnel. The IDEA key is also returned to
                    394: #   the caller after the SSL tunnel is torn down.
                    395: #
                    396: # Parameters:
                    397: #   Name              Type             Purpose
                    398: #   $Socket          IO::Socket::INET  Plaintext socket.
                    399: #
                    400: # Returns:
                    401: #    IDEA key on success.
                    402: #    undef on failure.
                    403: #
                    404: sub SSLConnection {
                    405:     my $Socket   = shift;
                    406: 
                    407:     Debug("SSLConnection: ");
                    408:     my $KeyFile         = lonssl::KeyFile();
                    409:     if(!$KeyFile) {
                    410: 	my $err = lonssl::LastError();
                    411: 	&logthis("<font color=\"red\"> CRITICAL"
                    412: 		 ."Can't get key file $err </font>");
                    413: 	return undef;
                    414:     }
                    415:     my ($CACertificate,
                    416: 	$Certificate) = lonssl::CertificateFile();
                    417: 
                    418: 
                    419:     # If any of the key, certificate or certificate authority 
                    420:     # certificate filenames are not defined, this can't work.
                    421: 
                    422:     if((!$Certificate) || (!$CACertificate)) {
                    423: 	my $err = lonssl::LastError();
                    424: 	&logthis("<font color=\"red\"> CRITICAL"
                    425: 		 ."Can't get certificates: $err </font>");
                    426: 
                    427: 	return undef;
                    428:     }
                    429:     Debug("Key: $KeyFile CA: $CACertificate Cert: $Certificate");
                    430: 
                    431:     # Indicate to our peer that we can procede with
                    432:     # a transition to ssl authentication:
                    433: 
                    434:     print $Socket "ok:ssl\n";
                    435: 
                    436:     Debug("Approving promotion -> ssl");
                    437:     #  And do so:
                    438: 
1.545     raeburn   439:     my $CRLFile;
                    440:     unless ($crlchecked{$clientname}) {
                    441:         $CRLFile = lonssl::CRLFile();
                    442:         $crlchecked{$clientname} = 1;
                    443:     }
                    444: 
1.200     matthew   445:     my $SSLSocket = lonssl::PromoteServerSocket($Socket,
                    446: 						$CACertificate,
                    447: 						$Certificate,
1.544     raeburn   448: 						$KeyFile,
1.545     raeburn   449: 						$clientname,
1.546     raeburn   450:                                                 $CRLFile,
                    451:                                                 $clientversion);
1.200     matthew   452:     if(! ($SSLSocket) ) {	# SSL socket promotion failed.
                    453: 	my $err = lonssl::LastError();
                    454: 	&logthis("<font color=\"red\"> CRITICAL "
                    455: 		 ."SSL Socket promotion failed: $err </font>");
                    456: 	return undef;
                    457:     }
                    458:     Debug("SSL Promotion successful");
                    459: 
                    460:     # 
                    461:     #  The only thing we'll use the socket for is to send the IDEA key
                    462:     #  to the peer:
                    463: 
                    464:     my $Key = lonlocal::CreateCipherKey();
                    465:     print $SSLSocket "$Key\n";
                    466: 
                    467:     lonssl::Close($SSLSocket); 
                    468: 
                    469:     Debug("Key exchange complete: $Key");
                    470: 
                    471:     return $Key;
                    472: }
                    473: #
                    474: #     InsecureConnection: 
                    475: #        If insecure connections are allowd,
                    476: #        exchange a challenge with the client to 'validate' the
                    477: #        client (not really, but that's the protocol):
                    478: #        We produce a challenge string that's sent to the client.
                    479: #        The client must then echo the challenge verbatim to us.
                    480: #
                    481: #  Parameter:
                    482: #      Socket      - Socket open on the client.
                    483: #  Returns:
                    484: #      1           - success.
                    485: #      0           - failure (e.g.mismatch or insecure not allowed).
                    486: #
                    487: sub InsecureConnection {
                    488:     my $Socket  =  shift;
                    489: 
                    490:     #   Don't even start if insecure connections are not allowed.
1.532     raeburn   491:     #   return 0 if Insecure connections not allowed.
                    492:     #
                    493:     if (ref($secureconf{'connfrom'}) eq 'HASH') {
                    494:         if ($clientsamedom) {
                    495:             if ($secureconf{'connfrom'}{'dom'} eq 'req') {
                    496:                 return 0;
                    497:             } 
                    498:         } elsif ($clientsameinst) {
                    499:             if ($secureconf{'connfrom'}{'intdom'} eq 'req') {
                    500:                 return 0;
                    501:             }
                    502:         } else {
                    503:             if ($secureconf{'connfrom'}{'other'} eq 'req') {
                    504:                 return 0;
                    505:             }
                    506:         }
                    507:     } elsif (!$perlvar{londAllowInsecure}) {
1.200     matthew   508: 	return 0;
                    509:     }
                    510: 
                    511:     #   Fabricate a challenge string and send it..
                    512: 
                    513:     my $challenge = "$$".time;	# pid + time.
                    514:     print $Socket "$challenge\n";
                    515:     &status("Waiting for challenge reply");
                    516: 
                    517:     my $answer = <$Socket>;
                    518:     $answer    =~s/\W//g;
                    519:     if($challenge eq $answer) {
                    520: 	return 1;
1.224     foxr      521:     } else {
1.200     matthew   522: 	logthis("<font color='blue'>WARNING client did not respond to challenge</font>");
                    523: 	&status("No challenge reqply");
                    524: 	return 0;
                    525:     }
                    526:     
                    527: 
                    528: }
1.251     foxr      529: #
                    530: #   Safely execute a command (as long as it's not a shel command and doesn
                    531: #   not require/rely on shell escapes.   The function operates by doing a
                    532: #   a pipe based fork and capturing stdout and stderr  from the pipe.
                    533: #
                    534: # Formal Parameters:
                    535: #     $line                    - A line of text to be executed as a command.
                    536: # Returns:
                    537: #     The output from that command.  If the output is multiline the caller
                    538: #     must know how to split up the output.
                    539: #
                    540: #
                    541: sub execute_command {
                    542:     my ($line)    = @_;
                    543:     my @words     = split(/\s/, $line);	# Bust the command up into words.
                    544:     my $output    = "";
                    545: 
                    546:     my $pid = open(CHILD, "-|");
                    547:     
                    548:     if($pid) {			# Parent process
                    549: 	Debug("In parent process for execute_command");
                    550: 	my @data = <CHILD>;	# Read the child's outupt...
                    551: 	close CHILD;
                    552: 	foreach my $output_line (@data) {
                    553: 	    Debug("Adding $output_line");
                    554: 	    $output .= $output_line; # Presumably has a \n on it.
                    555: 	}
                    556: 
                    557:     } else {			# Child process
                    558: 	close (STDERR);
                    559: 	open  (STDERR, ">&STDOUT");# Combine stderr, and stdout...
                    560: 	exec(@words);		# won't return.
                    561:     }
                    562:     return $output;
                    563: }
                    564: 
1.200     matthew   565: 
1.140     foxr      566: #   GetCertificate: Given a transaction that requires a certificate,
                    567: #   this function will extract the certificate from the transaction
                    568: #   request.  Note that at this point, the only concept of a certificate
                    569: #   is the hostname to which we are connected.
                    570: #
                    571: #   Parameter:
                    572: #      request   - The request sent by our client (this parameterization may
                    573: #                  need to change when we really use a certificate granting
                    574: #                  authority.
                    575: #
                    576: sub GetCertificate {
                    577:     my $request = shift;
                    578: 
                    579:     return $clientip;
                    580: }
1.161     foxr      581: 
1.178     foxr      582: #
                    583: #   Return true if client is a manager.
                    584: #
                    585: sub isManager {
                    586:     return (($ConnectionType eq "manager") || ($ConnectionType eq "both"));
                    587: }
                    588: #
                    589: #   Return tru if client can do client functions
                    590: #
                    591: sub isClient {
                    592:     return (($ConnectionType eq "client") || ($ConnectionType eq "both"));
                    593: }
1.161     foxr      594: 
                    595: 
1.156     foxr      596: #
                    597: #   ReadManagerTable: Reads in the current manager table. For now this is
                    598: #                     done on each manager authentication because:
                    599: #                     - These authentications are not frequent
                    600: #                     - This allows dynamic changes to the manager table
                    601: #                       without the need to signal to the lond.
                    602: #
                    603: sub ReadManagerTable {
                    604: 
1.412     foxr      605:     &Debug("Reading manager table");
1.156     foxr      606:     #   Clean out the old table first..
                    607: 
1.166     foxr      608:    foreach my $key (keys %managers) {
                    609:       delete $managers{$key};
                    610:    }
                    611: 
                    612:    my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
                    613:    if (!open (MANAGERS, $tablename)) {
1.473     raeburn   614:        my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
                    615:        if (&Apache::lonnet::is_LC_dns($hostname)) {
1.472     raeburn   616:            &logthis('<font color="red">No manager table.  Nobody can manage!!</font>');
                    617:        }
                    618:        return;
1.166     foxr      619:    }
                    620:    while(my $host = <MANAGERS>) {
                    621:       chomp($host);
                    622:       if ($host =~ "^#") {                  # Comment line.
                    623:          next;
                    624:       }
1.368     albertel  625:       if (!defined &Apache::lonnet::get_host_ip($host)) { # This is a non cluster member
1.161     foxr      626: 	    #  The entry is of the form:
                    627: 	    #    cluname:hostname
                    628: 	    #  cluname - A 'cluster hostname' is needed in order to negotiate
                    629: 	    #            the host key.
                    630: 	    #  hostname- The dns name of the host.
                    631: 	    #
1.166     foxr      632:           my($cluname, $dnsname) = split(/:/, $host);
                    633:           
                    634:           my $ip = gethostbyname($dnsname);
                    635:           if(defined($ip)) {                 # bad names don't deserve entry.
                    636:             my $hostip = inet_ntoa($ip);
                    637:             $managers{$hostip} = $cluname;
                    638:             logthis('<font color="green"> registering manager '.
                    639:                     "$dnsname as $cluname with $hostip </font>\n");
                    640:          }
                    641:       } else {
                    642:          logthis('<font color="green"> existing host'." $host</font>\n");
1.472     raeburn   643:          $managers{&Apache::lonnet::get_host_ip($host)} = $host;  # Use info from cluster tab if cluster memeber
1.166     foxr      644:       }
                    645:    }
1.156     foxr      646: }
1.140     foxr      647: 
                    648: #
                    649: #  ValidManager: Determines if a given certificate represents a valid manager.
                    650: #                in this primitive implementation, the 'certificate' is
                    651: #                just the connecting loncapa client name.  This is checked
                    652: #                against a valid client list in the configuration.
                    653: #
                    654: #                  
                    655: sub ValidManager {
                    656:     my $certificate = shift; 
                    657: 
1.163     foxr      658:     return isManager;
1.140     foxr      659: }
                    660: #
1.143     foxr      661: #  CopyFile:  Called as part of the process of installing a 
                    662: #             new configuration file.  This function copies an existing
                    663: #             file to a backup file.
                    664: # Parameters:
                    665: #     oldfile  - Name of the file to backup.
                    666: #     newfile  - Name of the backup file.
                    667: # Return:
                    668: #     0   - Failure (errno has failure reason).
                    669: #     1   - Success.
                    670: #
                    671: sub CopyFile {
1.192     foxr      672: 
                    673:     my ($oldfile, $newfile) = @_;
1.143     foxr      674: 
1.281     matthew   675:     if (! copy($oldfile,$newfile)) {
                    676:         return 0;
1.143     foxr      677:     }
1.281     matthew   678:     chmod(0660, $newfile);
                    679:     return 1;
1.143     foxr      680: }
1.157     foxr      681: #
                    682: #  Host files are passed out with externally visible host IPs.
                    683: #  If, for example, we are behind a fire-wall or NAT host, our 
                    684: #  internally visible IP may be different than the externally
                    685: #  visible IP.  Therefore, we always adjust the contents of the
                    686: #  host file so that the entry for ME is the IP that we believe
                    687: #  we have.  At present, this is defined as the entry that
                    688: #  DNS has for us.  If by some chance we are not able to get a
                    689: #  DNS translation for us, then we assume that the host.tab file
                    690: #  is correct.  
                    691: #    BUGBUGBUG - in the future, we really should see if we can
                    692: #       easily query the interface(s) instead.
                    693: # Parameter(s):
                    694: #     contents    - The contents of the host.tab to check.
                    695: # Returns:
                    696: #     newcontents - The adjusted contents.
                    697: #
                    698: #
                    699: sub AdjustHostContents {
                    700:     my $contents  = shift;
                    701:     my $adjusted;
                    702:     my $me        = $perlvar{'lonHostID'};
                    703: 
1.354     albertel  704:     foreach my $line (split(/\n/,$contents)) {
1.472     raeburn   705: 	if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/) ||
                    706:              ($line =~ /^\s*\^/))) {
1.157     foxr      707: 	    chomp($line);
                    708: 	    my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
                    709: 	    if ($id eq $me) {
1.354     albertel  710: 		my $ip = gethostbyname($name);
                    711: 		my $ipnew = inet_ntoa($ip);
                    712: 		$ip = $ipnew;
1.157     foxr      713: 		#  Reconstruct the host line and append to adjusted:
                    714: 		
1.354     albertel  715: 		my $newline = "$id:$domain:$role:$name:$ip";
                    716: 		if($maxcon ne "") { # Not all hosts have loncnew tuning params
                    717: 		    $newline .= ":$maxcon:$idleto:$mincon";
                    718: 		}
                    719: 		$adjusted .= $newline."\n";
1.157     foxr      720: 		
1.354     albertel  721: 	    } else {		# Not me, pass unmodified.
                    722: 		$adjusted .= $line."\n";
                    723: 	    }
1.157     foxr      724: 	} else {                  # Blank or comment never re-written.
                    725: 	    $adjusted .= $line."\n";	# Pass blanks and comments as is.
                    726: 	}
1.354     albertel  727:     }
                    728:     return $adjusted;
1.157     foxr      729: }
1.143     foxr      730: #
                    731: #   InstallFile: Called to install an administrative file:
1.412     foxr      732: #       - The file is created int a temp directory called <name>.tmp
                    733: #       - lcinstall file is called to install the file.
                    734: #         since the web app has no direct write access to the table directory
1.143     foxr      735: #
                    736: #  Parameters:
                    737: #       Name of the file
                    738: #       File Contents.
                    739: #  Return:
                    740: #      nonzero - success.
                    741: #      0       - failure and $! has an errno.
1.412     foxr      742: # Assumptions:
                    743: #    File installtion is a relatively infrequent
1.143     foxr      744: #
                    745: sub InstallFile {
1.192     foxr      746: 
                    747:     my ($Filename, $Contents) = @_;
1.412     foxr      748: #     my $TempFile = $Filename.".tmp";
                    749:     my $exedir = $perlvar{'lonDaemons'};
                    750:     my $tmpdir = $exedir.'/tmp/';
                    751:     my $TempFile = $tmpdir."TempTableFile.tmp";
1.143     foxr      752: 
                    753:     #  Open the file for write:
                    754: 
                    755:     my $fh = IO::File->new("> $TempFile"); # Write to temp.
                    756:     if(!(defined $fh)) {
                    757: 	&logthis('<font color="red"> Unable to create '.$TempFile."</font>");
                    758: 	return 0;
                    759:     }
                    760:     #  write the contents of the file:
                    761: 
                    762:     print $fh ($Contents); 
                    763:     $fh->close;			# In case we ever have a filesystem w. locking
                    764: 
1.412     foxr      765:     chmod(0664, $TempFile);	# Everyone can write it.
                    766: 
                    767:     # Use lcinstall file to put the file in the table directory...
                    768: 
                    769:     &Debug("Opening pipe to $exedir/lcinstallfile $TempFile $Filename");
                    770:     my $pf = IO::File->new("| $exedir/lcinstallfile   $TempFile $Filename > $exedir/logs/lcinstallfile.log");
                    771:     close $pf;
                    772:     my $err = $?;
                    773:     &Debug("Status is $err");
                    774:     if ($err != 0) {
                    775: 	my $msg = $err;
                    776: 	if ($err < @installerrors) {
                    777: 	    $msg = $installerrors[$err];
                    778: 	}
                    779: 	&logthis("Install failed for table file $Filename : $msg");
                    780: 	return 0;
                    781:     }
                    782: 
                    783:     # Remove the temp file:
1.143     foxr      784: 
1.412     foxr      785:     unlink($TempFile);
1.143     foxr      786: 
                    787:     return 1;
                    788: }
1.200     matthew   789: 
                    790: 
1.169     foxr      791: #
                    792: #   ConfigFileFromSelector: converts a configuration file selector
1.411     foxr      793: #                 into a configuration file pathname.
1.472     raeburn   794: #                 Supports the following file selectors: 
                    795: #                 hosts, domain, dns_hosts, dns_domain  
1.411     foxr      796: #
1.169     foxr      797: #
                    798: #  Parameters:
                    799: #      selector  - Configuration file selector.
                    800: #  Returns:
                    801: #      Full path to the file or undef if the selector is invalid.
                    802: #
                    803: sub ConfigFileFromSelector {
                    804:     my $selector   = shift;
                    805:     my $tablefile;
                    806: 
1.549     raeburn   807:     if ($selector eq 'loncapaCAcrl') {
                    808:         my $tabledir = $perlvar{'lonCertificateDirectory'};
                    809:         if (-d $tabledir) {
                    810:             $tablefile =  $tabledir.'/'.$selector.'.pem';
                    811:         }
                    812:     } else {
                    813:         my $tabledir = $perlvar{'lonTabDir'}.'/';
                    814:         if (($selector eq "hosts") || ($selector eq "domain") || 
                    815:             ($selector eq "dns_hosts") || ($selector eq "dns_domain")) {
                    816: 	    $tablefile =  $tabledir.$selector.'.tab';
                    817:         }
1.169     foxr      818:     }
                    819:     return $tablefile;
                    820: }
1.143     foxr      821: #
1.141     foxr      822: #   PushFile:  Called to do an administrative push of a file.
                    823: #              - Ensure the file being pushed is one we support.
                    824: #              - Backup the old file to <filename.saved>
                    825: #              - Separate the contents of the new file out from the
                    826: #                rest of the request.
                    827: #              - Write the new file.
                    828: #  Parameter:
                    829: #     Request - The entire user request.  This consists of a : separated
                    830: #               string pushfile:tablename:contents.
                    831: #     NOTE:  The contents may have :'s in it as well making things a bit
                    832: #            more interesting... but not much.
                    833: #  Returns:
                    834: #     String to send to client ("ok" or "refused" if bad file).
                    835: #
                    836: sub PushFile {
1.510     raeburn   837:     my $request = shift;
1.141     foxr      838:     my ($command, $filename, $contents) = split(":", $request, 3);
1.412     foxr      839:     &Debug("PushFile");
1.141     foxr      840:     
1.549     raeburn   841:     #  At this point in time, pushes for only the following tables and
                    842:     #  CRL file are supported:
1.141     foxr      843:     #   hosts.tab  ($filename eq host).
                    844:     #   domain.tab ($filename eq domain).
1.472     raeburn   845:     #   dns_hosts.tab ($filename eq dns_host).
1.554     raeburn   846:     #   dns_domain.tab ($filename eq dns_domain).
                    847:     #   loncapaCAcrl.pem ($filename eq loncapaCAcrl).
1.141     foxr      848:     # Construct the destination filename or reject the request.
                    849:     #
                    850:     # lonManage is supposed to ensure this, however this session could be
                    851:     # part of some elaborate spoof that managed somehow to authenticate.
                    852:     #
                    853: 
1.169     foxr      854: 
                    855:     my $tablefile = ConfigFileFromSelector($filename);
                    856:     if(! (defined $tablefile)) {
1.141     foxr      857: 	return "refused";
                    858:     }
1.412     foxr      859: 
1.157     foxr      860:     #  If the file being pushed is the host file, we adjust the entry for ourself so that the
                    861:     #  IP will be our current IP as looked up in dns.  Note this is only 99% good as it's possible
                    862:     #  to conceive of conditions where we don't have a DNS entry locally.  This is possible in a 
                    863:     #  network sense but it doesn't make much sense in a LonCAPA sense so we ignore (for now)
                    864:     #  that possibilty.
                    865: 
                    866:     if($filename eq "host") {
                    867: 	$contents = AdjustHostContents($contents);
1.549     raeburn   868:     } elsif (($filename eq 'dns_host') || ($filename eq 'dns_domain') ||
                    869:              ($filename eq 'loncapaCAcrl')) {
1.510     raeburn   870:         if ($contents eq '') {
                    871:             &logthis('<font color="red"> Pushfile: unable to install '
                    872:                     .$tablefile." - no data received from push. </font>");
                    873:             return 'error: push had no data';
                    874:         }
                    875:         if (&Apache::lonnet::get_host_ip($clientname)) {
                    876:             my $clienthost = &Apache::lonnet::hostname($clientname);
                    877:             if ($managers{$clientip} eq $clientname) {
                    878:                 my $clientprotocol = $Apache::lonnet::protocol{$clientname};
                    879:                 $clientprotocol = 'http' if ($clientprotocol ne 'https');
1.549     raeburn   880:                 my $url;
                    881:                 if ($filename eq 'loncapaCAcrl') {
                    882:                     $url = '/adm/dns/loncapaCRL';
                    883:                 } else {
                    884:                     $url = '/adm/'.$filename;
                    885:                     $url =~ s{_}{/};
                    886:                 }
1.510     raeburn   887:                 my $request=new HTTP::Request('GET',"$clientprotocol://$clienthost$url");
1.523     raeburn   888:                 my $response = LONCAPA::LWPReq::makerequest($clientname,$request,'',\%perlvar,60,0);
1.510     raeburn   889:                 if ($response->is_error()) {
                    890:                     &logthis('<font color="red"> Pushfile: unable to install '
                    891:                             .$tablefile." - error attempting to pull data. </font>");
                    892:                     return 'error: pull failed';
                    893:                 } else {
                    894:                     my $result = $response->content;
                    895:                     chomp($result);
                    896:                     unless ($result eq $contents) {
                    897:                         &logthis('<font color="red"> Pushfile: unable to install '
                    898:                                 .$tablefile." - pushed data and pulled data differ. </font>");
                    899:                         my $pushleng = length($contents);
                    900:                         my $pullleng = length($result);
                    901:                         if ($pushleng != $pullleng) {
                    902:                             return "error: $pushleng vs $pullleng bytes";
                    903:                         } else {
                    904:                             return "error: mismatch push and pull";
                    905:                         }
                    906:                     }
                    907:                 }
                    908:             }
                    909:         }
1.157     foxr      910:     }
                    911: 
1.141     foxr      912:     #  Install the new file:
                    913: 
1.412     foxr      914:     &logthis("Installing new $tablefile contents:\n$contents");
1.143     foxr      915:     if(!InstallFile($tablefile, $contents)) {
                    916: 	&logthis('<font color="red"> Pushfile: unable to install '
1.145     foxr      917: 	 .$tablefile." $! </font>");
1.143     foxr      918: 	return "error:$!";
1.224     foxr      919:     } else {
1.143     foxr      920: 	&logthis('<font color="green"> Installed new '.$tablefile
1.473     raeburn   921: 		 ." - transaction by: $clientname ($clientip)</font>");
1.472     raeburn   922:         my $adminmail = $perlvar{'lonAdmEMail'};
                    923:         my $admindom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                    924:         if ($admindom ne '') {
                    925:             my %domconfig =
                    926:                 &Apache::lonnet::get_dom('configuration',['contacts'],$admindom);
                    927:             if (ref($domconfig{'contacts'}) eq 'HASH') {
                    928:                 if ($domconfig{'contacts'}{'adminemail'} ne '') {
                    929:                     $adminmail = $domconfig{'contacts'}{'adminemail'};
                    930:                 }
                    931:             }
                    932:         }
                    933:         if ($adminmail =~ /^[^\@]+\@[^\@]+$/) {
                    934:             my $msg = new Mail::Send;
                    935:             $msg->to($adminmail);
                    936:             $msg->subject('LON-CAPA DNS update on '.$perlvar{'lonHostID'});
                    937:             $msg->add('Content-type','text/plain; charset=UTF-8');
                    938:             if (my $fh = $msg->open()) {
                    939:                 print $fh 'Update to '.$tablefile.' from Cluster Manager '.
1.473     raeburn   940:                           "$clientname ($clientip)\n";
1.472     raeburn   941:                 $fh->close;
                    942:             }
                    943:         }
1.143     foxr      944:     }
                    945: 
1.141     foxr      946:     #  Indicate success:
                    947:  
                    948:     return "ok";
                    949: 
                    950: }
1.145     foxr      951: 
                    952: #
                    953: #  Called to re-init either lonc or lond.
                    954: #
                    955: #  Parameters:
                    956: #    request   - The full request by the client.  This is of the form
                    957: #                reinit:<process>  
                    958: #                where <process> is allowed to be either of 
                    959: #                lonc or lond
                    960: #
                    961: #  Returns:
                    962: #     The string to be sent back to the client either:
                    963: #   ok         - Everything worked just fine.
                    964: #   error:why  - There was a failure and why describes the reason.
                    965: #
                    966: #
                    967: sub ReinitProcess {
                    968:     my $request = shift;
                    969: 
1.146     foxr      970: 
                    971:     # separate the request (reinit) from the process identifier and
                    972:     # validate it producing the name of the .pid file for the process.
                    973:     #
                    974:     #
                    975:     my ($junk, $process) = split(":", $request);
1.147     foxr      976:     my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
1.146     foxr      977:     if($process eq 'lonc') {
                    978: 	$processpidfile = $processpidfile."lonc.pid";
1.147     foxr      979: 	if (!open(PIDFILE, "< $processpidfile")) {
                    980: 	    return "error:Open failed for $processpidfile";
                    981: 	}
                    982: 	my $loncpid = <PIDFILE>;
                    983: 	close(PIDFILE);
                    984: 	logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
                    985: 		."</font>");
                    986: 	kill("USR2", $loncpid);
1.146     foxr      987:     } elsif ($process eq 'lond') {
1.147     foxr      988: 	logthis('<font color="red"> Reinitializing self (lond) </font>');
                    989: 	&UpdateHosts;			# Lond is us!!
1.146     foxr      990:     } else {
                    991: 	&logthis('<font color="yellow" Invalid reinit request for '.$process
                    992: 		 ."</font>");
                    993: 	return "error:Invalid process identifier $process";
                    994:     }
1.145     foxr      995:     return 'ok';
                    996: }
1.168     foxr      997: #   Validate a line in a configuration file edit script:
                    998: #   Validation includes:
                    999: #     - Ensuring the command is valid.
                   1000: #     - Ensuring the command has sufficient parameters
                   1001: #   Parameters:
                   1002: #     scriptline - A line to validate (\n has been stripped for what it's worth).
1.167     foxr     1003: #
1.168     foxr     1004: #   Return:
                   1005: #      0     - Invalid scriptline.
                   1006: #      1     - Valid scriptline
                   1007: #  NOTE:
                   1008: #     Only the command syntax is checked, not the executability of the
                   1009: #     command.
                   1010: #
                   1011: sub isValidEditCommand {
                   1012:     my $scriptline = shift;
                   1013: 
                   1014:     #   Line elements are pipe separated:
                   1015: 
                   1016:     my ($command, $key, $newline)  = split(/\|/, $scriptline);
                   1017:     &logthis('<font color="green"> isValideditCommand checking: '.
                   1018: 	     "Command = '$command', Key = '$key', Newline = '$newline' </font>\n");
                   1019:     
                   1020:     if ($command eq "delete") {
                   1021: 	#
                   1022: 	#   key with no newline.
                   1023: 	#
                   1024: 	if( ($key eq "") || ($newline ne "")) {
                   1025: 	    return 0;		# Must have key but no newline.
                   1026: 	} else {
                   1027: 	    return 1;		# Valid syntax.
                   1028: 	}
1.169     foxr     1029:     } elsif ($command eq "replace") {
1.168     foxr     1030: 	#
                   1031: 	#   key and newline:
                   1032: 	#
                   1033: 	if (($key eq "") || ($newline eq "")) {
                   1034: 	    return 0;
                   1035: 	} else {
                   1036: 	    return 1;
                   1037: 	}
1.169     foxr     1038:     } elsif ($command eq "append") {
                   1039: 	if (($key ne "") && ($newline eq "")) {
                   1040: 	    return 1;
                   1041: 	} else {
                   1042: 	    return 0;
                   1043: 	}
1.168     foxr     1044:     } else {
                   1045: 	return 0;		# Invalid command.
                   1046:     }
                   1047:     return 0;			# Should not get here!!!
                   1048: }
1.169     foxr     1049: #
                   1050: #   ApplyEdit - Applies an edit command to a line in a configuration 
                   1051: #               file.  It is the caller's responsiblity to validate the
                   1052: #               edit line.
                   1053: #   Parameters:
                   1054: #      $directive - A single edit directive to apply.  
                   1055: #                   Edit directives are of the form:
                   1056: #                  append|newline      - Appends a new line to the file.
                   1057: #                  replace|key|newline - Replaces the line with key value 'key'
                   1058: #                  delete|key          - Deletes the line with key value 'key'.
                   1059: #      $editor   - A config file editor object that contains the
                   1060: #                  file being edited.
                   1061: #
                   1062: sub ApplyEdit {
1.192     foxr     1063: 
                   1064:     my ($directive, $editor) = @_;
1.169     foxr     1065: 
                   1066:     # Break the directive down into its command and its parameters
                   1067:     # (at most two at this point.  The meaning of the parameters, if in fact
                   1068:     #  they exist depends on the command).
                   1069: 
                   1070:     my ($command, $p1, $p2) = split(/\|/, $directive);
                   1071: 
                   1072:     if($command eq "append") {
                   1073: 	$editor->Append($p1);	          # p1 - key p2 null.
                   1074:     } elsif ($command eq "replace") {
                   1075: 	$editor->ReplaceLine($p1, $p2);   # p1 - key p2 = newline.
                   1076:     } elsif ($command eq "delete") {
                   1077: 	$editor->DeleteLine($p1);         # p1 - key p2 null.
                   1078:     } else {			          # Should not get here!!!
                   1079: 	die "Invalid command given to ApplyEdit $command"
                   1080:     }
                   1081: }
                   1082: #
                   1083: # AdjustOurHost:
                   1084: #           Adjusts a host file stored in a configuration file editor object
                   1085: #           for the true IP address of this host. This is necessary for hosts
                   1086: #           that live behind a firewall.
                   1087: #           Those hosts have a publicly distributed IP of the firewall, but
                   1088: #           internally must use their actual IP.  We assume that a given
                   1089: #           host only has a single IP interface for now.
                   1090: # Formal Parameters:
                   1091: #     editor   - The configuration file editor to adjust.  This
                   1092: #                editor is assumed to contain a hosts.tab file.
                   1093: # Strategy:
                   1094: #    - Figure out our hostname.
                   1095: #    - Lookup the entry for this host.
                   1096: #    - Modify the line to contain our IP
                   1097: #    - Do a replace for this host.
                   1098: sub AdjustOurHost {
                   1099:     my $editor        = shift;
                   1100: 
                   1101:     # figure out who I am.
                   1102: 
                   1103:     my $myHostName    = $perlvar{'lonHostID'}; # LonCAPA hostname.
                   1104: 
                   1105:     #  Get my host file entry.
                   1106: 
                   1107:     my $ConfigLine    = $editor->Find($myHostName);
                   1108:     if(! (defined $ConfigLine)) {
                   1109: 	die "AdjustOurHost - no entry for me in hosts file $myHostName";
                   1110:     }
                   1111:     # figure out my IP:
                   1112:     #   Use the config line to get my hostname.
                   1113:     #   Use gethostbyname to translate that into an IP address.
                   1114:     #
1.338     albertel 1115:     my ($id,$domain,$role,$name,$maxcon,$idleto,$mincon) = split(/:/,$ConfigLine);
1.169     foxr     1116:     #
                   1117:     #  Reassemble the config line from the elements in the list.
                   1118:     #  Note that if the loncnew items were not present before, they will
                   1119:     #  be now even if they would be empty
                   1120:     #
                   1121:     my $newConfigLine = $id;
1.338     albertel 1122:     foreach my $item ($domain, $role, $name, $maxcon, $idleto, $mincon) {
1.169     foxr     1123: 	$newConfigLine .= ":".$item;
                   1124:     }
                   1125:     #  Replace the line:
                   1126: 
                   1127:     $editor->ReplaceLine($id, $newConfigLine);
                   1128:     
                   1129: }
                   1130: #
                   1131: #   ReplaceConfigFile:
                   1132: #              Replaces a configuration file with the contents of a
                   1133: #              configuration file editor object.
                   1134: #              This is done by:
                   1135: #              - Copying the target file to <filename>.old
                   1136: #              - Writing the new file to <filename>.tmp
                   1137: #              - Moving <filename.tmp>  -> <filename>
                   1138: #              This laborious process ensures that the system is never without
                   1139: #              a configuration file that's at least valid (even if the contents
                   1140: #              may be dated).
                   1141: #   Parameters:
                   1142: #        filename   - Name of the file to modify... this is a full path.
                   1143: #        editor     - Editor containing the file.
                   1144: #
                   1145: sub ReplaceConfigFile {
1.192     foxr     1146:     
                   1147:     my ($filename, $editor) = @_;
1.168     foxr     1148: 
1.169     foxr     1149:     CopyFile ($filename, $filename.".old");
                   1150: 
                   1151:     my $contents  = $editor->Get(); # Get the contents of the file.
                   1152: 
                   1153:     InstallFile($filename, $contents);
                   1154: }
1.168     foxr     1155: #   
                   1156: #
                   1157: #   Called to edit a configuration table  file
1.167     foxr     1158: #   Parameters:
                   1159: #      request           - The entire command/request sent by lonc or lonManage
                   1160: #   Return:
                   1161: #      The reply to send to the client.
1.168     foxr     1162: #
1.167     foxr     1163: sub EditFile {
                   1164:     my $request = shift;
                   1165: 
                   1166:     #  Split the command into it's pieces:  edit:filetype:script
                   1167: 
1.339     albertel 1168:     my ($cmd, $filetype, $script) = split(/:/, $request,3);	# : in script
1.167     foxr     1169: 
                   1170:     #  Check the pre-coditions for success:
                   1171: 
1.339     albertel 1172:     if($cmd != "edit") {	# Something is amiss afoot alack.
1.167     foxr     1173: 	return "error:edit request detected, but request != 'edit'\n";
                   1174:     }
                   1175:     if( ($filetype ne "hosts")  &&
                   1176: 	($filetype ne "domain")) {
                   1177: 	return "error:edit requested with invalid file specifier: $filetype \n";
                   1178:     }
                   1179: 
                   1180:     #   Split the edit script and check it's validity.
1.168     foxr     1181: 
                   1182:     my @scriptlines = split(/\n/, $script);  # one line per element.
                   1183:     my $linecount   = scalar(@scriptlines);
                   1184:     for(my $i = 0; $i < $linecount; $i++) {
                   1185: 	chomp($scriptlines[$i]);
                   1186: 	if(!isValidEditCommand($scriptlines[$i])) {
                   1187: 	    return "error:edit with bad script line: '$scriptlines[$i]' \n";
                   1188: 	}
                   1189:     }
1.145     foxr     1190: 
1.167     foxr     1191:     #   Execute the edit operation.
1.169     foxr     1192:     #   - Create a config file editor for the appropriate file and 
                   1193:     #   - execute each command in the script:
                   1194:     #
                   1195:     my $configfile = ConfigFileFromSelector($filetype);
                   1196:     if (!(defined $configfile)) {
                   1197: 	return "refused\n";
                   1198:     }
                   1199:     my $editor = ConfigFileEdit->new($configfile);
1.167     foxr     1200: 
1.169     foxr     1201:     for (my $i = 0; $i < $linecount; $i++) {
                   1202: 	ApplyEdit($scriptlines[$i], $editor);
                   1203:     }
                   1204:     # If the file is the host file, ensure that our host is
                   1205:     # adjusted to have our ip:
                   1206:     #
                   1207:     if($filetype eq "host") {
                   1208: 	AdjustOurHost($editor);
                   1209:     }
                   1210:     #  Finally replace the current file with our file.
                   1211:     #
                   1212:     ReplaceConfigFile($configfile, $editor);
1.167     foxr     1213: 
                   1214:     return "ok\n";
                   1215: }
1.207     foxr     1216: 
1.255     foxr     1217: #   read_profile
                   1218: #
                   1219: #   Returns a set of specific entries from a user's profile file.
                   1220: #   this is a utility function that is used by both get_profile_entry and
                   1221: #   get_profile_entry_encrypted.
                   1222: #
                   1223: # Parameters:
                   1224: #    udom       - Domain in which the user exists.
                   1225: #    uname      - User's account name (loncapa account)
                   1226: #    namespace  - The profile namespace to open.
                   1227: #    what       - A set of & separated queries.
                   1228: # Returns:
                   1229: #    If all ok: - The string that needs to be shipped back to the user.
                   1230: #    If failure - A string that starts with error: followed by the failure
                   1231: #                 reason.. note that this probabyl gets shipped back to the
                   1232: #                 user as well.
                   1233: #
                   1234: sub read_profile {
                   1235:     my ($udom, $uname, $namespace, $what) = @_;
                   1236:     
                   1237:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   1238: 				 &GDBM_READER());
                   1239:     if ($hashref) {
                   1240:         my @queries=split(/\&/,$what);
1.440     raeburn  1241:         if ($namespace eq 'roles') {
                   1242:             @queries = map { &unescape($_); } @queries; 
                   1243:         }
1.255     foxr     1244:         my $qresult='';
                   1245: 	
                   1246: 	for (my $i=0;$i<=$#queries;$i++) {
                   1247: 	    $qresult.="$hashref->{$queries[$i]}&";    # Presumably failure gives empty string.
                   1248: 	}
                   1249: 	$qresult=~s/\&$//;              # Remove trailing & from last lookup.
1.311     albertel 1250: 	if (&untie_user_hash($hashref)) {
1.255     foxr     1251: 	    return $qresult;
                   1252: 	} else {
                   1253: 	    return "error: ".($!+0)." untie (GDBM) Failed";
                   1254: 	}
                   1255:     } else {
                   1256: 	if ($!+0 == 2) {
                   1257: 	    return "error:No such file or GDBM reported bad block error";
                   1258: 	} else {
                   1259: 	    return "error: ".($!+0)." tie (GDBM) Failed";
                   1260: 	}
                   1261:     }
                   1262: 
                   1263: }
1.214     foxr     1264: #--------------------- Request Handlers --------------------------------------------
                   1265: #
1.215     foxr     1266: #   By convention each request handler registers itself prior to the sub 
                   1267: #   declaration:
1.214     foxr     1268: #
                   1269: 
1.216     foxr     1270: #++
                   1271: #
1.214     foxr     1272: #  Handles ping requests.
                   1273: #  Parameters:
                   1274: #      $cmd    - the actual keyword that invoked us.
                   1275: #      $tail   - the tail of the request that invoked us.
                   1276: #      $replyfd- File descriptor connected to the client
                   1277: #  Implicit Inputs:
                   1278: #      $currenthostid - Global variable that carries the name of the host we are
                   1279: #                       known as.
                   1280: #  Returns:
                   1281: #      1       - Ok to continue processing.
                   1282: #      0       - Program should exit.
                   1283: #  Side effects:
                   1284: #      Reply information is sent to the client.
                   1285: sub ping_handler {
                   1286:     my ($cmd, $tail, $client) = @_;
                   1287:     Debug("$cmd $tail $client .. $currenthostid:");
                   1288:    
1.387     albertel 1289:     Reply( $client,\$currenthostid,"$cmd:$tail");
1.214     foxr     1290:    
                   1291:     return 1;
                   1292: }
                   1293: &register_handler("ping", \&ping_handler, 0, 1, 1);       # Ping unencoded, client or manager.
                   1294: 
1.216     foxr     1295: #++
1.215     foxr     1296: #
                   1297: # Handles pong requests.  Pong replies with our current host id, and
                   1298: #                         the results of a ping sent to us via our lonc.
                   1299: #
                   1300: # Parameters:
                   1301: #      $cmd    - the actual keyword that invoked us.
                   1302: #      $tail   - the tail of the request that invoked us.
                   1303: #      $replyfd- File descriptor connected to the client
                   1304: #  Implicit Inputs:
                   1305: #      $currenthostid - Global variable that carries the name of the host we are
                   1306: #                       connected to.
                   1307: #  Returns:
                   1308: #      1       - Ok to continue processing.
                   1309: #      0       - Program should exit.
                   1310: #  Side effects:
                   1311: #      Reply information is sent to the client.
                   1312: sub pong_handler {
                   1313:     my ($cmd, $tail, $replyfd) = @_;
                   1314: 
1.365     albertel 1315:     my $reply=&Apache::lonnet::reply("ping",$clientname);
1.215     foxr     1316:     &Reply( $replyfd, "$currenthostid:$reply\n", "$cmd:$tail"); 
                   1317:     return 1;
                   1318: }
                   1319: &register_handler("pong", \&pong_handler, 0, 1, 1);       # Pong unencoded, client or manager
                   1320: 
1.216     foxr     1321: #++
                   1322: #      Called to establish an encrypted session key with the remote client.
                   1323: #      Note that with secure lond, in most cases this function is never
                   1324: #      invoked.  Instead, the secure session key is established either
                   1325: #      via a local file that's locked down tight and only lives for a short
                   1326: #      time, or via an ssl tunnel...and is generated from a bunch-o-random
                   1327: #      bits from /dev/urandom, rather than the predictable pattern used by
                   1328: #      by this sub.  This sub is only used in the old-style insecure
                   1329: #      key negotiation.
                   1330: # Parameters:
                   1331: #      $cmd    - the actual keyword that invoked us.
                   1332: #      $tail   - the tail of the request that invoked us.
                   1333: #      $replyfd- File descriptor connected to the client
                   1334: #  Implicit Inputs:
                   1335: #      $currenthostid - Global variable that carries the name of the host
                   1336: #                       known as.
1.448     raeburn  1337: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.216     foxr     1338: #  Returns:
                   1339: #      1       - Ok to continue processing.
                   1340: #      0       - Program should exit.
                   1341: #  Implicit Outputs:
                   1342: #      Reply information is sent to the client.
                   1343: #      $cipher is set with a reference to a new IDEA encryption object.
                   1344: #
                   1345: sub establish_key_handler {
                   1346:     my ($cmd, $tail, $replyfd) = @_;
                   1347: 
                   1348:     my $buildkey=time.$$.int(rand 100000);
                   1349:     $buildkey=~tr/1-6/A-F/;
                   1350:     $buildkey=int(rand 100000).$buildkey.int(rand 100000);
                   1351:     my $key=$currenthostid.$clientname;
                   1352:     $key=~tr/a-z/A-Z/;
                   1353:     $key=~tr/G-P/0-9/;
                   1354:     $key=~tr/Q-Z/0-9/;
                   1355:     $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
                   1356:     $key=substr($key,0,32);
                   1357:     my $cipherkey=pack("H32",$key);
                   1358:     $cipher=new IDEA $cipherkey;
1.387     albertel 1359:     &Reply($replyfd, \$buildkey, "$cmd:$tail"); 
1.216     foxr     1360:    
                   1361:     return 1;
                   1362: 
                   1363: }
                   1364: &register_handler("ekey", \&establish_key_handler, 0, 1,1);
                   1365: 
1.217     foxr     1366: #     Handler for the load command.  Returns the current system load average
                   1367: #     to the requestor.
                   1368: #
                   1369: # Parameters:
                   1370: #      $cmd    - the actual keyword that invoked us.
                   1371: #      $tail   - the tail of the request that invoked us.
                   1372: #      $replyfd- File descriptor connected to the client
                   1373: #  Implicit Inputs:
                   1374: #      $currenthostid - Global variable that carries the name of the host
                   1375: #                       known as.
1.448     raeburn  1376: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.217     foxr     1377: #  Returns:
                   1378: #      1       - Ok to continue processing.
                   1379: #      0       - Program should exit.
                   1380: #  Side effects:
                   1381: #      Reply information is sent to the client.
                   1382: sub load_handler {
                   1383:     my ($cmd, $tail, $replyfd) = @_;
                   1384: 
1.463     foxr     1385: 
                   1386: 
1.217     foxr     1387:    # Get the load average from /proc/loadavg and calculate it as a percentage of
                   1388:    # the allowed load limit as set by the perl global variable lonLoadLim
                   1389: 
                   1390:     my $loadavg;
                   1391:     my $loadfile=IO::File->new('/proc/loadavg');
                   1392:    
                   1393:     $loadavg=<$loadfile>;
                   1394:     $loadavg =~ s/\s.*//g;                      # Extract the first field only.
                   1395:    
                   1396:     my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
                   1397: 
1.387     albertel 1398:     &Reply( $replyfd, \$loadpercent, "$cmd:$tail");
1.217     foxr     1399:    
                   1400:     return 1;
                   1401: }
1.263     albertel 1402: &register_handler("load", \&load_handler, 0, 1, 0);
1.217     foxr     1403: 
                   1404: #
                   1405: #   Process the userload request.  This sub returns to the client the current
                   1406: #  user load average.  It can be invoked either by clients or managers.
                   1407: #
                   1408: # Parameters:
                   1409: #      $cmd    - the actual keyword that invoked us.
                   1410: #      $tail   - the tail of the request that invoked us.
                   1411: #      $replyfd- File descriptor connected to the client
                   1412: #  Implicit Inputs:
                   1413: #      $currenthostid - Global variable that carries the name of the host
                   1414: #                       known as.
1.448     raeburn  1415: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.217     foxr     1416: #  Returns:
                   1417: #      1       - Ok to continue processing.
                   1418: #      0       - Program should exit
                   1419: # Implicit inputs:
                   1420: #     whatever the userload() function requires.
                   1421: #  Implicit outputs:
                   1422: #     the reply is written to the client.
                   1423: #
                   1424: sub user_load_handler {
                   1425:     my ($cmd, $tail, $replyfd) = @_;
                   1426: 
1.365     albertel 1427:     my $userloadpercent=&Apache::lonnet::userload();
1.387     albertel 1428:     &Reply($replyfd, \$userloadpercent, "$cmd:$tail");
1.217     foxr     1429:     
                   1430:     return 1;
                   1431: }
1.263     albertel 1432: &register_handler("userload", \&user_load_handler, 0, 1, 0);
1.217     foxr     1433: 
1.218     foxr     1434: #   Process a request for the authorization type of a user:
                   1435: #   (userauth).
                   1436: #
                   1437: # Parameters:
                   1438: #      $cmd    - the actual keyword that invoked us.
                   1439: #      $tail   - the tail of the request that invoked us.
                   1440: #      $replyfd- File descriptor connected to the client
                   1441: #  Returns:
                   1442: #      1       - Ok to continue processing.
                   1443: #      0       - Program should exit
                   1444: # Implicit outputs:
                   1445: #    The user authorization type is written to the client.
                   1446: #
                   1447: sub user_authorization_type {
                   1448:     my ($cmd, $tail, $replyfd) = @_;
                   1449:    
                   1450:     my $userinput = "$cmd:$tail";
                   1451:    
                   1452:     #  Pull the domain and username out of the command tail.
1.222     foxr     1453:     # and call get_auth_type to determine the authentication type.
1.218     foxr     1454:    
                   1455:     my ($udom,$uname)=split(/:/,$tail);
1.222     foxr     1456:     my $result = &get_auth_type($udom, $uname);
1.218     foxr     1457:     if($result eq "nouser") {
                   1458: 	&Failure( $replyfd, "unknown_user\n", $userinput);
                   1459:     } else {
                   1460: 	#
1.222     foxr     1461: 	# We only want to pass the second field from get_auth_type
1.218     foxr     1462: 	# for ^krb.. otherwise we'll be handing out the encrypted
                   1463: 	# password for internals e.g.
                   1464: 	#
                   1465: 	my ($type,$otherinfo) = split(/:/,$result);
                   1466: 	if($type =~ /^krb/) {
                   1467: 	    $type = $result;
1.269     raeburn  1468: 	} else {
                   1469:             $type .= ':';
                   1470:         }
1.387     albertel 1471: 	&Reply( $replyfd, \$type, $userinput);
1.218     foxr     1472:     }
                   1473:   
                   1474:     return 1;
                   1475: }
                   1476: &register_handler("currentauth", \&user_authorization_type, 1, 1, 0);
                   1477: 
                   1478: #   Process a request by a manager to push a hosts or domain table 
                   1479: #   to us.  We pick apart the command and pass it on to the subs
                   1480: #   that already exist to do this.
                   1481: #
                   1482: # Parameters:
                   1483: #      $cmd    - the actual keyword that invoked us.
                   1484: #      $tail   - the tail of the request that invoked us.
                   1485: #      $client - File descriptor connected to the client
                   1486: #  Returns:
                   1487: #      1       - Ok to continue processing.
                   1488: #      0       - Program should exit
                   1489: # Implicit Output:
                   1490: #    a reply is written to the client.
                   1491: sub push_file_handler {
                   1492:     my ($cmd, $tail, $client) = @_;
1.412     foxr     1493:     &Debug("In push file handler");
1.218     foxr     1494:     my $userinput = "$cmd:$tail";
                   1495: 
                   1496:     # At this time we only know that the IP of our partner is a valid manager
                   1497:     # the code below is a hook to do further authentication (e.g. to resolve
                   1498:     # spoofing).
                   1499: 
                   1500:     my $cert = &GetCertificate($userinput);
1.412     foxr     1501:     if(&ValidManager($cert)) {
                   1502: 	&Debug("Valid manager: $client");
1.218     foxr     1503: 
                   1504: 	# Now presumably we have the bona fides of both the peer host and the
                   1505: 	# process making the request.
                   1506:       
                   1507: 	my $reply = &PushFile($userinput);
1.387     albertel 1508: 	&Reply($client, \$reply, $userinput);
1.218     foxr     1509: 
                   1510:     } else {
1.412     foxr     1511: 	&logthis("push_file_handler $client is not valid");
1.218     foxr     1512: 	&Failure( $client, "refused\n", $userinput);
                   1513:     } 
1.219     foxr     1514:     return 1;
1.218     foxr     1515: }
                   1516: &register_handler("pushfile", \&push_file_handler, 1, 0, 1);
                   1517: 
1.399     raeburn  1518: # The du_handler routine should be considered obsolete and is retained
                   1519: # for communication with legacy servers.  Please see the du2_handler.
1.243     banghart 1520: #
1.399     raeburn  1521: #   du  - list the disk usage of a directory recursively. 
1.243     banghart 1522: #    
                   1523: #   note: stolen code from the ls file handler
                   1524: #   under construction by Rick Banghart 
                   1525: #    .
                   1526: # Parameters:
                   1527: #    $cmd        - The command that dispatched us (du).
                   1528: #    $ududir     - The directory path to list... I'm not sure what this
                   1529: #                  is relative as things like ls:. return e.g.
                   1530: #                  no_such_dir.
                   1531: #    $client     - Socket open on the client.
                   1532: # Returns:
                   1533: #     1 - indicating that the daemon should not disconnect.
                   1534: # Side Effects:
                   1535: #   The reply is written to  $client.
                   1536: #
                   1537: sub du_handler {
                   1538:     my ($cmd, $ududir, $client) = @_;
1.339     albertel 1539:     ($ududir) = split(/:/,$ududir); # Make 'telnet' testing easier.
1.251     foxr     1540:     my $userinput = "$cmd:$ududir";
                   1541: 
1.245     albertel 1542:     if ($ududir=~/\.\./ || $ududir!~m|^/home/httpd/|) {
                   1543: 	&Failure($client,"refused\n","$cmd:$ududir");
                   1544: 	return 1;
                   1545:     }
1.249     foxr     1546:     #  Since $ududir could have some nasties in it,
                   1547:     #  we will require that ududir is a valid
                   1548:     #  directory.  Just in case someone tries to
                   1549:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
                   1550:     #  etc.
                   1551:     #
                   1552:     if (-d $ududir) {
1.292     albertel 1553: 	my $total_size=0;
                   1554: 	my $code=sub { 
                   1555: 	    if ($_=~/\.\d+\./) { return;} 
                   1556: 	    if ($_=~/\.meta$/) { return;}
1.362     albertel 1557: 	    if (-d $_)         { return;}
1.292     albertel 1558: 	    $total_size+=(stat($_))[7];
                   1559: 	};
1.295     raeburn  1560: 	chdir($ududir);
1.292     albertel 1561: 	find($code,$ududir);
                   1562: 	$total_size=int($total_size/1024);
1.387     albertel 1563: 	&Reply($client,\$total_size,"$cmd:$ududir");
1.249     foxr     1564:     } else {
1.251     foxr     1565: 	&Failure($client, "bad_directory:$ududir\n","$cmd:$ududir"); 
1.249     foxr     1566:     }
1.243     banghart 1567:     return 1;
                   1568: }
                   1569: &register_handler("du", \&du_handler, 0, 1, 0);
1.218     foxr     1570: 
1.399     raeburn  1571: # Please also see the du_handler, which is obsoleted by du2. 
                   1572: # du2_handler differs from du_handler in that required path to directory
                   1573: # provided by &propath() is prepended in the handler instead of on the 
                   1574: # client side.
1.239     foxr     1575: #
1.399     raeburn  1576: #   du2  - list the disk usage of a directory recursively.
                   1577: #
                   1578: # Parameters:
                   1579: #    $cmd        - The command that dispatched us (du).
                   1580: #    $tail       - The tail of the request that invoked us.
                   1581: #                  $tail is a : separated list of the following:
                   1582: #                   - $ududir - directory path to list (before prepending)
                   1583: #                   - $getpropath = 1 if &propath() should prepend
                   1584: #                   - $uname - username to use for &propath or user dir
                   1585: #                   - $udom - domain to use for &propath or user dir
                   1586: #                   All are escaped.
                   1587: #    $client     - Socket open on the client.
                   1588: # Returns:
                   1589: #     1 - indicating that the daemon should not disconnect.
                   1590: # Side Effects:
                   1591: #   The reply is written to $client.
                   1592: #
                   1593: 
                   1594: sub du2_handler {
                   1595:     my ($cmd, $tail, $client) = @_;
                   1596:     my ($ududir,$getpropath,$uname,$udom) = map { &unescape($_) } (split(/:/, $tail));
                   1597:     my $userinput = "$cmd:$tail";
                   1598:     if (($ududir=~/\.\./) || (($ududir!~m|^/home/httpd/|) && (!$getpropath))) {
                   1599:         &Failure($client,"refused\n","$cmd:$tail");
                   1600:         return 1;
                   1601:     }
                   1602:     if ($getpropath) {
                   1603:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
                   1604:             $ududir = &propath($udom,$uname).'/'.$ududir;
                   1605:         } else {
                   1606:             &Failure($client,"refused\n","$cmd:$tail");
                   1607:             return 1;
                   1608:         }
                   1609:     }
                   1610:     #  Since $ududir could have some nasties in it,
                   1611:     #  we will require that ududir is a valid
                   1612:     #  directory.  Just in case someone tries to
                   1613:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
                   1614:     #  etc.
                   1615:     #
                   1616:     if (-d $ududir) {
                   1617:         my $total_size=0;
                   1618:         my $code=sub {
                   1619:             if ($_=~/\.\d+\./) { return;}
                   1620:             if ($_=~/\.meta$/) { return;}
                   1621:             if (-d $_)         { return;}
                   1622:             $total_size+=(stat($_))[7];
                   1623:         };
                   1624:         chdir($ududir);
                   1625:         find($code,$ududir);
                   1626:         $total_size=int($total_size/1024);
                   1627:         &Reply($client,\$total_size,"$cmd:$ududir");
                   1628:     } else {
                   1629:         &Failure($client, "bad_directory:$ududir\n","$cmd:$tail");
                   1630:     }
                   1631:     return 1;
                   1632: }
                   1633: &register_handler("du2", \&du2_handler, 0, 1, 0);
                   1634: 
                   1635: #
                   1636: # The ls_handler routine should be considered obsolete and is retained
                   1637: # for communication with legacy servers.  Please see the ls3_handler.
1.280     matthew  1638: #
1.239     foxr     1639: #   ls  - list the contents of a directory.  For each file in the
                   1640: #    selected directory the filename followed by the full output of
                   1641: #    the stat function is returned.  The returned info for each
                   1642: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1643: #
                   1644: #    If the requested path contains /../ or is:
                   1645: #
                   1646: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1647: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1648: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1649: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
                   1650: #    or is:
                   1651: #
1.538     raeburn  1652: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1653: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1654: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1655: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
1.529     raeburn  1656: #
                   1657: #    the response will be "refused".
                   1658: #
1.239     foxr     1659: # Parameters:
                   1660: #    $cmd        - The command that dispatched us (ls).
                   1661: #    $ulsdir     - The directory path to list... I'm not sure what this
                   1662: #                  is relative as things like ls:. return e.g.
                   1663: #                  no_such_dir.
                   1664: #    $client     - Socket open on the client.
                   1665: # Returns:
                   1666: #     1 - indicating that the daemon should not disconnect.
                   1667: # Side Effects:
                   1668: #   The reply is written to  $client.
                   1669: #
                   1670: sub ls_handler {
1.280     matthew  1671:     # obsoleted by ls2_handler
1.239     foxr     1672:     my ($cmd, $ulsdir, $client) = @_;
                   1673: 
                   1674:     my $userinput = "$cmd:$ulsdir";
                   1675: 
                   1676:     my $obs;
                   1677:     my $rights;
                   1678:     my $ulsout='';
                   1679:     my $ulsfn;
1.529     raeburn  1680:     if ($ulsdir =~m{/\.\./}) {
                   1681:         &Failure($client,"refused\n",$userinput);
                   1682:         return 1;
                   1683:     }
1.239     foxr     1684:     if (-e $ulsdir) {
                   1685: 	if(-d $ulsdir) {
1.539     raeburn  1686:             unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1687:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
1.529     raeburn  1688:                 &Failure($client,"refused\n",$userinput);
                   1689:                 return 1;
                   1690:             }
1.239     foxr     1691: 	    if (opendir(LSDIR,$ulsdir)) {
                   1692: 		while ($ulsfn=readdir(LSDIR)) {
1.291     albertel 1693: 		    undef($obs);
                   1694: 		    undef($rights); 
1.239     foxr     1695: 		    my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1696: 		    #We do some obsolete checking here
                   1697: 		    if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   1698: 			open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1699: 			my @obsolete=<FILE>;
                   1700: 			foreach my $obsolete (@obsolete) {
1.301     www      1701: 			    if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
1.239     foxr     1702: 			    if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
                   1703: 			}
                   1704: 		    }
                   1705: 		    $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
                   1706: 		    if($obs eq '1') { $ulsout.="&1"; }
                   1707: 		    else { $ulsout.="&0"; }
                   1708: 		    if($rights eq '1') { $ulsout.="&1:"; }
                   1709: 		    else { $ulsout.="&0:"; }
                   1710: 		}
                   1711: 		closedir(LSDIR);
                   1712: 	    }
                   1713: 	} else {
1.539     raeburn  1714:             unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1715:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
1.529     raeburn  1716:                 &Failure($client,"refused\n",$userinput);
                   1717:                 return 1;
                   1718:             }
1.239     foxr     1719: 	    my @ulsstats=stat($ulsdir);
                   1720: 	    $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1721: 	}
                   1722:     } else {
                   1723: 	$ulsout='no_such_dir';
                   1724:     }
                   1725:     if ($ulsout eq '') { $ulsout='empty'; }
1.387     albertel 1726:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1.239     foxr     1727:     
                   1728:     return 1;
                   1729: 
                   1730: }
                   1731: &register_handler("ls", \&ls_handler, 0, 1, 0);
                   1732: 
1.399     raeburn  1733: # The ls2_handler routine should be considered obsolete and is retained
                   1734: # for communication with legacy servers.  Please see the ls3_handler.
                   1735: # Please also see the ls_handler, which was itself obsoleted by ls2.
1.280     matthew  1736: # ls2_handler differs from ls_handler in that it escapes its return 
                   1737: # values before concatenating them together with ':'s.
                   1738: #
                   1739: #   ls2  - list the contents of a directory.  For each file in the
                   1740: #    selected directory the filename followed by the full output of
                   1741: #    the stat function is returned.  The returned info for each
                   1742: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1743: #
                   1744: #    If the requested path contains /../ or is:
                   1745: #
                   1746: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1747: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1748: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1749: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
                   1750: #    or is:
                   1751: #
1.538     raeburn  1752: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1753: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1754: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1755: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
1.529     raeburn  1756: #
                   1757: #    the response will be "refused".
                   1758: #
1.280     matthew  1759: # Parameters:
                   1760: #    $cmd        - The command that dispatched us (ls).
                   1761: #    $ulsdir     - The directory path to list... I'm not sure what this
                   1762: #                  is relative as things like ls:. return e.g.
                   1763: #                  no_such_dir.
                   1764: #    $client     - Socket open on the client.
                   1765: # Returns:
                   1766: #     1 - indicating that the daemon should not disconnect.
                   1767: # Side Effects:
                   1768: #   The reply is written to  $client.
                   1769: #
                   1770: sub ls2_handler {
                   1771:     my ($cmd, $ulsdir, $client) = @_;
                   1772: 
                   1773:     my $userinput = "$cmd:$ulsdir";
                   1774: 
                   1775:     my $obs;
                   1776:     my $rights;
                   1777:     my $ulsout='';
                   1778:     my $ulsfn;
1.529     raeburn  1779:     if ($ulsdir =~m{/\.\./}) {
                   1780:         &Failure($client,"refused\n",$userinput);
                   1781:         return 1;
                   1782:     }
1.280     matthew  1783:     if (-e $ulsdir) {
                   1784:         if(-d $ulsdir) {
1.539     raeburn  1785:             unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1786:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
1.529     raeburn  1787:                 &Failure($client,"refused\n","$userinput");
                   1788:                 return 1;
                   1789:             }
1.280     matthew  1790:             if (opendir(LSDIR,$ulsdir)) {
                   1791:                 while ($ulsfn=readdir(LSDIR)) {
1.291     albertel 1792:                     undef($obs);
                   1793: 		    undef($rights); 
1.280     matthew  1794:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1795:                     #We do some obsolete checking here
                   1796:                     if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   1797:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1798:                         my @obsolete=<FILE>;
                   1799:                         foreach my $obsolete (@obsolete) {
1.301     www      1800:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
1.280     matthew  1801:                             if($obsolete =~ m|(<copyright>)(default)|) {
                   1802:                                 $rights = 1;
                   1803:                             }
                   1804:                         }
                   1805:                     }
                   1806:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
                   1807:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1808:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1809:                     $ulsout.= &escape($tmp).':';
                   1810:                 }
                   1811:                 closedir(LSDIR);
                   1812:             }
                   1813:         } else {
1.539     raeburn  1814:             unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1815:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
1.529     raeburn  1816:                 &Failure($client,"refused\n",$userinput);
                   1817:                 return 1;
                   1818:             }
1.280     matthew  1819:             my @ulsstats=stat($ulsdir);
                   1820:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1821:         }
                   1822:     } else {
                   1823:         $ulsout='no_such_dir';
                   1824:    }
                   1825:    if ($ulsout eq '') { $ulsout='empty'; }
1.387     albertel 1826:    &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1.280     matthew  1827:    return 1;
                   1828: }
                   1829: &register_handler("ls2", \&ls2_handler, 0, 1, 0);
1.399     raeburn  1830: #
                   1831: #   ls3  - list the contents of a directory.  For each file in the
                   1832: #    selected directory the filename followed by the full output of
                   1833: #    the stat function is returned.  The returned info for each
                   1834: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1835: #
                   1836: #    If the requested path (after prepending) contains /../ or is:
                   1837: #
                   1838: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1839: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1840: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1841: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
1.539     raeburn  1842: #        (d) /home/httpd/html/priv/<domain> and client is the homeserver
1.529     raeburn  1843: #
1.530     raeburn  1844: #    or is:
1.529     raeburn  1845: #
1.538     raeburn  1846: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1847: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1848: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1849: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
                   1850: #        (d) /home/httpd/html/priv/<domain>/<username>/ and client is the homeserver
1.529     raeburn  1851: #
                   1852: #    the response will be "refused".
                   1853: #
1.399     raeburn  1854: # Parameters:
                   1855: #    $cmd        - The command that dispatched us (ls).
                   1856: #    $tail       - The tail of the request that invoked us.
                   1857: #                  $tail is a : separated list of the following:
                   1858: #                   - $ulsdir - directory path to list (before prepending)
                   1859: #                   - $getpropath = 1 if &propath() should prepend
                   1860: #                   - $getuserdir = 1 if path to user dir in lonUsers should
                   1861: #                                     prepend
                   1862: #                   - $alternate_root - path to prepend
                   1863: #                   - $uname - username to use for &propath or user dir
                   1864: #                   - $udom - domain to use for &propath or user dir
                   1865: #            All of these except $getpropath and &getuserdir are escaped.    
                   1866: #                  no_such_dir.
                   1867: #    $client     - Socket open on the client.
                   1868: # Returns:
                   1869: #     1 - indicating that the daemon should not disconnect.
                   1870: # Side Effects:
                   1871: #   The reply is written to $client.
                   1872: #
                   1873: 
                   1874: sub ls3_handler {
                   1875:     my ($cmd, $tail, $client) = @_;
                   1876:     my $userinput = "$cmd:$tail";
                   1877:     my ($ulsdir,$getpropath,$getuserdir,$alternate_root,$uname,$udom) =
                   1878:         split(/:/,$tail);
                   1879:     if (defined($ulsdir)) {
                   1880:         $ulsdir = &unescape($ulsdir);
                   1881:     }
                   1882:     if (defined($alternate_root)) {
                   1883:         $alternate_root = &unescape($alternate_root);
                   1884:     }
                   1885:     if (defined($uname)) {
                   1886:         $uname = &unescape($uname);
                   1887:     }
                   1888:     if (defined($udom)) {
                   1889:         $udom = &unescape($udom);
                   1890:     }
                   1891: 
                   1892:     my $dir_root = $perlvar{'lonDocRoot'};
1.529     raeburn  1893:     if (($getpropath) || ($getuserdir)) {
1.399     raeburn  1894:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
                   1895:             $dir_root = &propath($udom,$uname);
                   1896:             $dir_root =~ s/\/$//;
                   1897:         } else {
1.529     raeburn  1898:             &Failure($client,"refused\n",$userinput);
1.399     raeburn  1899:             return 1;
                   1900:         }
1.400     raeburn  1901:     } elsif ($alternate_root ne '') {
1.399     raeburn  1902:         $dir_root = $alternate_root;
                   1903:     }
1.408     raeburn  1904:     if (($dir_root ne '') && ($dir_root ne '/')) {
1.400     raeburn  1905:         if ($ulsdir =~ /^\//) {
                   1906:             $ulsdir = $dir_root.$ulsdir;
                   1907:         } else {
                   1908:             $ulsdir = $dir_root.'/'.$ulsdir;
                   1909:         }
1.399     raeburn  1910:     }
1.529     raeburn  1911:     if ($ulsdir =~m{/\.\./}) {
                   1912:         &Failure($client,"refused\n",$userinput);
                   1913:         return 1;
                   1914:     }
                   1915:     my $islocal;
                   1916:     my @machine_ids = &Apache::lonnet::current_machine_ids();
                   1917:     if (grep(/^\Q$clientname\E$/,@machine_ids)) {
                   1918:         $islocal = 1;
                   1919:     }
1.399     raeburn  1920:     my $obs;
                   1921:     my $rights;
                   1922:     my $ulsout='';
                   1923:     my $ulsfn;
1.547     raeburn  1924: 
                   1925:     my ($crscheck,$toplevel,$currdom,$currnum,$skip);
                   1926:     unless ($islocal) {
                   1927:         my ($major,$minor) = split(/\./,$clientversion);
                   1928:         if (($major < 2) || ($major == 2 && $minor < 12)) {
                   1929:             $crscheck = 1;
                   1930:         }
                   1931:     }
1.399     raeburn  1932:     if (-e $ulsdir) {
                   1933:         if(-d $ulsdir) {
1.529     raeburn  1934:             unless (($getpropath) || ($getuserdir) ||
1.539     raeburn  1935:                     ($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1936:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles}) ||
                   1937:                     (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain}) && ($islocal))) {
1.529     raeburn  1938:                 &Failure($client,"refused\n",$userinput);
                   1939:                 return 1;
                   1940:             }
1.547     raeburn  1941:             if (($crscheck) &&
                   1942:                 ($ulsdir =~ m{^/home/httpd/html/res/($LONCAPA::match_domain)(/?$|/$LONCAPA::match_courseid)})) {
                   1943:                 ($currdom,my $posscnum) = ($1,$2);
                   1944:                 if (($posscnum eq '') || ($posscnum eq '/')) {
                   1945:                     $toplevel = 1;
                   1946:                 } else {
                   1947:                     $posscnum =~ s{^/+}{};
                   1948:                     if (&LONCAPA::Lond::is_course($currdom,$posscnum)) {
                   1949:                         $skip = 1;
                   1950:                     }
                   1951:                 }
                   1952:             }
                   1953:             if ((!$skip) && (opendir(LSDIR,$ulsdir))) {
1.399     raeburn  1954:                 while ($ulsfn=readdir(LSDIR)) {
1.547     raeburn  1955:                     if (($crscheck) && ($toplevel) && ($currdom ne '') &&
                   1956:                         ($ulsfn =~ /^$LONCAPA::match_courseid$/) && (-d "$ulsdir/$ulsfn")) {
                   1957:                         if (&LONCAPA::Lond::is_course($currdom,$ulsfn)) {
                   1958:                             next;
                   1959:                         }
                   1960:                     }
1.399     raeburn  1961:                     undef($obs);
                   1962:                     undef($rights);
                   1963:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1964:                     #We do some obsolete checking here
                   1965:                     if(-e $ulsdir.'/'.$ulsfn.".meta") {
                   1966:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1967:                         my @obsolete=<FILE>;
                   1968:                         foreach my $obsolete (@obsolete) {
                   1969:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; }
                   1970:                             if($obsolete =~ m|(<copyright>)(default)|) {
                   1971:                                 $rights = 1;
                   1972:                             }
                   1973:                         }
                   1974:                     }
                   1975:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
                   1976:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1977:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1978:                     $ulsout.= &escape($tmp).':';
                   1979:                 }
                   1980:                 closedir(LSDIR);
                   1981:             }
                   1982:         } else {
1.529     raeburn  1983:             unless (($getpropath) || ($getuserdir) ||
1.539     raeburn  1984:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1985:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/}) ||
                   1986:                     (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain/$LONCAPA::match_name/}) && ($islocal))) {
1.529     raeburn  1987:                 &Failure($client,"refused\n",$userinput);
                   1988:                 return 1;
                   1989:             }
1.399     raeburn  1990:             my @ulsstats=stat($ulsdir);
                   1991:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1992:         }
                   1993:     } else {
                   1994:         $ulsout='no_such_dir';
1.400     raeburn  1995:     }
                   1996:     if ($ulsout eq '') { $ulsout='empty'; }
                   1997:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
                   1998:     return 1;
1.399     raeburn  1999: }
                   2000: &register_handler("ls3", \&ls3_handler, 0, 1, 0);
1.280     matthew  2001: 
1.477     raeburn  2002: sub read_lonnet_global {
                   2003:     my ($cmd,$tail,$client) = @_;
                   2004:     my $userinput = "$cmd:$tail";
                   2005:     my $requested = &Apache::lonnet::thaw_unescape($tail);
                   2006:     my $result;
1.480     raeburn  2007:     my %packagevars = (
                   2008:                         spareid => \%Apache::lonnet::spareid,
                   2009:                         perlvar => \%Apache::lonnet::perlvar,
                   2010:                       );
                   2011:     my %limit_to = (
                   2012:                     perlvar => {
1.531     raeburn  2013:                                  lonOtherAuthen  => 1,
                   2014:                                  lonBalancer     => 1,
                   2015:                                  lonVersion      => 1,
                   2016:                                  lonAdmEMail     => 1,
                   2017:                                  lonSupportEMail => 1,  
                   2018:                                  lonSysEMail     => 1,
                   2019:                                  lonHostID       => 1,
                   2020:                                  lonRole         => 1,
                   2021:                                  lonDefDomain    => 1,
                   2022:                                  lonLoadLim      => 1,
                   2023:                                  lonUserLoadLim  => 1,
1.480     raeburn  2024:                                }
                   2025:                   );
1.477     raeburn  2026:     if (ref($requested) eq 'HASH') {
                   2027:         foreach my $what (keys(%{$requested})) {
                   2028:             my $response;
1.480     raeburn  2029:             my $items = {};
                   2030:             if (exists($packagevars{$what})) {
                   2031:                 if (ref($limit_to{$what}) eq 'HASH') {
                   2032:                     foreach my $varname (keys(%{$packagevars{$what}})) {
                   2033:                         if ($limit_to{$what}{$varname}) {
                   2034:                             $items->{$varname} = $packagevars{$what}{$varname};
                   2035:                         }
                   2036:                     }
                   2037:                 } else {
                   2038:                     $items = $packagevars{$what};
1.477     raeburn  2039:                 }
1.480     raeburn  2040:                 if ($what eq 'perlvar') {
                   2041:                     if (!exists($packagevars{$what}{'lonBalancer'})) {
1.570     raeburn  2042:                         if ($dist =~ /^(centos|rhes|fedora|scientific|oracle|rocky|alma)/) {
1.480     raeburn  2043:                             my $othervarref=LONCAPA::Configuration::read_conf('httpd.conf');
                   2044:                             if (ref($othervarref) eq 'HASH') {
                   2045:                                 $items->{'lonBalancer'} = $othervarref->{'lonBalancer'};
                   2046:                             }
                   2047:                         }
                   2048:                     }
1.477     raeburn  2049:                 }
1.480     raeburn  2050:                 $response = &Apache::lonnet::freeze_escape($items);
1.477     raeburn  2051:             }
1.478     raeburn  2052:             $result .= &escape($what).'='.$response.'&';
1.477     raeburn  2053:         }
                   2054:     }
                   2055:     $result =~ s/\&$//;
                   2056:     &Reply($client,\$result,$userinput);
                   2057:     return 1;
                   2058: }
                   2059: &register_handler("readlonnetglobal", \&read_lonnet_global, 0, 1, 0);
                   2060: 
1.479     raeburn  2061: sub server_devalidatecache_handler {
                   2062:     my ($cmd,$tail,$client) = @_;
                   2063:     my $userinput = "$cmd:$tail";
1.503     raeburn  2064:     my $items = &unescape($tail);
                   2065:     my @cached = split(/\&/,$items);
                   2066:     foreach my $key (@cached) {
                   2067:         if ($key =~ /:/) {
                   2068:             my ($name,$id) = map { &unescape($_); } split(/:/,$key);
                   2069:             &Apache::lonnet::devalidate_cache_new($name,$id);
                   2070:         }
                   2071:     }
1.479     raeburn  2072:     my $result = 'ok';
                   2073:     &Reply($client,\$result,$userinput);
                   2074:     return 1;
                   2075: }
1.481     raeburn  2076: &register_handler("devalidatecache", \&server_devalidatecache_handler, 0, 1, 0);
1.479     raeburn  2077: 
1.410     raeburn  2078: sub server_timezone_handler {
                   2079:     my ($cmd,$tail,$client) = @_;
                   2080:     my $userinput = "$cmd:$tail";
                   2081:     my $timezone;
                   2082:     my $clockfile = '/etc/sysconfig/clock'; # Fedora/CentOS/SuSE
                   2083:     my $tzfile = '/etc/timezone'; # Debian/Ubuntu
                   2084:     if (-e $clockfile) {
                   2085:         if (open(my $fh,"<$clockfile")) {
                   2086:             while (<$fh>) {
                   2087:                 next if (/^[\#\s]/);
                   2088:                 if (/^(?:TIME)?ZONE\s*=\s*['"]?\s*([\w\/]+)/) {
                   2089:                     $timezone = $1;
                   2090:                     last;
                   2091:                 }
                   2092:             }
                   2093:             close($fh);
                   2094:         }
                   2095:     } elsif (-e $tzfile) {
                   2096:         if (open(my $fh,"<$tzfile")) {
                   2097:             $timezone = <$fh>;
                   2098:             close($fh);
                   2099:             chomp($timezone);
                   2100:             if ($timezone =~ m{^Etc/(\w+)$}) {
                   2101:                 $timezone = $1;
                   2102:             }
                   2103:         }
                   2104:     }
                   2105:     &Reply($client,\$timezone,$userinput); # This supports debug logging.
                   2106:     return 1;
                   2107: }
                   2108: &register_handler("servertimezone", \&server_timezone_handler, 0, 1, 0);
                   2109: 
1.413     raeburn  2110: sub server_loncaparev_handler {
                   2111:     my ($cmd,$tail,$client) = @_;
                   2112:     my $userinput = "$cmd:$tail";
                   2113:     &Reply($client,\$perlvar{'lonVersion'},$userinput);
                   2114:     return 1;
                   2115: }
                   2116: &register_handler("serverloncaparev", \&server_loncaparev_handler, 0, 1, 0);
                   2117: 
1.448     raeburn  2118: sub server_homeID_handler {
                   2119:     my ($cmd,$tail,$client) = @_;
                   2120:     my $userinput = "$cmd:$tail";
                   2121:     &Reply($client,\$perlvar{'lonHostID'},$userinput);
                   2122:     return 1;
                   2123: }
                   2124: &register_handler("serverhomeID", \&server_homeID_handler, 0, 1, 0);
                   2125: 
1.471     raeburn  2126: sub server_distarch_handler {
                   2127:     my ($cmd,$tail,$client) = @_;
                   2128:     my $userinput = "$cmd:$tail";
                   2129:     my $reply = &distro_and_arch();
                   2130:     &Reply($client,\$reply,$userinput);
                   2131:     return 1;
                   2132: }
                   2133: &register_handler("serverdistarch", \&server_distarch_handler, 0, 1, 0);
                   2134: 
1.523     raeburn  2135: sub server_certs_handler {
                   2136:     my ($cmd,$tail,$client) = @_;
                   2137:     my $userinput = "$cmd:$tail";
1.548     raeburn  2138:     my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
                   2139:     my $result = &LONCAPA::Lond::server_certs(\%perlvar,$perlvar{'lonHostID'},$hostname);
1.523     raeburn  2140:     &Reply($client,\$result,$userinput);
                   2141:     return;
                   2142: }
                   2143: &register_handler("servercerts", \&server_certs_handler, 0, 1, 0);
                   2144: 
1.218     foxr     2145: #   Process a reinit request.  Reinit requests that either
                   2146: #   lonc or lond be reinitialized so that an updated 
                   2147: #   host.tab or domain.tab can be processed.
                   2148: #
                   2149: # Parameters:
                   2150: #      $cmd    - the actual keyword that invoked us.
                   2151: #      $tail   - the tail of the request that invoked us.
                   2152: #      $client - File descriptor connected to the client
                   2153: #  Returns:
                   2154: #      1       - Ok to continue processing.
                   2155: #      0       - Program should exit
                   2156: #  Implicit output:
                   2157: #     a reply is sent to the client.
                   2158: #
                   2159: sub reinit_process_handler {
                   2160:     my ($cmd, $tail, $client) = @_;
                   2161:    
                   2162:     my $userinput = "$cmd:$tail";
                   2163:    
                   2164:     my $cert = &GetCertificate($userinput);
                   2165:     if(&ValidManager($cert)) {
                   2166: 	chomp($userinput);
                   2167: 	my $reply = &ReinitProcess($userinput);
1.387     albertel 2168: 	&Reply( $client,  \$reply, $userinput);
1.218     foxr     2169:     } else {
                   2170: 	&Failure( $client, "refused\n", $userinput);
                   2171:     }
                   2172:     return 1;
                   2173: }
                   2174: &register_handler("reinit", \&reinit_process_handler, 1, 0, 1);
                   2175: 
                   2176: #  Process the editing script for a table edit operation.
                   2177: #  the editing operation must be encrypted and requested by
                   2178: #  a manager host.
                   2179: #
                   2180: # Parameters:
                   2181: #      $cmd    - the actual keyword that invoked us.
                   2182: #      $tail   - the tail of the request that invoked us.
                   2183: #      $client - File descriptor connected to the client
                   2184: #  Returns:
                   2185: #      1       - Ok to continue processing.
                   2186: #      0       - Program should exit
                   2187: #  Implicit output:
                   2188: #     a reply is sent to the client.
                   2189: #
                   2190: sub edit_table_handler {
                   2191:     my ($command, $tail, $client) = @_;
                   2192:    
                   2193:     my $userinput = "$command:$tail";
                   2194: 
                   2195:     my $cert = &GetCertificate($userinput);
                   2196:     if(&ValidManager($cert)) {
                   2197: 	my($filetype, $script) = split(/:/, $tail);
                   2198: 	if (($filetype eq "hosts") || 
                   2199: 	    ($filetype eq "domain")) {
                   2200: 	    if($script ne "") {
                   2201: 		&Reply($client,              # BUGBUG - EditFile
                   2202: 		      &EditFile($userinput), #   could fail.
                   2203: 		      $userinput);
                   2204: 	    } else {
                   2205: 		&Failure($client,"refused\n",$userinput);
                   2206: 	    }
                   2207: 	} else {
                   2208: 	    &Failure($client,"refused\n",$userinput);
                   2209: 	}
                   2210:     } else {
                   2211: 	&Failure($client,"refused\n",$userinput);
                   2212:     }
                   2213:     return 1;
                   2214: }
1.263     albertel 2215: &register_handler("edit", \&edit_table_handler, 1, 0, 1);
1.218     foxr     2216: 
1.220     foxr     2217: #
                   2218: #   Authenticate a user against the LonCAPA authentication
                   2219: #   database.  Note that there are several authentication
                   2220: #   possibilities:
                   2221: #   - unix     - The user can be authenticated against the unix
                   2222: #                password file.
                   2223: #   - internal - The user can be authenticated against a purely 
                   2224: #                internal per user password file.
                   2225: #   - kerberos - The user can be authenticated against either a kerb4 or kerb5
                   2226: #                ticket granting authority.
                   2227: #   - user     - The person tailoring LonCAPA can supply a user authentication
                   2228: #                mechanism that is per system.
                   2229: #
                   2230: # Parameters:
                   2231: #    $cmd      - The command that got us here.
                   2232: #    $tail     - Tail of the command (remaining parameters).
                   2233: #    $client   - File descriptor connected to client.
                   2234: # Returns
                   2235: #     0        - Requested to exit, caller should shut down.
                   2236: #     1        - Continue processing.
                   2237: # Implicit inputs:
                   2238: #    The authentication systems describe above have their own forms of implicit
                   2239: #    input into the authentication process that are described above.
                   2240: #
                   2241: sub authenticate_handler {
                   2242:     my ($cmd, $tail, $client) = @_;
                   2243: 
                   2244:     
                   2245:     #  Regenerate the full input line 
                   2246:     
                   2247:     my $userinput  = $cmd.":".$tail;
                   2248:     
                   2249:     #  udom    - User's domain.
                   2250:     #  uname   - Username.
                   2251:     #  upass   - User's password.
1.396     raeburn  2252:     #  checkdefauth - Pass to validate_user() to try authentication
                   2253:     #                 with default auth type(s) if no user account.
1.447     raeburn  2254:     #  clientcancheckhost - Passed by clients with functionality in lonauth.pm
                   2255:     #                       to check if session can be hosted.
1.220     foxr     2256:     
1.447     raeburn  2257:     my ($udom, $uname, $upass, $checkdefauth, $clientcancheckhost)=split(/:/,$tail);
1.399     raeburn  2258:     &Debug(" Authenticate domain = $udom, user = $uname, password = $upass,  checkdefauth = $checkdefauth");
1.220     foxr     2259:     chomp($upass);
                   2260:     $upass=&unescape($upass);
                   2261: 
1.396     raeburn  2262:     my $pwdcorrect = &validate_user($udom,$uname,$upass,$checkdefauth);
1.220     foxr     2263:     if($pwdcorrect) {
1.447     raeburn  2264:         my $canhost = 1;
                   2265:         unless ($clientcancheckhost) {
1.448     raeburn  2266:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   2267:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.452     raeburn  2268:             my @intdoms;
                   2269:             my $internet_names = &Apache::lonnet::get_internet_names($clientname);
                   2270:             if (ref($internet_names) eq 'ARRAY') {
                   2271:                 @intdoms = @{$internet_names};
                   2272:             }
1.448     raeburn  2273:             unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
1.447     raeburn  2274:                 my ($remote,$hosted);
                   2275:                 my $remotesession = &get_usersession_config($udom,'remotesession');
                   2276:                 if (ref($remotesession) eq 'HASH') {
1.525     raeburn  2277:                     $remote = $remotesession->{'remote'};
1.447     raeburn  2278:                 }
1.448     raeburn  2279:                 my $hostedsession = &get_usersession_config($clienthomedom,'hostedsession');
1.447     raeburn  2280:                 if (ref($hostedsession) eq 'HASH') {
                   2281:                     $hosted = $hostedsession->{'hosted'};
                   2282:                 }
1.448     raeburn  2283:                 $canhost = &Apache::lonnet::can_host_session($udom,$clientname,
1.492     droeschl 2284:                                                              $clientversion,
1.447     raeburn  2285:                                                              $remote,$hosted);
                   2286:             }
                   2287:         }
                   2288:         if ($canhost) {               
                   2289:             &Reply( $client, "authorized\n", $userinput);
                   2290:         } else {
                   2291:             &Reply( $client, "not_allowed_to_host\n", $userinput);
                   2292:         }
1.220     foxr     2293: 	#
                   2294: 	#  Bad credentials: Failed to authorize
                   2295: 	#
                   2296:     } else {
                   2297: 	&Failure( $client, "non_authorized\n", $userinput);
                   2298:     }
                   2299: 
                   2300:     return 1;
                   2301: }
1.263     albertel 2302: &register_handler("auth", \&authenticate_handler, 1, 1, 0);
1.214     foxr     2303: 
1.222     foxr     2304: #
                   2305: #   Change a user's password.  Note that this function is complicated by
                   2306: #   the fact that a user may be authenticated in more than one way:
                   2307: #   At present, we are not able to change the password for all types of
                   2308: #   authentication methods.  Only for:
                   2309: #      unix    - unix password or shadow passoword style authentication.
                   2310: #      local   - Locally written authentication mechanism.
                   2311: #   For now, kerb4 and kerb5 password changes are not supported and result
                   2312: #   in an error.
                   2313: # FUTURE WORK:
                   2314: #    Support kerberos passwd changes?
                   2315: # Parameters:
                   2316: #    $cmd      - The command that got us here.
                   2317: #    $tail     - Tail of the command (remaining parameters).
                   2318: #    $client   - File descriptor connected to client.
                   2319: # Returns
                   2320: #     0        - Requested to exit, caller should shut down.
                   2321: #     1        - Continue processing.
                   2322: # Implicit inputs:
                   2323: #    The authentication systems describe above have their own forms of implicit
                   2324: #    input into the authentication process that are described above.
                   2325: sub change_password_handler {
                   2326:     my ($cmd, $tail, $client) = @_;
                   2327: 
                   2328:     my $userinput = $cmd.":".$tail;           # Reconstruct client's string.
                   2329: 
                   2330:     #
                   2331:     #  udom  - user's domain.
                   2332:     #  uname - Username.
                   2333:     #  upass - Current password.
                   2334:     #  npass - New password.
1.346     raeburn  2335:     #  context - Context in which this was called 
                   2336:     #            (preferences or reset_by_email).
1.428     raeburn  2337:     #  lonhost - HostID of server where request originated 
1.222     foxr     2338:    
1.428     raeburn  2339:     my ($udom,$uname,$upass,$npass,$context,$lonhost)=split(/:/,$tail);
1.222     foxr     2340: 
                   2341:     $upass=&unescape($upass);
                   2342:     $npass=&unescape($npass);
                   2343:     &Debug("Trying to change password for $uname");
                   2344: 
                   2345:     # First require that the user can be authenticated with their
1.346     raeburn  2346:     # old password unless context was 'reset_by_email':
                   2347:     
1.428     raeburn  2348:     my ($validated,$failure);
1.346     raeburn  2349:     if ($context eq 'reset_by_email') {
1.428     raeburn  2350:         if ($lonhost eq '') {
                   2351:             $failure = 'invalid_client';
                   2352:         } else {
                   2353:             $validated = 1;
                   2354:         }
1.346     raeburn  2355:     } else {
                   2356:         $validated = &validate_user($udom, $uname, $upass);
                   2357:     }
1.222     foxr     2358:     if($validated) {
                   2359: 	my $realpasswd  = &get_auth_type($udom, $uname); # Defined since authd.
                   2360: 	my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
1.558     raeburn  2361:         my $notunique;
1.222     foxr     2362: 	if ($howpwd eq 'internal') {
                   2363: 	    &Debug("internal auth");
1.518     raeburn  2364:             my $ncpass = &hash_passwd($udom,$npass);
1.558     raeburn  2365:             my (undef,$method,@rest) = split(/!/,$contentpwd);
                   2366:             if ($method eq 'bcrypt') {
                   2367:                 my %passwdconf = &Apache::lonnet::get_passwdconf($udom);
                   2368:                 if (($passwdconf{'numsaved'}) && ($passwdconf{'numsaved'} =~ /^\d+$/)) {
                   2369:                     my @oldpasswds;
                   2370:                     my $userpath = &propath($udom,$uname);
                   2371:                     my $fullpath = $userpath.'/oldpasswds';
                   2372:                     if (-d $userpath) {
                   2373:                         my @oldfiles;
                   2374:                         if (-e $fullpath) {
                   2375:                             if (opendir(my $dir,$fullpath)) {
                   2376:                                 (@oldfiles) = grep(/^\d+$/,readdir($dir));
                   2377:                                 closedir($dir);
                   2378:                             }
                   2379:                             if (@oldfiles) {
                   2380:                                 @oldfiles = sort { $b <=> $a } (@oldfiles);
                   2381:                                 my $numremoved = 0;
                   2382:                                 for (my $i=0; $i<@oldfiles; $i++) {
                   2383:                                     if ($i>=$passwdconf{'numsaved'}) {
                   2384:                                         if (-f "$fullpath/$oldfiles[$i]") {
                   2385:                                             if (unlink("$fullpath/$oldfiles[$i]")) {
                   2386:                                                 $numremoved ++;
                   2387:                                             }
                   2388:                                         }
                   2389:                                     } elsif (open(my $fh,'<',"$fullpath/$oldfiles[$i]")) {
                   2390:                                         while (my $line = <$fh>) {
                   2391:                                             push(@oldpasswds,$line);
                   2392:                                         }
                   2393:                                         close($fh);
                   2394:                                     }
                   2395:                                 }
                   2396:                                 if ($numremoved) {
                   2397:                                     &logthis("unlinked $numremoved old password files for $uname:$udom");
                   2398:                                 }
                   2399:                             }
                   2400:                         }
                   2401:                         push(@oldpasswds,$contentpwd);
                   2402:                         foreach my $item (@oldpasswds) {
                   2403:                             my (undef,$method,@rest) = split(/!/,$item);
                   2404:                             if ($method eq 'bcrypt') {
                   2405:                                 my $result = &hash_passwd($udom,$npass,@rest);
                   2406:                                 if ($result eq $item) {
                   2407:                                     $notunique = 1;
                   2408:                                     last;
                   2409:                                 }
                   2410:                             }
                   2411:                         }
                   2412:                         unless ($notunique) {
                   2413:                             unless (-e $fullpath) {
                   2414:                                 if (&mkpath("$fullpath/")) {
                   2415:                                     chmod(0700,$fullpath);
                   2416:                                 }
                   2417:                             }
                   2418:                             if (-d $fullpath) {
                   2419:                                 my $now = time;
                   2420:                                 if (open(my $fh,'>',"$fullpath/$now")) {
                   2421:                                     print $fh $contentpwd;
                   2422:                                     close($fh);
                   2423:                                     chmod(0400,"$fullpath/$now");
                   2424:                                 }
                   2425:                             }
                   2426:                         }
                   2427:                     }
                   2428:                 }
                   2429:             }
                   2430:             if ($notunique) {
                   2431:                 my $msg="Result of password change for $uname:$udom - password matches one used before";
                   2432:                 if ($lonhost) {
                   2433:                     $msg .= " - request originated from: $lonhost";
                   2434:                 }
                   2435:                 &logthis($msg);
                   2436:                 &Reply($client, "prioruse\n", $userinput);
                   2437: 	    } elsif (&rewrite_password_file($udom, $uname, "internal:$ncpass")) {
1.428     raeburn  2438: 		my $msg="Result of password change for $uname: pwchange_success";
                   2439:                 if ($lonhost) {
                   2440:                     $msg .= " - request originated from: $lonhost";
                   2441:                 }
                   2442:                 &logthis($msg);
1.518     raeburn  2443:                 &update_passwd_history($uname,$udom,$howpwd,$context);
1.222     foxr     2444: 		&Reply($client, "ok\n", $userinput);
                   2445: 	    } else {
                   2446: 		&logthis("Unable to open $uname passwd "               
                   2447: 			 ."to change password");
                   2448: 		&Failure( $client, "non_authorized\n",$userinput);
                   2449: 	    }
1.346     raeburn  2450: 	} elsif ($howpwd eq 'unix' && $context ne 'reset_by_email') {
1.287     foxr     2451: 	    my $result = &change_unix_password($uname, $npass);
1.518     raeburn  2452:             if ($result eq 'ok') {
                   2453:                 &update_passwd_history($uname,$udom,$howpwd,$context);
1.561     raeburn  2454:             }
1.222     foxr     2455: 	    &logthis("Result of password change for $uname: ".
1.287     foxr     2456: 		     $result);
1.387     albertel 2457: 	    &Reply($client, \$result, $userinput);
1.222     foxr     2458: 	} else {
                   2459: 	    # this just means that the current password mode is not
                   2460: 	    # one we know how to change (e.g the kerberos auth modes or
                   2461: 	    # locally written auth handler).
                   2462: 	    #
                   2463: 	    &Failure( $client, "auth_mode_error\n", $userinput);
                   2464: 	}  
1.224     foxr     2465:     } else {
1.428     raeburn  2466: 	if ($failure eq '') {
                   2467: 	    $failure = 'non_authorized';
                   2468: 	}
                   2469: 	&Failure( $client, "$failure\n", $userinput);
1.222     foxr     2470:     }
                   2471: 
                   2472:     return 1;
                   2473: }
1.263     albertel 2474: &register_handler("passwd", \&change_password_handler, 1, 1, 0);
1.222     foxr     2475: 
1.518     raeburn  2476: sub hash_passwd {
                   2477:     my ($domain,$plainpass,@rest) = @_;
                   2478:     my ($salt,$cost);
                   2479:     if (@rest) {
                   2480:         $cost = $rest[0];
                   2481:         # salt is first 22 characters, base-64 encoded by bcrypt
                   2482:         my $plainsalt = substr($rest[1],0,22);
                   2483:         $salt = Crypt::Eksblowfish::Bcrypt::de_base64($plainsalt);
                   2484:     } else {
1.533     raeburn  2485:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   2486:         my $defaultcost = $domdefaults{'intauth_cost'};
1.518     raeburn  2487:         if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
                   2488:             $cost = 10;
                   2489:         } else {
                   2490:             $cost = $defaultcost;
                   2491:         }
                   2492:         # Generate random 16-octet base64 salt
                   2493:         $salt = "";
                   2494:         $salt .= pack("C", int rand(256)) for 1..16;
                   2495:     }
                   2496:     my $hash = &Crypt::Eksblowfish::Bcrypt::bcrypt_hash({
                   2497:         key_nul => 1,
                   2498:         cost    => $cost,
                   2499:         salt    => $salt,
                   2500:     }, Digest::SHA::sha512(Encode::encode('UTF-8',$plainpass)));
                   2501: 
                   2502:     my $result = join("!", "", "bcrypt", sprintf("%02d",$cost),
                   2503:                 &Crypt::Eksblowfish::Bcrypt::en_base64($salt).
                   2504:                 &Crypt::Eksblowfish::Bcrypt::en_base64($hash));
                   2505:     return $result;
                   2506: }
                   2507: 
1.225     foxr     2508: #
                   2509: #   Create a new user.  User in this case means a lon-capa user.
                   2510: #   The user must either already exist in some authentication realm
                   2511: #   like kerberos or the /etc/passwd.  If not, a user completely local to
                   2512: #   this loncapa system is created.
                   2513: #
                   2514: # Parameters:
                   2515: #    $cmd      - The command that got us here.
                   2516: #    $tail     - Tail of the command (remaining parameters).
                   2517: #    $client   - File descriptor connected to client.
                   2518: # Returns
                   2519: #     0        - Requested to exit, caller should shut down.
                   2520: #     1        - Continue processing.
                   2521: # Implicit inputs:
                   2522: #    The authentication systems describe above have their own forms of implicit
                   2523: #    input into the authentication process that are described above.
                   2524: sub add_user_handler {
                   2525: 
                   2526:     my ($cmd, $tail, $client) = @_;
                   2527: 
                   2528: 
                   2529:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   2530:     my $userinput = $cmd.":".$tail; # Reconstruct the full request line.
                   2531: 
                   2532:     &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
                   2533: 
                   2534: 
                   2535:     if($udom eq $currentdomainid) { # Reject new users for other domains...
                   2536: 	
                   2537: 	my $oldumask=umask(0077);
                   2538: 	chomp($npass);
                   2539: 	$npass=&unescape($npass);
                   2540: 	my $passfilename  = &password_path($udom, $uname);
                   2541: 	&Debug("Password file created will be:".$passfilename);
                   2542: 	if (-e $passfilename) {
                   2543: 	    &Failure( $client, "already_exists\n", $userinput);
                   2544: 	} else {
                   2545: 	    my $fperror='';
1.264     albertel 2546: 	    if (!&mkpath($passfilename)) {
                   2547: 		$fperror="error: ".($!+0)." mkdir failed while attempting "
                   2548: 		    ."makeuser";
1.225     foxr     2549: 	    }
                   2550: 	    unless ($fperror) {
1.518     raeburn  2551: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
                   2552:                                              $passfilename,'makeuser');
1.390     raeburn  2553: 		&Reply($client,\$result, $userinput);     #BUGBUG - could be fail
1.225     foxr     2554: 	    } else {
1.387     albertel 2555: 		&Failure($client, \$fperror, $userinput);
1.225     foxr     2556: 	    }
                   2557: 	}
                   2558: 	umask($oldumask);
                   2559:     }  else {
                   2560: 	&Failure($client, "not_right_domain\n",
                   2561: 		$userinput);	# Even if we are multihomed.
                   2562:     
                   2563:     }
                   2564:     return 1;
                   2565: 
                   2566: }
                   2567: &register_handler("makeuser", \&add_user_handler, 1, 1, 0);
                   2568: 
                   2569: #
                   2570: #   Change the authentication method of a user.  Note that this may
                   2571: #   also implicitly change the user's password if, for example, the user is
                   2572: #   joining an existing authentication realm.  Known authentication realms at
                   2573: #   this time are:
                   2574: #    internal   - Purely internal password file (only loncapa knows this user)
                   2575: #    local      - Institutionally written authentication module.
                   2576: #    unix       - Unix user (/etc/passwd with or without /etc/shadow).
                   2577: #    kerb4      - kerberos version 4
                   2578: #    kerb5      - kerberos version 5
                   2579: #
                   2580: # Parameters:
                   2581: #    $cmd      - The command that got us here.
                   2582: #    $tail     - Tail of the command (remaining parameters).
                   2583: #    $client   - File descriptor connected to client.
                   2584: # Returns
                   2585: #     0        - Requested to exit, caller should shut down.
                   2586: #     1        - Continue processing.
                   2587: # Implicit inputs:
                   2588: #    The authentication systems describe above have their own forms of implicit
                   2589: #    input into the authentication process that are described above.
1.287     foxr     2590: # NOTE:
                   2591: #   This is also used to change the authentication credential values (e.g. passwd).
                   2592: #   
1.225     foxr     2593: #
                   2594: sub change_authentication_handler {
                   2595: 
                   2596:     my ($cmd, $tail, $client) = @_;
                   2597:    
                   2598:     my $userinput  = "$cmd:$tail";              # Reconstruct user input.
                   2599: 
                   2600:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   2601:     &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
                   2602:     if ($udom ne $currentdomainid) {
                   2603: 	&Failure( $client, "not_right_domain\n", $client);
                   2604:     } else {
                   2605: 	
                   2606: 	chomp($npass);
                   2607: 	
                   2608: 	$npass=&unescape($npass);
1.261     foxr     2609: 	my $oldauth = &get_auth_type($udom, $uname); # Get old auth info.
1.225     foxr     2610: 	my $passfilename = &password_path($udom, $uname);
                   2611: 	if ($passfilename) {	# Not allowed to create a new user!!
1.287     foxr     2612: 	    # If just changing the unix passwd. need to arrange to run
1.502     raeburn  2613: 	    # passwd since otherwise make_passwd_file will fail as 
                   2614: 	    # creation of unix authenticated users is no longer supported
                   2615:             # except from the command line, when running make_domain_coordinator.pl
1.287     foxr     2616: 
                   2617: 	    if(($oldauth =~/^unix/) && ($umode eq "unix")) {
                   2618: 		my $result = &change_unix_password($uname, $npass);
                   2619: 		&logthis("Result of password change for $uname: ".$result);
                   2620: 		if ($result eq "ok") {
1.518     raeburn  2621:                     &update_passwd_history($uname,$udom,$umode,'changeuserauth'); 
1.390     raeburn  2622: 		    &Reply($client, \$result);
1.288     albertel 2623: 		} else {
1.387     albertel 2624: 		    &Failure($client, \$result);
1.287     foxr     2625: 		}
1.288     albertel 2626: 	    } else {
1.518     raeburn  2627: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
                   2628:                                              $passfilename,'changeuserauth');
1.287     foxr     2629: 		#
                   2630: 		#  If the current auth mode is internal, and the old auth mode was
                   2631: 		#  unix, or krb*,  and the user is an author for this domain,
                   2632: 		#  re-run manage_permissions for that role in order to be able
                   2633: 		#  to take ownership of the construction space back to www:www
                   2634: 		#
1.502     raeburn  2635: 
                   2636: 
1.387     albertel 2637: 		&Reply($client, \$result, $userinput);
1.261     foxr     2638: 	    }
                   2639: 	       
                   2640: 
1.225     foxr     2641: 	} else {	       
1.251     foxr     2642: 	    &Failure($client, "non_authorized\n", $userinput); # Fail the user now.
1.225     foxr     2643: 	}
                   2644:     }
                   2645:     return 1;
                   2646: }
                   2647: &register_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
                   2648: 
1.518     raeburn  2649: sub update_passwd_history {
                   2650:     my ($uname,$udom,$umode,$context) = @_;
                   2651:     my $proname=&propath($udom,$uname);
                   2652:     my $now = time;
                   2653:     if (open(my $fh,">>$proname/passwd.log")) {
                   2654:         print $fh "$now:$umode:$context\n";
                   2655:         close($fh);
                   2656:     }
                   2657:     return;
                   2658: }
                   2659: 
1.575   ! raeburn  2660: sub inst_unamemap_check {
        !          2661:     my ($cmd, $tail, $client)   = @_;
        !          2662:     my $userinput               = "$cmd:$tail";
        !          2663:     my %rulecheck;
        !          2664:     my $outcome;
        !          2665:     my ($udom,$uname,@rules) = split(/:/,$tail);
        !          2666:     $udom = &unescape($udom);
        !          2667:     $uname = &unescape($uname);
        !          2668:     @rules = map {&unescape($_);} (@rules);
        !          2669:     eval {
        !          2670:         local($SIG{__DIE__})='DEFAULT';
        !          2671:         $outcome = &localenroll::unamemap_check($udom,$uname,\@rules,\%rulecheck);
        !          2672:     };
        !          2673:     if (!$@) {
        !          2674:         if ($outcome eq 'ok') {
        !          2675:             my $result='';
        !          2676:             foreach my $key (keys(%rulecheck)) {
        !          2677:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
        !          2678:             }
        !          2679:             &Reply($client,\$result,$userinput);
        !          2680:         } else {
        !          2681:             &Reply($client,"error\n", $userinput);
        !          2682:         }
        !          2683:     } else {
        !          2684:         &Failure($client,"unknown_cmd\n",$userinput);
        !          2685:     }
        !          2686: }
        !          2687: &register_handler("instunamemapcheck",\&inst_unamemap_check,0,1,0);
        !          2688: 
        !          2689: 
1.225     foxr     2690: #
                   2691: #   Determines if this is the home server for a user.  The home server
                   2692: #   for a user will have his/her lon-capa passwd file.  Therefore all we need
                   2693: #   to do is determine if this file exists.
                   2694: #
                   2695: # Parameters:
                   2696: #    $cmd      - The command that got us here.
                   2697: #    $tail     - Tail of the command (remaining parameters).
                   2698: #    $client   - File descriptor connected to client.
                   2699: # Returns
                   2700: #     0        - Requested to exit, caller should shut down.
                   2701: #     1        - Continue processing.
                   2702: # Implicit inputs:
                   2703: #    The authentication systems describe above have their own forms of implicit
                   2704: #    input into the authentication process that are described above.
                   2705: #
                   2706: sub is_home_handler {
                   2707:     my ($cmd, $tail, $client) = @_;
                   2708:    
                   2709:     my $userinput  = "$cmd:$tail";
                   2710:    
                   2711:     my ($udom,$uname)=split(/:/,$tail);
                   2712:     chomp($uname);
                   2713:     my $passfile = &password_filename($udom, $uname);
                   2714:     if($passfile) {
                   2715: 	&Reply( $client, "found\n", $userinput);
                   2716:     } else {
                   2717: 	&Failure($client, "not_found\n", $userinput);
                   2718:     }
                   2719:     return 1;
                   2720: }
                   2721: &register_handler("home", \&is_home_handler, 0,1,0);
                   2722: 
                   2723: #
1.434     www      2724: #   Process an update request for a resource.
                   2725: #   A resource has been modified that we hold a subscription to.
1.225     foxr     2726: #   If the resource is not local, then we must update, or at least invalidate our
                   2727: #   cached copy of the resource. 
                   2728: # Parameters:
                   2729: #    $cmd      - The command that got us here.
                   2730: #    $tail     - Tail of the command (remaining parameters).
                   2731: #    $client   - File descriptor connected to client.
                   2732: # Returns
                   2733: #     0        - Requested to exit, caller should shut down.
                   2734: #     1        - Continue processing.
                   2735: # Implicit inputs:
                   2736: #    The authentication systems describe above have their own forms of implicit
                   2737: #    input into the authentication process that are described above.
                   2738: #
                   2739: sub update_resource_handler {
                   2740: 
                   2741:     my ($cmd, $tail, $client) = @_;
                   2742:    
                   2743:     my $userinput = "$cmd:$tail";
                   2744:    
                   2745:     my $fname= $tail;		# This allows interactive testing
                   2746: 
                   2747: 
                   2748:     my $ownership=ishome($fname);
                   2749:     if ($ownership eq 'not_owner') {
                   2750: 	if (-e $fname) {
1.434     www      2751:             # Delete preview file, if exists
                   2752:             unlink("$fname.tmp");
                   2753:             # Get usage stats
1.225     foxr     2754: 	    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
                   2755: 		$atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
                   2756: 	    my $now=time;
                   2757: 	    my $since=$now-$atime;
1.434     www      2758:             # If the file has not been used within lonExpire seconds,
                   2759:             # unsubscribe from it and delete local copy
1.225     foxr     2760: 	    if ($since>$perlvar{'lonExpire'}) {
1.365     albertel 2761: 		my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
1.308     albertel 2762: 		&devalidate_meta_cache($fname);
1.225     foxr     2763: 		unlink("$fname");
1.334     albertel 2764: 		unlink("$fname.meta");
1.225     foxr     2765: 	    } else {
1.434     www      2766:             # Yes, this is in active use. Get a fresh copy. Since it might be in
                   2767:             # very active use and huge (like a movie), copy it to "in.transfer" filename first.
1.225     foxr     2768: 		my $transname="$fname.in.transfer";
1.365     albertel 2769: 		my $remoteurl=&Apache::lonnet::reply("sub:$fname","$clientname");
1.225     foxr     2770: 		my $response;
1.537     raeburn  2771: # FIXME: cannot replicate files that take more than two minutes to transfer -- needs checking now 1200s timeout used
                   2772: # for LWP request.
                   2773: 		my $request=new HTTP::Request('GET',"$remoteurl");
                   2774:                 $response=&LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,0,1);
1.225     foxr     2775: 		if ($response->is_error()) {
1.541     raeburn  2776:                     my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
                   2777:                     &devalidate_meta_cache($fname);
                   2778:                     if (-e $transname) {
                   2779:                         unlink($transname);
                   2780:                     }
                   2781:                     unlink($fname);
1.225     foxr     2782: 		    my $message=$response->status_line;
                   2783: 		    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   2784: 		} else {
                   2785: 		    if ($remoteurl!~/\.meta$/) {
1.537     raeburn  2786: 			my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2787:                         my $mresponse = &LONCAPA::LWPReq::makerequest($clientname,$mrequest,$fname.'.meta',\%perlvar,120,0,1);
                   2788: 			if ($mresponse->is_error()) {
                   2789: 			    unlink($fname.'.meta');
1.225     foxr     2790: 			}
                   2791: 		    }
1.434     www      2792:                     # we successfully transfered, copy file over to real name
1.225     foxr     2793: 		    rename($transname,$fname);
1.308     albertel 2794: 		    &devalidate_meta_cache($fname);
1.225     foxr     2795: 		}
                   2796: 	    }
                   2797: 	    &Reply( $client, "ok\n", $userinput);
                   2798: 	} else {
                   2799: 	    &Failure($client, "not_found\n", $userinput);
                   2800: 	}
                   2801:     } else {
                   2802: 	&Failure($client, "rejected\n", $userinput);
                   2803:     }
                   2804:     return 1;
                   2805: }
                   2806: &register_handler("update", \&update_resource_handler, 0 ,1, 0);
                   2807: 
1.308     albertel 2808: sub devalidate_meta_cache {
                   2809:     my ($url) = @_;
                   2810:     use Cache::Memcached;
                   2811:     my $memcache = new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.365     albertel 2812:     $url = &Apache::lonnet::declutter($url);
1.308     albertel 2813:     $url =~ s-\.meta$--;
                   2814:     my $id = &escape('meta:'.$url);
                   2815:     $memcache->delete($id);
                   2816: }
                   2817: 
1.225     foxr     2818: #
1.226     foxr     2819: #   Fetch a user file from a remote server to the user's home directory
                   2820: #   userfiles subdir.
1.225     foxr     2821: # Parameters:
                   2822: #    $cmd      - The command that got us here.
                   2823: #    $tail     - Tail of the command (remaining parameters).
                   2824: #    $client   - File descriptor connected to client.
                   2825: # Returns
                   2826: #     0        - Requested to exit, caller should shut down.
                   2827: #     1        - Continue processing.
                   2828: #
                   2829: sub fetch_user_file_handler {
                   2830: 
                   2831:     my ($cmd, $tail, $client) = @_;
                   2832: 
                   2833:     my $userinput = "$cmd:$tail";
                   2834:     my $fname           = $tail;
1.232     foxr     2835:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
1.225     foxr     2836:     my $udir=&propath($udom,$uname).'/userfiles';
                   2837:     unless (-e $udir) {
                   2838: 	mkdir($udir,0770); 
                   2839:     }
1.232     foxr     2840:     Debug("fetch user file for $fname");
1.225     foxr     2841:     if (-e $udir) {
                   2842: 	$ufile=~s/^[\.\~]+//;
1.232     foxr     2843: 
                   2844: 	# IF necessary, create the path right down to the file.
                   2845: 	# Note that any regular files in the way of this path are
                   2846: 	# wiped out to deal with some earlier folly of mine.
                   2847: 
1.267     raeburn  2848: 	if (!&mkpath($udir.'/'.$ufile)) {
1.264     albertel 2849: 	    &Failure($client, "unable_to_create\n", $userinput);	    
1.232     foxr     2850: 	}
                   2851: 
1.225     foxr     2852: 	my $destname=$udir.'/'.$ufile;
                   2853: 	my $transname=$udir.'/'.$ufile.'.in.transit';
1.476     raeburn  2854:         my $clientprotocol=$Apache::lonnet::protocol{$clientname};
                   2855:         $clientprotocol = 'http' if ($clientprotocol ne 'https');
1.486     raeburn  2856: 	my $clienthost = &Apache::lonnet::hostname($clientname);
                   2857: 	my $remoteurl=$clientprotocol.'://'.$clienthost.'/userfiles/'.$fname;
1.225     foxr     2858: 	my $response;
1.232     foxr     2859: 	Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
1.537     raeburn  2860: 	my $request=new HTTP::Request('GET',"$remoteurl");
                   2861:         my $verifycert = 1;
                   2862:         my @machine_ids = &Apache::lonnet::current_machine_ids();
                   2863:         if (grep(/^\Q$clientname\E$/,@machine_ids)) {
                   2864:             $verifycert = 0;
                   2865:         }
                   2866:         $response = &LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,$verifycert);
1.225     foxr     2867: 	if ($response->is_error()) {
                   2868: 	    unlink($transname);
                   2869: 	    my $message=$response->status_line;
                   2870: 	    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   2871: 	    &Failure($client, "failed\n", $userinput);
                   2872: 	} else {
1.232     foxr     2873: 	    Debug("Renaming $transname to $destname");
1.225     foxr     2874: 	    if (!rename($transname,$destname)) {
                   2875: 		&logthis("Unable to move $transname to $destname");
                   2876: 		unlink($transname);
                   2877: 		&Failure($client, "failed\n", $userinput);
                   2878: 	    } else {
1.495     raeburn  2879:                 if ($fname =~ /^default.+\.(page|sequence)$/) {
                   2880:                     my ($major,$minor) = split(/\./,$clientversion);
                   2881:                     if (($major < 2) || ($major == 2 && $minor < 11)) {
                   2882:                         my $now = time;
                   2883:                         &Apache::lonnet::do_cache_new('crschange',$udom.'_'.$uname,$now,600);
                   2884:                         my $key = &escape('internal.contentchange');
                   2885:                         my $what = "$key=$now";
                   2886:                         my $hashref = &tie_user_hash($udom,$uname,'environment',
                   2887:                                                      &GDBM_WRCREAT(),"P",$what);
                   2888:                         if ($hashref) {
                   2889:                             $hashref->{$key}=$now;
                   2890:                             if (!&untie_user_hash($hashref)) {
                   2891:                                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
                   2892:                                          "when updating internal.contentchange");
                   2893:                             }
                   2894:                         }
                   2895:                     }
                   2896:                 }
1.225     foxr     2897: 		&Reply($client, "ok\n", $userinput);
                   2898: 	    }
                   2899: 	}   
                   2900:     } else {
                   2901: 	&Failure($client, "not_home\n", $userinput);
                   2902:     }
                   2903:     return 1;
                   2904: }
                   2905: &register_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
                   2906: 
1.226     foxr     2907: #
                   2908: #   Remove a file from a user's home directory userfiles subdirectory.
                   2909: # Parameters:
                   2910: #    cmd   - the Lond request keyword that got us here.
                   2911: #    tail  - the part of the command past the keyword.
                   2912: #    client- File descriptor connected with the client.
                   2913: #
                   2914: # Returns:
                   2915: #    1    - Continue processing.
                   2916: sub remove_user_file_handler {
                   2917:     my ($cmd, $tail, $client) = @_;
                   2918: 
                   2919:     my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2920: 
                   2921:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2922:     if ($ufile =~m|/\.\./|) {
                   2923: 	# any files paths with /../ in them refuse 
                   2924: 	# to deal with
                   2925: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2926:     } else {
                   2927: 	my $udir = &propath($udom,$uname);
                   2928: 	if (-e $udir) {
                   2929: 	    my $file=$udir.'/userfiles/'.$ufile;
                   2930: 	    if (-e $file) {
1.253     foxr     2931: 		#
                   2932: 		#   If the file is a regular file unlink is fine...
1.520     raeburn  2933: 		#   However it's possible the client wants a dir 
                   2934: 		#   removed, in which case rmdir is more appropriate.
                   2935: 		#   Note: rmdir will only remove an empty directory.
1.253     foxr     2936: 		#
1.240     banghart 2937: 	        if (-f $file){
1.241     albertel 2938: 		    unlink($file);
1.520     raeburn  2939:                     # for html files remove the associated .bak file 
                   2940:                     # which may have been created by the editor.
                   2941:                     if ($ufile =~ m{^((docs|supplemental)/(?:\d+|default)/\d+(?:|/.+)/)[^/]+\.x?html?$}i) {
                   2942:                         my $path = $1;
                   2943:                         if (-e $file.'.bak') {
                   2944:                             unlink($file.'.bak');
                   2945:                         }
                   2946:                     }
1.241     albertel 2947: 		} elsif(-d $file) {
                   2948: 		    rmdir($file);
1.240     banghart 2949: 		}
1.226     foxr     2950: 		if (-e $file) {
1.253     foxr     2951: 		    #  File is still there after we deleted it ?!?
                   2952: 
1.226     foxr     2953: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2954: 		} else {
                   2955: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2956: 		}
                   2957: 	    } else {
                   2958: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2959: 	    }
                   2960: 	} else {
                   2961: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2962: 	}
                   2963:     }
                   2964:     return 1;
                   2965: }
                   2966: &register_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
                   2967: 
1.236     albertel 2968: #
                   2969: #   make a directory in a user's home directory userfiles subdirectory.
                   2970: # Parameters:
                   2971: #    cmd   - the Lond request keyword that got us here.
                   2972: #    tail  - the part of the command past the keyword.
                   2973: #    client- File descriptor connected with the client.
                   2974: #
                   2975: # Returns:
                   2976: #    1    - Continue processing.
                   2977: sub mkdir_user_file_handler {
                   2978:     my ($cmd, $tail, $client) = @_;
                   2979: 
                   2980:     my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2981:     $dir=&unescape($dir);
                   2982:     my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2983:     if ($ufile =~m|/\.\./|) {
                   2984: 	# any files paths with /../ in them refuse 
                   2985: 	# to deal with
                   2986: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2987:     } else {
                   2988: 	my $udir = &propath($udom,$uname);
                   2989: 	if (-e $udir) {
1.264     albertel 2990: 	    my $newdir=$udir.'/userfiles/'.$ufile.'/';
                   2991: 	    if (!&mkpath($newdir)) {
                   2992: 		&Failure($client, "failed\n", "$cmd:$tail");
1.236     albertel 2993: 	    }
1.264     albertel 2994: 	    &Reply($client, "ok\n", "$cmd:$tail");
1.236     albertel 2995: 	} else {
                   2996: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2997: 	}
                   2998:     }
                   2999:     return 1;
                   3000: }
                   3001: &register_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
                   3002: 
1.237     albertel 3003: #
                   3004: #   rename a file in a user's home directory userfiles subdirectory.
                   3005: # Parameters:
                   3006: #    cmd   - the Lond request keyword that got us here.
                   3007: #    tail  - the part of the command past the keyword.
                   3008: #    client- File descriptor connected with the client.
                   3009: #
                   3010: # Returns:
                   3011: #    1    - Continue processing.
                   3012: sub rename_user_file_handler {
                   3013:     my ($cmd, $tail, $client) = @_;
                   3014: 
                   3015:     my ($udom,$uname,$old,$new) = split(/:/, $tail);
                   3016:     $old=&unescape($old);
                   3017:     $new=&unescape($new);
                   3018:     if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
                   3019: 	# any files paths with /../ in them refuse to deal with
                   3020: 	&Failure($client, "refused\n", "$cmd:$tail");
                   3021:     } else {
                   3022: 	my $udir = &propath($udom,$uname);
                   3023: 	if (-e $udir) {
                   3024: 	    my $oldfile=$udir.'/userfiles/'.$old;
                   3025: 	    my $newfile=$udir.'/userfiles/'.$new;
                   3026: 	    if (-e $newfile) {
                   3027: 		&Failure($client, "exists\n", "$cmd:$tail");
                   3028: 	    } elsif (! -e $oldfile) {
                   3029: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   3030: 	    } else {
                   3031: 		if (!rename($oldfile,$newfile)) {
                   3032: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   3033: 		} else {
                   3034: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   3035: 		}
                   3036: 	    }
                   3037: 	} else {
                   3038: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   3039: 	}
                   3040:     }
                   3041:     return 1;
                   3042: }
                   3043: &register_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
                   3044: 
1.227     foxr     3045: #
1.382     albertel 3046: #  Checks if the specified user has an active session on the server
                   3047: #  return ok if so, not_found if not
                   3048: #
                   3049: # Parameters:
                   3050: #   cmd      - The request keyword that dispatched to tus.
                   3051: #   tail     - The tail of the request (colon separated parameters).
                   3052: #   client   - Filehandle open on the client.
                   3053: # Return:
                   3054: #    1.
                   3055: sub user_has_session_handler {
                   3056:     my ($cmd, $tail, $client) = @_;
                   3057: 
                   3058:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
                   3059:     
                   3060:     opendir(DIR,$perlvar{'lonIDsDir'});
                   3061:     my $filename;
                   3062:     while ($filename=readdir(DIR)) {
                   3063: 	last if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/);
                   3064:     }
                   3065:     if ($filename) {
                   3066: 	&Reply($client, "ok\n", "$cmd:$tail");
                   3067:     } else {
                   3068: 	&Failure($client, "not_found\n", "$cmd:$tail");
                   3069:     }
                   3070:     return 1;
                   3071: 
                   3072: }
                   3073: &register_handler("userhassession", \&user_has_session_handler, 0,1,0);
                   3074: 
1.560     raeburn  3075: sub del_usersession_handler {
                   3076:     my ($cmd, $tail, $client) = @_;
                   3077: 
                   3078:     my $result;
                   3079:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
                   3080:     if (($udom =~ /^$LONCAPA::match_domain$/) && ($uname =~ /^$LONCAPA::match_username$/)) {
                   3081:         my $lonidsdir = $perlvar{'lonIDsDir'};
                   3082:         if (-d $lonidsdir) {
                   3083:             if (opendir(DIR,$lonidsdir)) {
                   3084:                 my $filename;
                   3085:                 while ($filename=readdir(DIR)) {
                   3086:                     if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/) {
                   3087:                         if (tie(my %oldenv,'GDBM_File',"$lonidsdir/$filename",
                   3088:                                 &GDBM_READER(),0640)) {
                   3089:                             my $linkedfile;
                   3090:                             if (exists($oldenv{'user.linkedenv'})) {
                   3091:                                 $linkedfile = $oldenv{'user.linkedenv'};
                   3092:                             }
                   3093:                             untie(%oldenv);
                   3094:                             $result = unlink("$lonidsdir/$filename");
                   3095:                             if ($result) {
                   3096:                                 if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   3097:                                     if (-l "$lonidsdir/$linkedfile.id") {
                   3098:                                         unlink("$lonidsdir/$linkedfile.id");
                   3099:                                     }
                   3100:                                 }
                   3101:                             }
                   3102:                         } else {
                   3103:                             $result = unlink("$lonidsdir/$filename");
                   3104:                         }
                   3105:                         last;
                   3106:                     }
                   3107:                 }
                   3108:             }
                   3109:         }
                   3110:         if ($result == 1) {
                   3111:             &Reply($client, "$result\n", "$cmd:$tail");
                   3112:         } else {
                   3113:             &Reply($client, "not_found\n", "$cmd:$tail");
                   3114:         }
                   3115:     } else {
                   3116:         &Failure($client, "invalid_user\n", "$cmd:$tail");
                   3117:     }
                   3118:     return 1;
                   3119: }
                   3120: 
                   3121: &register_handler("delusersession", \&del_usersession_handler, 0,1,0);
                   3122: 
1.382     albertel 3123: #
1.263     albertel 3124: #  Authenticate access to a user file by checking that the token the user's 
                   3125: #  passed also exists in their session file
1.227     foxr     3126: #
                   3127: # Parameters:
                   3128: #   cmd      - The request keyword that dispatched to tus.
                   3129: #   tail     - The tail of the request (colon separated parameters).
                   3130: #   client   - Filehandle open on the client.
                   3131: # Return:
                   3132: #    1.
                   3133: sub token_auth_user_file_handler {
                   3134:     my ($cmd, $tail, $client) = @_;
                   3135: 
                   3136:     my ($fname, $session) = split(/:/, $tail);
                   3137:     
                   3138:     chomp($session);
1.393     raeburn  3139:     my $reply="non_auth";
1.343     albertel 3140:     my $file = $perlvar{'lonIDsDir'}.'/'.$session.'.id';
                   3141:     if (open(ENVIN,"$file")) {
1.332     albertel 3142: 	flock(ENVIN,LOCK_SH);
1.343     albertel 3143: 	tie(my %disk_env,'GDBM_File',"$file",&GDBM_READER(),0640);
                   3144: 	if (exists($disk_env{"userfile.$fname"})) {
1.393     raeburn  3145: 	    $reply="ok";
1.343     albertel 3146: 	} else {
                   3147: 	    foreach my $envname (keys(%disk_env)) {
                   3148: 		if ($envname=~ m|^userfile\.\Q$fname\E|) {
1.393     raeburn  3149: 		    $reply="ok";
1.343     albertel 3150: 		    last;
                   3151: 		}
                   3152: 	    }
1.227     foxr     3153: 	}
1.343     albertel 3154: 	untie(%disk_env);
1.227     foxr     3155: 	close(ENVIN);
1.387     albertel 3156: 	&Reply($client, \$reply, "$cmd:$tail");
1.227     foxr     3157:     } else {
                   3158: 	&Failure($client, "invalid_token\n", "$cmd:$tail");
                   3159:     }
                   3160:     return 1;
                   3161: 
                   3162: }
                   3163: &register_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
1.229     foxr     3164: 
                   3165: #
                   3166: #   Unsubscribe from a resource.
                   3167: #
                   3168: # Parameters:
                   3169: #    $cmd      - The command that got us here.
                   3170: #    $tail     - Tail of the command (remaining parameters).
                   3171: #    $client   - File descriptor connected to client.
                   3172: # Returns
                   3173: #     0        - Requested to exit, caller should shut down.
                   3174: #     1        - Continue processing.
                   3175: #
                   3176: sub unsubscribe_handler {
                   3177:     my ($cmd, $tail, $client) = @_;
                   3178: 
                   3179:     my $userinput= "$cmd:$tail";
                   3180:     
                   3181:     my ($fname) = split(/:/,$tail); # Split in case there's extrs.
                   3182: 
                   3183:     &Debug("Unsubscribing $fname");
                   3184:     if (-e $fname) {
                   3185: 	&Debug("Exists");
                   3186: 	&Reply($client, &unsub($fname,$clientip), $userinput);
                   3187:     } else {
                   3188: 	&Failure($client, "not_found\n", $userinput);
                   3189:     }
                   3190:     return 1;
                   3191: }
                   3192: &register_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
1.263     albertel 3193: 
1.230     foxr     3194: #   Subscribe to a resource
                   3195: #
                   3196: # Parameters:
                   3197: #    $cmd      - The command that got us here.
                   3198: #    $tail     - Tail of the command (remaining parameters).
                   3199: #    $client   - File descriptor connected to client.
                   3200: # Returns
                   3201: #     0        - Requested to exit, caller should shut down.
                   3202: #     1        - Continue processing.
                   3203: #
                   3204: sub subscribe_handler {
                   3205:     my ($cmd, $tail, $client)= @_;
                   3206: 
                   3207:     my $userinput  = "$cmd:$tail";
                   3208: 
                   3209:     &Reply( $client, &subscribe($userinput,$clientip), $userinput);
                   3210: 
                   3211:     return 1;
                   3212: }
                   3213: &register_handler("sub", \&subscribe_handler, 0, 1, 0);
                   3214: 
                   3215: #
1.379     albertel 3216: #   Determine the latest version of a resource (it looks for the highest
                   3217: #   past version and then returns that +1)
1.230     foxr     3218: #
                   3219: # Parameters:
                   3220: #    $cmd      - The command that got us here.
                   3221: #    $tail     - Tail of the command (remaining parameters).
1.379     albertel 3222: #                 (Should consist of an absolute path to a file)
1.230     foxr     3223: #    $client   - File descriptor connected to client.
                   3224: # Returns
                   3225: #     0        - Requested to exit, caller should shut down.
                   3226: #     1        - Continue processing.
                   3227: #
                   3228: sub current_version_handler {
                   3229:     my ($cmd, $tail, $client) = @_;
                   3230: 
                   3231:     my $userinput= "$cmd:$tail";
                   3232:    
                   3233:     my $fname   = $tail;
                   3234:     &Reply( $client, &currentversion($fname)."\n", $userinput);
                   3235:     return 1;
                   3236: 
                   3237: }
                   3238: &register_handler("currentversion", \&current_version_handler, 0, 1, 0);
                   3239: 
                   3240: #  Make an entry in a user's activity log.
                   3241: #
                   3242: # Parameters:
                   3243: #    $cmd      - The command that got us here.
                   3244: #    $tail     - Tail of the command (remaining parameters).
                   3245: #    $client   - File descriptor connected to client.
                   3246: # Returns
                   3247: #     0        - Requested to exit, caller should shut down.
                   3248: #     1        - Continue processing.
                   3249: #
                   3250: sub activity_log_handler {
                   3251:     my ($cmd, $tail, $client) = @_;
                   3252: 
                   3253: 
                   3254:     my $userinput= "$cmd:$tail";
                   3255: 
                   3256:     my ($udom,$uname,$what)=split(/:/,$tail);
                   3257:     chomp($what);
                   3258:     my $proname=&propath($udom,$uname);
                   3259:     my $now=time;
                   3260:     my $hfh;
                   3261:     if ($hfh=IO::File->new(">>$proname/activity.log")) { 
                   3262: 	print $hfh "$now:$clientname:$what\n";
                   3263: 	&Reply( $client, "ok\n", $userinput); 
                   3264:     } else {
                   3265: 	&Failure($client, "error: ".($!+0)." IO::File->new Failed "
                   3266: 		 ."while attempting log\n", 
                   3267: 		 $userinput);
                   3268:     }
                   3269: 
                   3270:     return 1;
                   3271: }
1.263     albertel 3272: &register_handler("log", \&activity_log_handler, 0, 1, 0);
1.230     foxr     3273: 
                   3274: #
                   3275: #   Put a namespace entry in a user profile hash.
                   3276: #   My druthers would be for this to be an encrypted interaction too.
                   3277: #   anything that might be an inadvertent covert channel about either
                   3278: #   user authentication or user personal information....
                   3279: #
                   3280: # Parameters:
                   3281: #    $cmd      - The command that got us here.
                   3282: #    $tail     - Tail of the command (remaining parameters).
                   3283: #    $client   - File descriptor connected to client.
                   3284: # Returns
                   3285: #     0        - Requested to exit, caller should shut down.
                   3286: #     1        - Continue processing.
                   3287: #
                   3288: sub put_user_profile_entry {
                   3289:     my ($cmd, $tail, $client)  = @_;
1.229     foxr     3290: 
1.230     foxr     3291:     my $userinput = "$cmd:$tail";
                   3292:     
1.242     raeburn  3293:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
1.230     foxr     3294:     if ($namespace ne 'roles') {
                   3295: 	chomp($what);
                   3296: 	my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3297: 				  &GDBM_WRCREAT(),"P",$what);
                   3298: 	if($hashref) {
                   3299: 	    my @pairs=split(/\&/,$what);
                   3300: 	    foreach my $pair (@pairs) {
                   3301: 		my ($key,$value)=split(/=/,$pair);
                   3302: 		$hashref->{$key}=$value;
                   3303: 	    }
1.311     albertel 3304: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     3305: 		&Reply( $client, "ok\n", $userinput);
                   3306: 	    } else {
                   3307: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3308: 			"while attempting put\n", 
                   3309: 			$userinput);
                   3310: 	    }
                   3311: 	} else {
1.316     albertel 3312: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.230     foxr     3313: 		     "while attempting put\n", $userinput);
                   3314: 	}
                   3315:     } else {
                   3316:         &Failure( $client, "refused\n", $userinput);
                   3317:     }
                   3318:     
                   3319:     return 1;
                   3320: }
                   3321: &register_handler("put", \&put_user_profile_entry, 0, 1, 0);
                   3322: 
1.283     albertel 3323: #   Put a piece of new data in hash, returns error if entry already exists
                   3324: # Parameters:
                   3325: #    $cmd      - The command that got us here.
                   3326: #    $tail     - Tail of the command (remaining parameters).
                   3327: #    $client   - File descriptor connected to client.
                   3328: # Returns
                   3329: #     0        - Requested to exit, caller should shut down.
                   3330: #     1        - Continue processing.
                   3331: #
                   3332: sub newput_user_profile_entry {
                   3333:     my ($cmd, $tail, $client)  = @_;
                   3334: 
                   3335:     my $userinput = "$cmd:$tail";
                   3336: 
                   3337:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
                   3338:     if ($namespace eq 'roles') {
                   3339:         &Failure( $client, "refused\n", $userinput);
                   3340: 	return 1;
                   3341:     }
                   3342: 
                   3343:     chomp($what);
                   3344: 
                   3345:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3346: 				 &GDBM_WRCREAT(),"N",$what);
                   3347:     if(!$hashref) {
1.316     albertel 3348: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.283     albertel 3349: 		  "while attempting put\n", $userinput);
                   3350: 	return 1;
                   3351:     }
                   3352: 
                   3353:     my @pairs=split(/\&/,$what);
                   3354:     foreach my $pair (@pairs) {
                   3355: 	my ($key,$value)=split(/=/,$pair);
                   3356: 	if (exists($hashref->{$key})) {
1.513     raeburn  3357:             if (!&untie_user_hash($hashref)) {
                   3358:                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
                   3359:                          "while attempting newput - early out as key exists");
                   3360:             }
                   3361:             &Failure($client, "key_exists: ".$key."\n",$userinput);
                   3362:             return 1;
1.283     albertel 3363: 	}
                   3364:     }
                   3365: 
                   3366:     foreach my $pair (@pairs) {
                   3367: 	my ($key,$value)=split(/=/,$pair);
                   3368: 	$hashref->{$key}=$value;
                   3369:     }
                   3370: 
1.311     albertel 3371:     if (&untie_user_hash($hashref)) {
1.283     albertel 3372: 	&Reply( $client, "ok\n", $userinput);
                   3373:     } else {
                   3374: 	&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3375: 		 "while attempting put\n", 
                   3376: 		 $userinput);
                   3377:     }
                   3378:     return 1;
                   3379: }
                   3380: &register_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
                   3381: 
1.230     foxr     3382: # 
                   3383: #   Increment a profile entry in the user history file.
                   3384: #   The history contains keyword value pairs.  In this case,
                   3385: #   The value itself is a pair of numbers.  The first, the current value
                   3386: #   the second an increment that this function applies to the current
                   3387: #   value.
                   3388: #
                   3389: # Parameters:
                   3390: #    $cmd      - The command that got us here.
                   3391: #    $tail     - Tail of the command (remaining parameters).
                   3392: #    $client   - File descriptor connected to client.
                   3393: # Returns
                   3394: #     0        - Requested to exit, caller should shut down.
                   3395: #     1        - Continue processing.
                   3396: #
                   3397: sub increment_user_value_handler {
                   3398:     my ($cmd, $tail, $client) = @_;
                   3399:     
                   3400:     my $userinput   = "$cmd:$tail";
                   3401:     
                   3402:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
                   3403:     if ($namespace ne 'roles') {
                   3404:         chomp($what);
                   3405: 	my $hashref = &tie_user_hash($udom, $uname,
                   3406: 				     $namespace, &GDBM_WRCREAT(),
                   3407: 				     "P",$what);
                   3408: 	if ($hashref) {
                   3409: 	    my @pairs=split(/\&/,$what);
                   3410: 	    foreach my $pair (@pairs) {
                   3411: 		my ($key,$value)=split(/=/,$pair);
1.284     raeburn  3412:                 $value = &unescape($value);
1.230     foxr     3413: 		# We could check that we have a number...
                   3414: 		if (! defined($value) || $value eq '') {
                   3415: 		    $value = 1;
                   3416: 		}
                   3417: 		$hashref->{$key}+=$value;
1.284     raeburn  3418:                 if ($namespace eq 'nohist_resourcetracker') {
                   3419:                     if ($hashref->{$key} < 0) {
                   3420:                         $hashref->{$key} = 0;
                   3421:                     }
                   3422:                 }
1.230     foxr     3423: 	    }
1.311     albertel 3424: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     3425: 		&Reply( $client, "ok\n", $userinput);
                   3426: 	    } else {
                   3427: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3428: 			 "while attempting inc\n", $userinput);
                   3429: 	    }
                   3430: 	} else {
                   3431: 	    &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3432: 		     "while attempting inc\n", $userinput);
                   3433: 	}
                   3434:     } else {
                   3435: 	&Failure($client, "refused\n", $userinput);
                   3436:     }
                   3437:     
                   3438:     return 1;
                   3439: }
                   3440: &register_handler("inc", \&increment_user_value_handler, 0, 1, 0);
                   3441: 
                   3442: #
                   3443: #   Put a new role for a user.  Roles are LonCAPA's packaging of permissions.
                   3444: #   Each 'role' a user has implies a set of permissions.  Adding a new role
                   3445: #   for a person grants the permissions packaged with that role
                   3446: #   to that user when the role is selected.
                   3447: #
                   3448: # Parameters:
                   3449: #    $cmd       - The command string (rolesput).
                   3450: #    $tail      - The remainder of the request line.  For rolesput this
                   3451: #                 consists of a colon separated list that contains:
                   3452: #                 The domain and user that is granting the role (logged).
                   3453: #                 The domain and user that is getting the role.
                   3454: #                 The roles being granted as a set of & separated pairs.
                   3455: #                 each pair a key value pair.
                   3456: #    $client    - File descriptor connected to the client.
                   3457: # Returns:
                   3458: #     0         - If the daemon should exit
                   3459: #     1         - To continue processing.
                   3460: #
                   3461: #
                   3462: sub roles_put_handler {
                   3463:     my ($cmd, $tail, $client) = @_;
                   3464: 
                   3465:     my $userinput  = "$cmd:$tail";
                   3466: 
                   3467:     my ( $exedom, $exeuser, $udom, $uname,  $what) = split(/:/,$tail);
                   3468:     
                   3469: 
                   3470:     my $namespace='roles';
                   3471:     chomp($what);
                   3472:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3473: 				 &GDBM_WRCREAT(), "P",
                   3474: 				 "$exedom:$exeuser:$what");
                   3475:     #
                   3476:     #  Log the attempt to set a role.  The {}'s here ensure that the file 
                   3477:     #  handle is open for the minimal amount of time.  Since the flush
                   3478:     #  is done on close this improves the chances the log will be an un-
                   3479:     #  corrupted ordered thing.
                   3480:     if ($hashref) {
1.261     foxr     3481: 	my $pass_entry = &get_auth_type($udom, $uname);
                   3482: 	my ($auth_type,$pwd)  = split(/:/, $pass_entry);
                   3483: 	$auth_type = $auth_type.":";
1.230     foxr     3484: 	my @pairs=split(/\&/,$what);
                   3485: 	foreach my $pair (@pairs) {
                   3486: 	    my ($key,$value)=split(/=/,$pair);
                   3487: 	    &manage_permissions($key, $udom, $uname,
1.260     foxr     3488: 			       $auth_type);
1.230     foxr     3489: 	    $hashref->{$key}=$value;
                   3490: 	}
1.311     albertel 3491: 	if (&untie_user_hash($hashref)) {
1.230     foxr     3492: 	    &Reply($client, "ok\n", $userinput);
                   3493: 	} else {
                   3494: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3495: 		     "while attempting rolesput\n", $userinput);
                   3496: 	}
                   3497:     } else {
                   3498: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3499: 		 "while attempting rolesput\n", $userinput);
                   3500:     }
                   3501:     return 1;
                   3502: }
                   3503: &register_handler("rolesput", \&roles_put_handler, 1,1,0);  # Encoded client only.
                   3504: 
                   3505: #
1.231     foxr     3506: #   Deletes (removes) a role for a user.   This is equivalent to removing
                   3507: #  a permissions package associated with the role from the user's profile.
                   3508: #
                   3509: # Parameters:
                   3510: #     $cmd                 - The command (rolesdel)
                   3511: #     $tail                - The remainder of the request line. This consists
                   3512: #                             of:
                   3513: #                             The domain and user requesting the change (logged)
                   3514: #                             The domain and user being changed.
                   3515: #                             The roles being revoked.  These are shipped to us
                   3516: #                             as a bunch of & separated role name keywords.
                   3517: #     $client              - The file handle open on the client.
                   3518: # Returns:
                   3519: #     1                    - Continue processing
                   3520: #     0                    - Exit.
                   3521: #
                   3522: sub roles_delete_handler {
                   3523:     my ($cmd, $tail, $client)  = @_;
                   3524: 
                   3525:     my $userinput    = "$cmd:$tail";
                   3526:    
                   3527:     my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
                   3528:     &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
                   3529: 	   "what = ".$what);
                   3530:     my $namespace='roles';
                   3531:     chomp($what);
                   3532:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3533: 				 &GDBM_WRCREAT(), "D",
                   3534: 				 "$exedom:$exeuser:$what");
                   3535:     
                   3536:     if ($hashref) {
                   3537: 	my @rolekeys=split(/\&/,$what);
                   3538: 	
                   3539: 	foreach my $key (@rolekeys) {
                   3540: 	    delete $hashref->{$key};
                   3541: 	}
1.315     albertel 3542: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3543: 	    &Reply($client, "ok\n", $userinput);
                   3544: 	} else {
                   3545: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3546: 		     "while attempting rolesdel\n", $userinput);
                   3547: 	}
                   3548:     } else {
                   3549:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3550: 		 "while attempting rolesdel\n", $userinput);
                   3551:     }
                   3552:     
                   3553:     return 1;
                   3554: }
                   3555: &register_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
                   3556: 
                   3557: # Unencrypted get from a user's profile database.  See 
                   3558: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
                   3559: # This function retrieves a keyed item from a specific named database in the
                   3560: # user's directory.
                   3561: #
                   3562: # Parameters:
                   3563: #   $cmd             - Command request keyword (get).
                   3564: #   $tail            - Tail of the command.  This is a colon separated list
                   3565: #                      consisting of the domain and username that uniquely
                   3566: #                      identifies the profile,
                   3567: #                      The 'namespace' which selects the gdbm file to 
                   3568: #                      do the lookup in, 
                   3569: #                      & separated list of keys to lookup.  Note that
                   3570: #                      the values are returned as an & separated list too.
                   3571: #   $client          - File descriptor open on the client.
                   3572: # Returns:
                   3573: #   1       - Continue processing.
                   3574: #   0       - Exit.
                   3575: #
                   3576: sub get_profile_entry {
                   3577:     my ($cmd, $tail, $client) = @_;
                   3578: 
                   3579:     my $userinput= "$cmd:$tail";
                   3580:    
                   3581:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   3582:     chomp($what);
1.255     foxr     3583: 
1.390     raeburn  3584: 
1.255     foxr     3585:     my $replystring = read_profile($udom, $uname, $namespace, $what);
                   3586:     my ($first) = split(/:/,$replystring);
                   3587:     if($first ne "error") {
1.387     albertel 3588: 	&Reply($client, \$replystring, $userinput);
1.231     foxr     3589:     } else {
1.255     foxr     3590: 	&Failure($client, $replystring." while attempting get\n", $userinput);
1.231     foxr     3591:     }
                   3592:     return 1;
1.255     foxr     3593: 
                   3594: 
1.231     foxr     3595: }
                   3596: &register_handler("get", \&get_profile_entry, 0,1,0);
                   3597: 
                   3598: #
                   3599: #  Process the encrypted get request.  Note that the request is sent
                   3600: #  in clear, but the reply is encrypted.  This is a small covert channel:
                   3601: #  information about the sensitive keys is given to the snooper.  Just not
                   3602: #  information about the values of the sensitive key.  Hmm if I wanted to
                   3603: #  know these I'd snoop for the egets. Get the profile item names from them
                   3604: #  and then issue a get for them since there's no enforcement of the
                   3605: #  requirement of an encrypted get for particular profile items.  If I
                   3606: #  were re-doing this, I'd force the request to be encrypted as well as the
                   3607: #  reply.  I'd also just enforce encrypted transactions for all gets since
                   3608: #  that would prevent any covert channel snooping.
                   3609: #
                   3610: #  Parameters:
                   3611: #     $cmd               - Command keyword of request (eget).
1.536     raeburn  3612: #     $tail              - Tail of the command.  See GetProfileEntry
                   3613: #                          for more information about this.
1.231     foxr     3614: #     $client            - File open on the client.
                   3615: #  Returns:
                   3616: #     1      - Continue processing
                   3617: #     0      - server should exit.
                   3618: sub get_profile_entry_encrypted {
                   3619:     my ($cmd, $tail, $client) = @_;
                   3620: 
                   3621:     my $userinput = "$cmd:$tail";
                   3622:    
1.339     albertel 3623:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
1.231     foxr     3624:     chomp($what);
1.255     foxr     3625:     my $qresult = read_profile($udom, $uname, $namespace, $what);
                   3626:     my ($first) = split(/:/, $qresult);
                   3627:     if($first ne "error") {
                   3628: 	
                   3629: 	if ($cipher) {
                   3630: 	    my $cmdlength=length($qresult);
                   3631: 	    $qresult.="         ";
                   3632: 	    my $encqresult='';
                   3633: 	    for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   3634: 		$encqresult.= unpack("H16", 
                   3635: 				     $cipher->encrypt(substr($qresult,
                   3636: 							     $encidx,
                   3637: 							     8)));
                   3638: 	    }
                   3639: 	    &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
                   3640: 	} else {
1.231     foxr     3641: 		&Failure( $client, "error:no_key\n", $userinput);
                   3642: 	    }
                   3643:     } else {
1.255     foxr     3644: 	&Failure($client, "$qresult while attempting eget\n", $userinput);
                   3645: 
1.231     foxr     3646:     }
                   3647:     
                   3648:     return 1;
                   3649: }
1.255     foxr     3650: &register_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
1.263     albertel 3651: 
1.231     foxr     3652: #
                   3653: #   Deletes a key in a user profile database.
                   3654: #   
                   3655: #   Parameters:
                   3656: #       $cmd                  - Command keyword (del).
                   3657: #       $tail                 - Command tail.  IN this case a colon
                   3658: #                               separated list containing:
                   3659: #                               The domain and user that identifies uniquely
                   3660: #                               the identity of the user.
                   3661: #                               The profile namespace (name of the profile
                   3662: #                               database file).
                   3663: #                               & separated list of keywords to delete.
                   3664: #       $client              - File open on client socket.
                   3665: # Returns:
                   3666: #     1   - Continue processing
                   3667: #     0   - Exit server.
                   3668: #
                   3669: #
                   3670: sub delete_profile_entry {
                   3671:     my ($cmd, $tail, $client) = @_;
                   3672: 
                   3673:     my $userinput = "cmd:$tail";
                   3674: 
                   3675:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   3676:     chomp($what);
                   3677:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3678: 				 &GDBM_WRCREAT(),
                   3679: 				 "D",$what);
                   3680:     if ($hashref) {
                   3681:         my @keys=split(/\&/,$what);
                   3682: 	foreach my $key (@keys) {
                   3683: 	    delete($hashref->{$key});
                   3684: 	}
1.315     albertel 3685: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3686: 	    &Reply($client, "ok\n", $userinput);
                   3687: 	} else {
                   3688: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3689: 		    "while attempting del\n", $userinput);
                   3690: 	}
                   3691:     } else {
                   3692: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3693: 		 "while attempting del\n", $userinput);
                   3694:     }
                   3695:     return 1;
                   3696: }
                   3697: &register_handler("del", \&delete_profile_entry, 0, 1, 0);
1.263     albertel 3698: 
1.231     foxr     3699: #
                   3700: #  List the set of keys that are defined in a profile database file.
                   3701: #  A successful reply from this will contain an & separated list of
                   3702: #  the keys. 
                   3703: # Parameters:
                   3704: #     $cmd              - Command request (keys).
                   3705: #     $tail             - Remainder of the request, a colon separated
                   3706: #                         list containing domain/user that identifies the
                   3707: #                         user being queried, and the database namespace
                   3708: #                         (database filename essentially).
                   3709: #     $client           - File open on the client.
                   3710: #  Returns:
                   3711: #    1    - Continue processing.
                   3712: #    0    - Exit the server.
                   3713: #
                   3714: sub get_profile_keys {
                   3715:     my ($cmd, $tail, $client) = @_;
                   3716: 
                   3717:     my $userinput = "$cmd:$tail";
                   3718: 
                   3719:     my ($udom,$uname,$namespace)=split(/:/,$tail);
                   3720:     my $qresult='';
                   3721:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3722: 				  &GDBM_READER());
                   3723:     if ($hashref) {
                   3724: 	foreach my $key (keys %$hashref) {
                   3725: 	    $qresult.="$key&";
                   3726: 	}
1.315     albertel 3727: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3728: 	    $qresult=~s/\&$//;
1.387     albertel 3729: 	    &Reply($client, \$qresult, $userinput);
1.231     foxr     3730: 	} else {
                   3731: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3732: 		    "while attempting keys\n", $userinput);
                   3733: 	}
                   3734:     } else {
                   3735: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3736: 		 "while attempting keys\n", $userinput);
                   3737:     }
                   3738:    
                   3739:     return 1;
                   3740: }
                   3741: &register_handler("keys", \&get_profile_keys, 0, 1, 0);
                   3742: 
                   3743: #
                   3744: #   Dump the contents of a user profile database.
                   3745: #   Note that this constitutes a very large covert channel too since
                   3746: #   the dump will return sensitive information that is not encrypted.
                   3747: #   The naive security assumption is that the session negotiation ensures
                   3748: #   our client is trusted and I don't believe that's assured at present.
                   3749: #   Sure want badly to go to ssl or tls.  Of course if my peer isn't really
                   3750: #   a LonCAPA node they could have negotiated an encryption key too so >sigh<.
                   3751: # 
                   3752: #  Parameters:
                   3753: #     $cmd           - The command request keyword (currentdump).
                   3754: #     $tail          - Remainder of the request, consisting of a colon
                   3755: #                      separated list that has the domain/username and
                   3756: #                      the namespace to dump (database file).
                   3757: #     $client        - file open on the remote client.
                   3758: # Returns:
                   3759: #     1    - Continue processing.
                   3760: #     0    - Exit the server.
                   3761: #
                   3762: sub dump_profile_database {
                   3763:     my ($cmd, $tail, $client) = @_;
                   3764: 
1.494     droeschl 3765:     my $res = LONCAPA::Lond::dump_profile_database($tail);
                   3766: 
                   3767:     if ($res =~ /^error:/) {
                   3768:         Failure($client, \$res, "$cmd:$tail");
                   3769:     } else {
                   3770:         Reply($client, \$res, "$cmd:$tail");
                   3771:     }
                   3772: 
                   3773:     return 1;  
                   3774: 
                   3775:     #TODO remove 
1.231     foxr     3776:     my $userinput = "$cmd:$tail";
                   3777:    
                   3778:     my ($udom,$uname,$namespace) = split(/:/,$tail);
                   3779:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3780: 				 &GDBM_READER());
                   3781:     if ($hashref) {
                   3782: 	# Structure of %data:
                   3783: 	# $data{$symb}->{$parameter}=$value;
                   3784: 	# $data{$symb}->{'v.'.$parameter}=$version;
                   3785: 	# since $parameter will be unescaped, we do not
                   3786:  	# have to worry about silly parameter names...
                   3787: 	
                   3788:         my $qresult='';
                   3789: 	my %data = ();                     # A hash of anonymous hashes..
                   3790: 	while (my ($key,$value) = each(%$hashref)) {
                   3791: 	    my ($v,$symb,$param) = split(/:/,$key);
                   3792: 	    next if ($v eq 'version' || $symb eq 'keys');
                   3793: 	    next if (exists($data{$symb}) && 
                   3794: 		     exists($data{$symb}->{$param}) &&
                   3795: 		     $data{$symb}->{'v.'.$param} > $v);
                   3796: 	    $data{$symb}->{$param}=$value;
                   3797: 	    $data{$symb}->{'v.'.$param}=$v;
                   3798: 	}
1.311     albertel 3799: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3800: 	    while (my ($symb,$param_hash) = each(%data)) {
                   3801: 		while(my ($param,$value) = each (%$param_hash)){
                   3802: 		    next if ($param =~ /^v\./);       # Ignore versions...
                   3803: 		    #
                   3804: 		    #   Just dump the symb=value pairs separated by &
                   3805: 		    #
                   3806: 		    $qresult.=$symb.':'.$param.'='.$value.'&';
                   3807: 		}
                   3808: 	    }
                   3809: 	    chop($qresult);
1.387     albertel 3810: 	    &Reply($client , \$qresult, $userinput);
1.231     foxr     3811: 	} else {
                   3812: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3813: 		     "while attempting currentdump\n", $userinput);
                   3814: 	}
                   3815:     } else {
                   3816: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3817: 		"while attempting currentdump\n", $userinput);
                   3818:     }
                   3819: 
                   3820:     return 1;
                   3821: }
                   3822: &register_handler("currentdump", \&dump_profile_database, 0, 1, 0);
                   3823: 
                   3824: #
                   3825: #   Dump a profile database with an optional regular expression
                   3826: #   to match against the keys.  In this dump, no effort is made
                   3827: #   to separate symb from version information. Presumably the
                   3828: #   databases that are dumped by this command are of a different
                   3829: #   structure.  Need to look at this and improve the documentation of
                   3830: #   both this and the currentdump handler.
                   3831: # Parameters:
                   3832: #    $cmd                     - The command keyword.
                   3833: #    $tail                    - All of the characters after the $cmd:
                   3834: #                               These are expected to be a colon
                   3835: #                               separated list containing:
                   3836: #                               domain/user - identifying the user.
                   3837: #                               namespace   - identifying the database.
                   3838: #                               regexp      - optional regular expression
                   3839: #                                             that is matched against
                   3840: #                                             database keywords to do
                   3841: #                                             selective dumps.
1.488     raeburn  3842: #                               range       - optional range of entries
                   3843: #                                             e.g., 10-20 would return the
                   3844: #                                             10th to 19th items, etc.  
1.231     foxr     3845: #   $client                   - Channel open on the client.
                   3846: # Returns:
                   3847: #    1    - Continue processing.
                   3848: # Side effects:
                   3849: #    response is written to $client.
                   3850: #
                   3851: sub dump_with_regexp {
                   3852:     my ($cmd, $tail, $client) = @_;
                   3853: 
1.494     droeschl 3854:     my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
1.490     droeschl 3855:     
                   3856:     if ($res =~ /^error:/) {
                   3857:         Failure($client, \$res, "$cmd:$tail");
                   3858:     } else {
                   3859:         Reply($client, \$res, "$cmd:$tail");
                   3860:     }
1.231     foxr     3861: 
                   3862:     return 1;
                   3863: }
                   3864: &register_handler("dump", \&dump_with_regexp, 0, 1, 0);
                   3865: 
1.568     raeburn  3866: #
                   3867: #  Process the encrypted dump request. Original call should
                   3868: #  be from lonnet::dump() with seventh arg ($encrypt) set to
                   3869: #  1, to ensure that both request and response are encrypted.
                   3870: #
                   3871: #  Parameters:
                   3872: #     $cmd               - Command keyword of request (edump).
                   3873: #     $tail              - Tail of the command.
                   3874: #                          See &dump_with_regexp for more
                   3875: #                          information about this.
                   3876: #     $client            - File open on the client.
                   3877: #  Returns:
                   3878: #     1      - Continue processing
                   3879: #     0      - server should exit.
                   3880: #
                   3881: 
                   3882: sub encrypted_dump_with_regexp {
                   3883:     my ($cmd, $tail, $client) = @_;
                   3884:     my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
                   3885: 
                   3886:     if ($res =~ /^error:/) {
                   3887:         Failure($client, \$res, "$cmd:$tail");
                   3888:     } else {
                   3889:         if ($cipher) {
                   3890:             my $cmdlength=length($res);
                   3891:             $res.="         ";
                   3892:             my $encres='';
                   3893:             for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   3894:                 $encres.= unpack("H16",
                   3895:                                  $cipher->encrypt(substr($res,
                   3896:                                                          $encidx,
                   3897:                                                          8)));
                   3898:             }
                   3899:             &Reply( $client,"enc:$cmdlength:$encres\n","$cmd:$tail");
                   3900:         } else {
                   3901:             &Failure( $client, "error:no_key\n","$cmd:$tail");
                   3902:         }
                   3903:     }
                   3904: }
                   3905: &register_handler("edump", \&encrypted_dump_with_regexp, 0, 1, 0);
                   3906: 
1.231     foxr     3907: #  Store a set of key=value pairs associated with a versioned name.
                   3908: #
                   3909: #  Parameters:
                   3910: #    $cmd                - Request command keyword.
                   3911: #    $tail               - Tail of the request.  This is a colon
                   3912: #                          separated list containing:
                   3913: #                          domain/user - User and authentication domain.
                   3914: #                          namespace   - Name of the database being modified
                   3915: #                          rid         - Resource keyword to modify.
                   3916: #                          what        - new value associated with rid.
1.512     raeburn  3917: #                          laststore   - (optional) version=timestamp
                   3918: #                                        for most recent transaction for rid
                   3919: #                                        in namespace, when cstore was called
1.231     foxr     3920: #
                   3921: #    $client             - Socket open on the client.
                   3922: #
                   3923: #
                   3924: #  Returns:
                   3925: #      1 (keep on processing).
                   3926: #  Side-Effects:
                   3927: #    Writes to the client
1.512     raeburn  3928: #    Successful storage will cause either 'ok', or, if $laststore was included
                   3929: #    in the tail of the request, and the version number for the last transaction
                   3930: #    is larger than the version in $laststore, delay:$numtrans , where $numtrans
                   3931: #    is the number of store evevnts recorded for rid in namespace since
                   3932: #    lonnet::store() was called by the client.
                   3933: #
1.231     foxr     3934: sub store_handler {
                   3935:     my ($cmd, $tail, $client) = @_;
                   3936:  
                   3937:     my $userinput = "$cmd:$tail";
1.512     raeburn  3938:     chomp($tail);
                   3939:     my ($udom,$uname,$namespace,$rid,$what,$laststore) =split(/:/,$tail);
1.231     foxr     3940:     if ($namespace ne 'roles') {
                   3941: 
                   3942: 	my @pairs=split(/\&/,$what);
                   3943: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
1.268     albertel 3944: 				       &GDBM_WRCREAT(), "S",
1.231     foxr     3945: 				       "$rid:$what");
                   3946: 	if ($hashref) {
                   3947: 	    my $now = time;
1.512     raeburn  3948:             my $numtrans;
                   3949:             if ($laststore) {
                   3950:                 my ($previousversion,$previoustime) = split(/\=/,$laststore);
                   3951:                 my ($lastversion,$lasttime) = (0,0);
                   3952:                 $lastversion = $hashref->{"version:$rid"};
                   3953:                 if ($lastversion) {
                   3954:                     $lasttime = $hashref->{"$lastversion:$rid:timestamp"};
                   3955:                 }
                   3956:                 if (($previousversion) && ($previousversion !~ /\D/)) {
                   3957:                     if (($lastversion > $previousversion) && ($lasttime >= $previoustime)) {
                   3958:                         $numtrans = $lastversion - $previousversion;
                   3959:                     }
                   3960:                 } elsif ($lastversion) {
                   3961:                     $numtrans = $lastversion;
                   3962:                 }
                   3963:                 if ($numtrans) {
                   3964:                     $numtrans =~ s/D//g;
                   3965:                 }
                   3966:             }
1.231     foxr     3967: 	    $hashref->{"version:$rid"}++;
                   3968: 	    my $version=$hashref->{"version:$rid"};
                   3969: 	    my $allkeys=''; 
                   3970: 	    foreach my $pair (@pairs) {
                   3971: 		my ($key,$value)=split(/=/,$pair);
                   3972: 		$allkeys.=$key.':';
                   3973: 		$hashref->{"$version:$rid:$key"}=$value;
                   3974: 	    }
                   3975: 	    $hashref->{"$version:$rid:timestamp"}=$now;
                   3976: 	    $allkeys.='timestamp';
                   3977: 	    $hashref->{"$version:keys:$rid"}=$allkeys;
1.311     albertel 3978: 	    if (&untie_user_hash($hashref)) {
1.512     raeburn  3979:                 my $msg = 'ok';
                   3980:                 if ($numtrans) {
                   3981:                     $msg = 'delay:'.$numtrans;
                   3982:                 }
                   3983: 		&Reply($client, "$msg\n", $userinput);
1.231     foxr     3984: 	    } else {
                   3985: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3986: 			"while attempting store\n", $userinput);
                   3987: 	    }
                   3988: 	} else {
                   3989: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3990: 		     "while attempting store\n", $userinput);
                   3991: 	}
                   3992:     } else {
                   3993: 	&Failure($client, "refused\n", $userinput);
                   3994:     }
                   3995: 
                   3996:     return 1;
                   3997: }
                   3998: &register_handler("store", \&store_handler, 0, 1, 0);
1.263     albertel 3999: 
1.323     albertel 4000: #  Modify a set of key=value pairs associated with a versioned name.
                   4001: #
                   4002: #  Parameters:
                   4003: #    $cmd                - Request command keyword.
                   4004: #    $tail               - Tail of the request.  This is a colon
                   4005: #                          separated list containing:
                   4006: #                          domain/user - User and authentication domain.
                   4007: #                          namespace   - Name of the database being modified
                   4008: #                          rid         - Resource keyword to modify.
                   4009: #                          v           - Version item to modify
                   4010: #                          what        - new value associated with rid.
                   4011: #
                   4012: #    $client             - Socket open on the client.
                   4013: #
                   4014: #
                   4015: #  Returns:
                   4016: #      1 (keep on processing).
                   4017: #  Side-Effects:
                   4018: #    Writes to the client
                   4019: sub putstore_handler {
                   4020:     my ($cmd, $tail, $client) = @_;
                   4021:  
                   4022:     my $userinput = "$cmd:$tail";
                   4023: 
                   4024:     my ($udom,$uname,$namespace,$rid,$v,$what) =split(/:/,$tail);
                   4025:     if ($namespace ne 'roles') {
                   4026: 
                   4027: 	chomp($what);
                   4028: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
                   4029: 				       &GDBM_WRCREAT(), "M",
                   4030: 				       "$rid:$v:$what");
                   4031: 	if ($hashref) {
                   4032: 	    my $now = time;
                   4033: 	    my %data = &hash_extract($what);
                   4034: 	    my @allkeys;
                   4035: 	    while (my($key,$value) = each(%data)) {
                   4036: 		push(@allkeys,$key);
                   4037: 		$hashref->{"$v:$rid:$key"} = $value;
                   4038: 	    }
                   4039: 	    my $allkeys = join(':',@allkeys);
                   4040: 	    $hashref->{"$v:keys:$rid"}=$allkeys;
                   4041: 
                   4042: 	    if (&untie_user_hash($hashref)) {
                   4043: 		&Reply($client, "ok\n", $userinput);
                   4044: 	    } else {
                   4045: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4046: 			"while attempting store\n", $userinput);
                   4047: 	    }
                   4048: 	} else {
                   4049: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4050: 		     "while attempting store\n", $userinput);
                   4051: 	}
                   4052:     } else {
                   4053: 	&Failure($client, "refused\n", $userinput);
                   4054:     }
                   4055: 
                   4056:     return 1;
                   4057: }
                   4058: &register_handler("putstore", \&putstore_handler, 0, 1, 0);
                   4059: 
                   4060: sub hash_extract {
                   4061:     my ($str)=@_;
                   4062:     my %hash;
                   4063:     foreach my $pair (split(/\&/,$str)) {
                   4064: 	my ($key,$value)=split(/=/,$pair);
                   4065: 	$hash{$key}=$value;
                   4066:     }
                   4067:     return (%hash);
                   4068: }
                   4069: sub hash_to_str {
                   4070:     my ($hash_ref)=@_;
                   4071:     my $str;
                   4072:     foreach my $key (keys(%$hash_ref)) {
                   4073: 	$str.=$key.'='.$hash_ref->{$key}.'&';
                   4074:     }
                   4075:     $str=~s/\&$//;
                   4076:     return $str;
                   4077: }
                   4078: 
1.231     foxr     4079: #
                   4080: #  Dump out all versions of a resource that has key=value pairs associated
                   4081: # with it for each version.  These resources are built up via the store
                   4082: # command.
                   4083: #
                   4084: #  Parameters:
                   4085: #     $cmd               - Command keyword.
                   4086: #     $tail              - Remainder of the request which consists of:
                   4087: #                          domain/user   - User and auth. domain.
                   4088: #                          namespace     - name of resource database.
                   4089: #                          rid           - Resource id.
                   4090: #    $client             - socket open on the client.
                   4091: #
                   4092: # Returns:
                   4093: #      1  indicating the caller should not yet exit.
                   4094: # Side-effects:
                   4095: #   Writes a reply to the client.
                   4096: #   The reply is a string of the following shape:
                   4097: #   version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
                   4098: #    Where the 1 above represents version 1.
                   4099: #    this continues for all pairs of keys in all versions.
                   4100: #
                   4101: #
                   4102: #    
                   4103: #
                   4104: sub restore_handler {
                   4105:     my ($cmd, $tail, $client) = @_;
                   4106: 
                   4107:     my $userinput = "$cmd:$tail";	# Only used for logging purposes.
1.351     banghart 4108:     my ($udom,$uname,$namespace,$rid) = split(/:/,$tail);
1.352     albertel 4109:     $namespace=~s/\//\_/g;
1.350     albertel 4110:     $namespace = &LONCAPA::clean_username($namespace);
1.349     albertel 4111: 
1.231     foxr     4112:     chomp($rid);
                   4113:     my $qresult='';
1.309     albertel 4114:     my $hashref = &tie_user_hash($udom, $uname, $namespace, &GDBM_READER());
                   4115:     if ($hashref) {
                   4116: 	my $version=$hashref->{"version:$rid"};
1.231     foxr     4117: 	$qresult.="version=$version&";
                   4118: 	my $scope;
                   4119: 	for ($scope=1;$scope<=$version;$scope++) {
1.309     albertel 4120: 	    my $vkeys=$hashref->{"$scope:keys:$rid"};
1.231     foxr     4121: 	    my @keys=split(/:/,$vkeys);
                   4122: 	    my $key;
                   4123: 	    $qresult.="$scope:keys=$vkeys&";
                   4124: 	    foreach $key (@keys) {
1.309     albertel 4125: 		$qresult.="$scope:$key=".$hashref->{"$scope:$rid:$key"}."&";
1.231     foxr     4126: 	    }                                  
                   4127: 	}
1.311     albertel 4128: 	if (&untie_user_hash($hashref)) {
1.231     foxr     4129: 	    $qresult=~s/\&$//;
1.387     albertel 4130: 	    &Reply( $client, \$qresult, $userinput);
1.231     foxr     4131: 	} else {
                   4132: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4133: 		    "while attempting restore\n", $userinput);
                   4134: 	}
                   4135:     } else {
                   4136: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4137: 		"while attempting restore\n", $userinput);
                   4138:     }
                   4139:   
                   4140:     return 1;
                   4141: 
                   4142: 
                   4143: }
                   4144: &register_handler("restore", \&restore_handler, 0,1,0);
1.234     foxr     4145: 
                   4146: #
1.324     raeburn  4147: #   Add a chat message to a synchronous discussion board.
1.234     foxr     4148: #
                   4149: # Parameters:
                   4150: #    $cmd                - Request keyword.
                   4151: #    $tail               - Tail of the command. A colon separated list
                   4152: #                          containing:
                   4153: #                          cdom    - Domain on which the chat board lives
1.324     raeburn  4154: #                          cnum    - Course containing the chat board.
                   4155: #                          newpost - Body of the posting.
                   4156: #                          group   - Optional group, if chat board is only 
                   4157: #                                    accessible in a group within the course 
1.234     foxr     4158: #   $client              - Socket open on the client.
                   4159: # Returns:
                   4160: #   1    - Indicating caller should keep on processing.
                   4161: #
                   4162: # Side-effects:
                   4163: #   writes a reply to the client.
                   4164: #
                   4165: #
                   4166: sub send_chat_handler {
                   4167:     my ($cmd, $tail, $client) = @_;
                   4168: 
                   4169:     
                   4170:     my $userinput = "$cmd:$tail";
                   4171: 
1.324     raeburn  4172:     my ($cdom,$cnum,$newpost,$group)=split(/\:/,$tail);
                   4173:     &chat_add($cdom,$cnum,$newpost,$group);
1.234     foxr     4174:     &Reply($client, "ok\n", $userinput);
                   4175: 
                   4176:     return 1;
                   4177: }
                   4178: &register_handler("chatsend", \&send_chat_handler, 0, 1, 0);
1.263     albertel 4179: 
1.234     foxr     4180: #
1.324     raeburn  4181: #   Retrieve the set of chat messages from a discussion board.
1.234     foxr     4182: #
                   4183: #  Parameters:
                   4184: #    $cmd             - Command keyword that initiated the request.
                   4185: #    $tail            - Remainder of the request after the command
                   4186: #                       keyword.  In this case a colon separated list of
                   4187: #                       chat domain    - Which discussion board.
                   4188: #                       chat id        - Discussion thread(?)
                   4189: #                       domain/user    - Authentication domain and username
                   4190: #                                        of the requesting person.
1.324     raeburn  4191: #                       group          - Optional course group containing
                   4192: #                                        the board.      
1.234     foxr     4193: #   $client           - Socket open on the client program.
                   4194: # Returns:
                   4195: #    1     - continue processing
                   4196: # Side effects:
                   4197: #    Response is written to the client.
                   4198: #
                   4199: sub retrieve_chat_handler {
                   4200:     my ($cmd, $tail, $client) = @_;
                   4201: 
                   4202: 
                   4203:     my $userinput = "$cmd:$tail";
                   4204: 
1.324     raeburn  4205:     my ($cdom,$cnum,$udom,$uname,$group)=split(/\:/,$tail);
1.234     foxr     4206:     my $reply='';
1.324     raeburn  4207:     foreach (&get_chat($cdom,$cnum,$udom,$uname,$group)) {
1.234     foxr     4208: 	$reply.=&escape($_).':';
                   4209:     }
                   4210:     $reply=~s/\:$//;
1.387     albertel 4211:     &Reply($client, \$reply, $userinput);
1.234     foxr     4212: 
                   4213: 
                   4214:     return 1;
                   4215: }
                   4216: &register_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
                   4217: 
                   4218: #
                   4219: #  Initiate a query of an sql database.  SQL query repsonses get put in
                   4220: #  a file for later retrieval.  This prevents sql query results from
                   4221: #  bottlenecking the system.  Note that with loncnew, perhaps this is
                   4222: #  less of an issue since multiple outstanding requests can be concurrently
                   4223: #  serviced.
                   4224: #
                   4225: #  Parameters:
1.535     raeburn  4226: #     $cmd       - Command keyword that initiated the request.
1.234     foxr     4227: #     $tail      - Remainder of the command after the keyword.
                   4228: #                  For this function, this consists of a query and
                   4229: #                  3 arguments that are self-documentingly labelled
                   4230: #                  in the original arg1, arg2, arg3.
                   4231: #     $client    - Socket open on the client.
                   4232: # Return:
                   4233: #    1   - Indicating processing should continue.
                   4234: # Side-effects:
                   4235: #    a reply is written to $client.
                   4236: #
                   4237: sub send_query_handler {
                   4238:     my ($cmd, $tail, $client) = @_;
                   4239: 
                   4240:     my $userinput = "$cmd:$tail";
                   4241: 
                   4242:     my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
                   4243:     $query=~s/\n*$//g;
1.534     raeburn  4244:     if (($query eq 'usersearch') || ($query eq 'instdirsearch')) {
                   4245:         my $usersearchconf = &get_usersearch_config($currentdomainid,'directorysrch');
                   4246:         my $earlyout;
                   4247:         if (ref($usersearchconf) eq 'HASH') {
                   4248:             if ($currentdomainid eq $clienthomedom) {
                   4249:                 if ($query eq 'usersearch') {
                   4250:                     if ($usersearchconf->{'lcavailable'} eq '0') {
                   4251:                         $earlyout = 1;
                   4252:                     }
                   4253:                 } else {
                   4254:                     if ($usersearchconf->{'available'} eq '0') {
                   4255:                         $earlyout = 1;
                   4256:                     }
                   4257:                 }
                   4258:             } else {
                   4259:                 if ($query eq 'usersearch') {
                   4260:                     if ($usersearchconf->{'lclocalonly'}) {
                   4261:                         $earlyout = 1;
                   4262:                     }
                   4263:                 } else {
                   4264:                     if ($usersearchconf->{'localonly'}) {
                   4265:                         $earlyout = 1;
                   4266:                     }
                   4267:                 }
                   4268:             }
                   4269:         }
                   4270:         if ($earlyout) {
                   4271:             &Reply($client, "query_not_authorized\n");
                   4272:             return 1;
                   4273:         }
                   4274:     }
1.234     foxr     4275:     &Reply($client, "". &sql_reply("$clientname\&$query".
                   4276: 				"\&$arg1"."\&$arg2"."\&$arg3")."\n",
                   4277: 	  $userinput);
                   4278:     
                   4279:     return 1;
                   4280: }
                   4281: &register_handler("querysend", \&send_query_handler, 0, 1, 0);
                   4282: 
                   4283: #
                   4284: #   Add a reply to an sql query.  SQL queries are done asyncrhonously.
                   4285: #   The query is submitted via a "querysend" transaction.
                   4286: #   There it is passed on to the lonsql daemon, queued and issued to
                   4287: #   mysql.
                   4288: #     This transaction is invoked when the sql transaction is complete
                   4289: #   it stores the query results in flie and indicates query completion.
                   4290: #   presumably local software then fetches this response... I'm guessing
                   4291: #   the sequence is: lonc does a querysend, we ask lonsql to do it.
                   4292: #   lonsql on completion of the query interacts with the lond of our
                   4293: #   client to do a query reply storing two files:
                   4294: #    - id     - The results of the query.
                   4295: #    - id.end - Indicating the transaction completed. 
                   4296: #    NOTE: id is a unique id assigned to the query and querysend time.
                   4297: # Parameters:
                   4298: #    $cmd        - Command keyword that initiated this request.
                   4299: #    $tail       - Remainder of the tail.  In this case that's a colon
                   4300: #                  separated list containing the query Id and the 
                   4301: #                  results of the query.
                   4302: #    $client     - Socket open on the client.
                   4303: # Return:
                   4304: #    1           - Indicating that we should continue processing.
                   4305: # Side effects:
                   4306: #    ok written to the client.
                   4307: #
                   4308: sub reply_query_handler {
                   4309:     my ($cmd, $tail, $client) = @_;
                   4310: 
                   4311: 
                   4312:     my $userinput = "$cmd:$tail";
                   4313: 
1.339     albertel 4314:     my ($id,$reply)=split(/:/,$tail); 
1.234     foxr     4315:     my $store;
                   4316:     my $execdir=$perlvar{'lonDaemons'};
                   4317:     if ($store=IO::File->new(">$execdir/tmp/$id")) {
                   4318: 	$reply=~s/\&/\n/g;
                   4319: 	print $store $reply;
                   4320: 	close $store;
                   4321: 	my $store2=IO::File->new(">$execdir/tmp/$id.end");
                   4322: 	print $store2 "done\n";
                   4323: 	close $store2;
                   4324: 	&Reply($client, "ok\n", $userinput);
                   4325:     } else {
                   4326: 	&Failure($client, "error: ".($!+0)
                   4327: 		." IO::File->new Failed ".
                   4328: 		"while attempting queryreply\n", $userinput);
                   4329:     }
                   4330:  
                   4331: 
                   4332:     return 1;
                   4333: }
                   4334: &register_handler("queryreply", \&reply_query_handler, 0, 1, 0);
                   4335: 
                   4336: #
                   4337: #  Process the courseidput request.  Not quite sure what this means
                   4338: #  at the system level sense.  It appears a gdbm file in the 
                   4339: #  /home/httpd/lonUsers/$domain/nohist_courseids is tied and
                   4340: #  a set of entries made in that database.
                   4341: #
                   4342: # Parameters:
                   4343: #   $cmd      - The command keyword that initiated this request.
                   4344: #   $tail     - Tail of the command.  In this case consists of a colon
                   4345: #               separated list contaning the domain to apply this to and
                   4346: #               an ampersand separated list of keyword=value pairs.
1.272     raeburn  4347: #               Each value is a colon separated list that includes:  
                   4348: #               description, institutional code and course owner.
                   4349: #               For backward compatibility with versions included
                   4350: #               in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
                   4351: #               code and/or course owner are preserved from the existing 
                   4352: #               record when writing a new record in response to 1.1 or 
                   4353: #               1.2 implementations of lonnet::flushcourselogs().   
                   4354: #                      
1.234     foxr     4355: #   $client   - Socket open on the client.
                   4356: # Returns:
                   4357: #   1    - indicating that processing should continue
                   4358: #
                   4359: # Side effects:
                   4360: #   reply is written to the client.
                   4361: #
                   4362: sub put_course_id_handler {
                   4363:     my ($cmd, $tail, $client) = @_;
                   4364: 
                   4365: 
                   4366:     my $userinput = "$cmd:$tail";
                   4367: 
1.266     raeburn  4368:     my ($udom, $what) = split(/:/, $tail,2);
1.234     foxr     4369:     chomp($what);
                   4370:     my $now=time;
                   4371:     my @pairs=split(/\&/,$what);
                   4372: 
                   4373:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   4374:     if ($hashref) {
                   4375: 	foreach my $pair (@pairs) {
1.271     raeburn  4376:             my ($key,$courseinfo) = split(/=/,$pair,2);
                   4377:             $courseinfo =~ s/=/:/g;
1.384     raeburn  4378:             if (defined($hashref->{$key})) {
                   4379:                 my $value = &Apache::lonnet::thaw_unescape($hashref->{$key});
                   4380:                 if (ref($value) eq 'HASH') {
                   4381:                     my @items = ('description','inst_code','owner','type');
                   4382:                     my @new_items = split(/:/,$courseinfo,-1);
                   4383:                     my %storehash; 
                   4384:                     for (my $i=0; $i<@new_items; $i++) {
1.391     raeburn  4385:                         $storehash{$items[$i]} = &unescape($new_items[$i]);
1.384     raeburn  4386:                     }
                   4387:                     $hashref->{$key} = 
                   4388:                         &Apache::lonnet::freeze_escape(\%storehash);
                   4389:                     my $unesc_key = &unescape($key);
                   4390:                     $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
                   4391:                     next;
1.383     raeburn  4392:                 }
1.384     raeburn  4393:             }
                   4394:             my @current_items = split(/:/,$hashref->{$key},-1);
                   4395:             shift(@current_items); # remove description
                   4396:             pop(@current_items);   # remove last access
                   4397:             my $numcurrent = scalar(@current_items);
                   4398:             if ($numcurrent > 3) {
                   4399:                 $numcurrent = 3;
                   4400:             }
                   4401:             my @new_items = split(/:/,$courseinfo,-1);
                   4402:             my $numnew = scalar(@new_items);
                   4403:             if ($numcurrent > 0) {
                   4404:                 if ($numnew <= $numcurrent) { # flushcourselogs() from pre 2.2 
                   4405:                     for (my $j=$numcurrent-$numnew; $j>=0; $j--) {
                   4406:                         $courseinfo .= ':'.$current_items[$numcurrent-$j-1];
1.333     raeburn  4407:                     }
1.272     raeburn  4408:                 }
                   4409:             }
1.384     raeburn  4410:             $hashref->{$key}=$courseinfo.':'.$now;
1.234     foxr     4411: 	}
1.311     albertel 4412: 	if (&untie_domain_hash($hashref)) {
1.253     foxr     4413: 	    &Reply( $client, "ok\n", $userinput);
1.234     foxr     4414: 	} else {
1.253     foxr     4415: 	    &Failure($client, "error: ".($!+0)
1.234     foxr     4416: 		     ." untie(GDBM) Failed ".
                   4417: 		     "while attempting courseidput\n", $userinput);
                   4418: 	}
                   4419:     } else {
1.253     foxr     4420: 	&Failure($client, "error: ".($!+0)
1.234     foxr     4421: 		 ." tie(GDBM) Failed ".
                   4422: 		 "while attempting courseidput\n", $userinput);
                   4423:     }
                   4424: 
                   4425:     return 1;
                   4426: }
                   4427: &register_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
                   4428: 
1.383     raeburn  4429: sub put_course_id_hash_handler {
                   4430:     my ($cmd, $tail, $client) = @_;
                   4431:     my $userinput = "$cmd:$tail";
1.384     raeburn  4432:     my ($udom,$mode,$what) = split(/:/, $tail,3);
1.383     raeburn  4433:     chomp($what);
                   4434:     my $now=time;
                   4435:     my @pairs=split(/\&/,$what);
1.384     raeburn  4436:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
1.383     raeburn  4437:     if ($hashref) {
                   4438:         foreach my $pair (@pairs) {
                   4439:             my ($key,$value)=split(/=/,$pair);
1.384     raeburn  4440:             my $unesc_key = &unescape($key);
                   4441:             if ($mode ne 'timeonly') {
                   4442:                 if (!defined($hashref->{&escape('lasttime:'.$unesc_key)})) {
                   4443:                     my $curritems = &Apache::lonnet::thaw_unescape($key); 
                   4444:                     if (ref($curritems) ne 'HASH') {
                   4445:                         my @current_items = split(/:/,$hashref->{$key},-1);
                   4446:                         my $lasttime = pop(@current_items);
                   4447:                         $hashref->{&escape('lasttime:'.$unesc_key)} = $lasttime;
                   4448:                     } else {
                   4449:                         $hashref->{&escape('lasttime:'.$unesc_key)} = '';
                   4450:                     }
                   4451:                 } 
                   4452:                 $hashref->{$key} = $value;
                   4453:             }
                   4454:             if ($mode ne 'notime') {
                   4455:                 $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
                   4456:             }
1.383     raeburn  4457:         }
                   4458:         if (&untie_domain_hash($hashref)) {
                   4459:             &Reply($client, "ok\n", $userinput);
                   4460:         } else {
                   4461:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4462:                      "while attempting courseidputhash\n", $userinput);
                   4463:         }
                   4464:     } else {
                   4465:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4466:                   "while attempting courseidputhash\n", $userinput);
                   4467:     }
                   4468:     return 1;
                   4469: }
                   4470: &register_handler("courseidputhash", \&put_course_id_hash_handler, 0, 1, 0);
                   4471: 
1.234     foxr     4472: #  Retrieves the value of a course id resource keyword pattern
                   4473: #  defined since a starting date.  Both the starting date and the
                   4474: #  keyword pattern are optional.  If the starting date is not supplied it
                   4475: #  is treated as the beginning of time.  If the pattern is not found,
                   4476: #  it is treatred as "." matching everything.
                   4477: #
                   4478: #  Parameters:
                   4479: #     $cmd     - Command keyword that resulted in us being dispatched.
                   4480: #     $tail    - The remainder of the command that, in this case, consists
                   4481: #                of a colon separated list of:
                   4482: #                 domain   - The domain in which the course database is 
                   4483: #                            defined.
                   4484: #                 since    - Optional parameter describing the minimum
                   4485: #                            time of definition(?) of the resources that
                   4486: #                            will match the dump.
                   4487: #                 description - regular expression that is used to filter
                   4488: #                            the dump.  Only keywords matching this regexp
                   4489: #                            will be used.
1.272     raeburn  4490: #                 institutional code - optional supplied code to filter 
                   4491: #                            the dump. Only courses with an institutional code 
                   4492: #                            that match the supplied code will be returned.
1.336     raeburn  4493: #                 owner    - optional supplied username and domain of owner to
                   4494: #                            filter the dump.  Only courses for which the course
                   4495: #                            owner matches the supplied username and/or domain
                   4496: #                            will be returned. Pre-2.2.0 legacy entries from 
                   4497: #                            nohist_courseiddump will only contain usernames.
1.384     raeburn  4498: #                 type     - optional parameter for selection 
1.418     raeburn  4499: #                 regexp_ok - if 1 or -1 allow the supplied institutional code
                   4500: #                            filter to behave as a regular expression:
                   4501: #	                      1 will not exclude the course if the instcode matches the RE 
                   4502: #                            -1 will exclude the course if the instcode matches the RE
1.384     raeburn  4503: #                 rtn_as_hash - whether to return the information available for
                   4504: #                            each matched item as a frozen hash of all 
                   4505: #                            key, value pairs in the item's hash, or as a 
                   4506: #                            colon-separated list of (in order) description,
                   4507: #                            institutional code, and course owner.
1.404     raeburn  4508: #                 selfenrollonly - filter by courses allowing self-enrollment  
                   4509: #                                  now or in the future (selfenrollonly = 1).
                   4510: #                 catfilter - filter by course category, assigned to a course 
                   4511: #                             using manually defined categories (i.e., not
1.407     raeburn  4512: #                             self-cataloging based on on institutional code).   
1.404     raeburn  4513: #                 showhidden - include course in results even if course  
1.407     raeburn  4514: #                              was set to be excluded from course catalog (DC only).
1.404     raeburn  4515: #                 caller -  if set to 'coursecatalog', courses set to be hidden
                   4516: #                           from course catalog will be excluded from results (unless
                   4517: #                           overridden by "showhidden".
1.427     raeburn  4518: #                 cloner - escaped username:domain of course cloner (if picking course to
1.419     raeburn  4519: #                          clone).
                   4520: #                 cc_clone_list - escaped comma separated list of courses for which 
                   4521: #                                 course cloner has active CC role (and so can clone
                   4522: #                                 automatically).
1.427     raeburn  4523: #                 cloneonly - filter by courses for which cloner has rights to clone.
                   4524: #                 createdbefore - include courses for which creation date preceeded this date.
                   4525: #                 createdafter - include courses for which creation date followed this date.
                   4526: #                 creationcontext - include courses created in specified context 
1.404     raeburn  4527: #
1.445     raeburn  4528: #                 domcloner - flag to indicate if user can create CCs in course's domain.
1.505     raeburn  4529: #                             If so, ability to clone course is automatic.
                   4530: #                 hasuniquecode - filter by courses for which a six character unique code has 
                   4531: #                                 been set.
1.445     raeburn  4532: #
1.234     foxr     4533: #     $client  - The socket open on the client.
                   4534: # Returns:
                   4535: #    1     - Continue processing.
                   4536: # Side Effects:
                   4537: #   a reply is written to $client.
                   4538: sub dump_course_id_handler {
                   4539:     my ($cmd, $tail, $client) = @_;
1.494     droeschl 4540: 
                   4541:     my $res = LONCAPA::Lond::dump_course_id_handler($tail);
                   4542:     if ($res =~ /^error:/) {
                   4543:         Failure($client, \$res, "$cmd:$tail");
                   4544:     } else {
                   4545:         Reply($client, \$res, "$cmd:$tail");
                   4546:     }
                   4547: 
                   4548:     return 1;  
                   4549: 
                   4550:     #TODO remove
1.234     foxr     4551:     my $userinput = "$cmd:$tail";
                   4552: 
1.333     raeburn  4553:     my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter,
1.404     raeburn  4554:         $typefilter,$regexp_ok,$rtn_as_hash,$selfenrollonly,$catfilter,$showhidden,
1.427     raeburn  4555:         $caller,$cloner,$cc_clone_list,$cloneonly,$createdbefore,$createdafter,
1.505     raeburn  4556:         $creationcontext,$domcloner,$hasuniquecode) =split(/:/,$tail);
1.397     raeburn  4557:     my $now = time;
1.419     raeburn  4558:     my ($cloneruname,$clonerudom,%cc_clone);
1.234     foxr     4559:     if (defined($description)) {
                   4560: 	$description=&unescape($description);
                   4561:     } else {
                   4562: 	$description='.';
                   4563:     }
1.266     raeburn  4564:     if (defined($instcodefilter)) {
                   4565:         $instcodefilter=&unescape($instcodefilter);
                   4566:     } else {
                   4567:         $instcodefilter='.';
                   4568:     }
1.336     raeburn  4569:     my ($ownerunamefilter,$ownerdomfilter);
1.266     raeburn  4570:     if (defined($ownerfilter)) {
                   4571:         $ownerfilter=&unescape($ownerfilter);
1.336     raeburn  4572:         if ($ownerfilter ne '.' && defined($ownerfilter)) {
                   4573:             if ($ownerfilter =~ /^([^:]*):([^:]*)$/) {
                   4574:                  $ownerunamefilter = $1;
                   4575:                  $ownerdomfilter = $2;
                   4576:             } else {
                   4577:                 $ownerunamefilter = $ownerfilter;
                   4578:                 $ownerdomfilter = '';
                   4579:             }
                   4580:         }
1.266     raeburn  4581:     } else {
                   4582:         $ownerfilter='.';
                   4583:     }
1.336     raeburn  4584: 
1.282     raeburn  4585:     if (defined($coursefilter)) {
                   4586:         $coursefilter=&unescape($coursefilter);
                   4587:     } else {
                   4588:         $coursefilter='.';
                   4589:     }
1.333     raeburn  4590:     if (defined($typefilter)) {
                   4591:         $typefilter=&unescape($typefilter);
                   4592:     } else {
                   4593:         $typefilter='.';
                   4594:     }
1.344     raeburn  4595:     if (defined($regexp_ok)) {
                   4596:         $regexp_ok=&unescape($regexp_ok);
                   4597:     }
1.401     raeburn  4598:     if (defined($catfilter)) {
                   4599:         $catfilter=&unescape($catfilter);
                   4600:     }
1.419     raeburn  4601:     if (defined($cloner)) {
                   4602:         $cloner = &unescape($cloner);
                   4603:         ($cloneruname,$clonerudom) = ($cloner =~ /^($LONCAPA::match_username):($LONCAPA::match_domain)$/); 
                   4604:     }
                   4605:     if (defined($cc_clone_list)) {
                   4606:         $cc_clone_list = &unescape($cc_clone_list);
                   4607:         my @cc_cloners = split('&',$cc_clone_list);
                   4608:         foreach my $cid (@cc_cloners) {
                   4609:             my ($clonedom,$clonenum) = split(':',$cid);
                   4610:             next if ($clonedom ne $udom); 
                   4611:             $cc_clone{$clonedom.'_'.$clonenum} = 1;
                   4612:         } 
                   4613:     }
1.431     raeburn  4614:     if ($createdbefore ne '') {
1.427     raeburn  4615:         $createdbefore = &unescape($createdbefore);
                   4616:     } else {
                   4617:        $createdbefore = 0;
                   4618:     }
1.431     raeburn  4619:     if ($createdafter ne '') {
1.427     raeburn  4620:         $createdafter = &unescape($createdafter);
                   4621:     } else {
                   4622:         $createdafter = 0;
                   4623:     }
1.431     raeburn  4624:     if ($creationcontext ne '') {
1.427     raeburn  4625:         $creationcontext = &unescape($creationcontext);
                   4626:     } else {
                   4627:         $creationcontext = '.';
                   4628:     }
1.505     raeburn  4629:     unless ($hasuniquecode) {
                   4630:         $hasuniquecode = '.';
                   4631:     }
1.384     raeburn  4632:     my $unpack = 1;
1.485     raeburn  4633:     if ($description eq '.' && $instcodefilter eq '.' && $ownerfilter eq '.' && 
1.384     raeburn  4634:         $typefilter eq '.') {
                   4635:         $unpack = 0;
                   4636:     }
                   4637:     if (!defined($since)) { $since=0; }
1.234     foxr     4638:     my $qresult='';
                   4639:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   4640:     if ($hashref) {
1.384     raeburn  4641: 	while (my ($key,$value) = each(%$hashref)) {
1.397     raeburn  4642:             my ($unesc_key,$lasttime_key,$lasttime,$is_hash,%val,
1.427     raeburn  4643:                 %unesc_val,$selfenroll_end,$selfenroll_types,$created,
                   4644:                 $context);
1.384     raeburn  4645:             $unesc_key = &unescape($key);
                   4646:             if ($unesc_key =~ /^lasttime:/) {
                   4647:                 next;
                   4648:             } else {
                   4649:                 $lasttime_key = &escape('lasttime:'.$unesc_key);
                   4650:             }
                   4651:             if ($hashref->{$lasttime_key} ne '') {
                   4652:                 $lasttime = $hashref->{$lasttime_key};
                   4653:                 next if ($lasttime<$since);
                   4654:             }
1.419     raeburn  4655:             my ($canclone,$valchange);
1.384     raeburn  4656:             my $items = &Apache::lonnet::thaw_unescape($value);
                   4657:             if (ref($items) eq 'HASH') {
1.429     raeburn  4658:                 if ($hashref->{$lasttime_key} eq '') {
1.430     raeburn  4659:                     next if ($since > 1);
1.429     raeburn  4660:                 }
1.384     raeburn  4661:                 $is_hash =  1;
1.445     raeburn  4662:                 if ($domcloner) {
                   4663:                     $canclone = 1;
                   4664:                 } elsif (defined($clonerudom)) {
1.419     raeburn  4665:                     if ($items->{'cloners'}) {
                   4666:                         my @cloneable = split(',',$items->{'cloners'});
                   4667:                         if (@cloneable) {
                   4668:                             if (grep(/^\*$/,@cloneable))  {
                   4669:                                 $canclone = 1;
                   4670:                             } elsif (grep(/^\*:\Q$clonerudom\E$/,@cloneable)) {
                   4671:                                 $canclone = 1;
                   4672:                             } elsif (grep(/^\Q$cloneruname\E:\Q$clonerudom\E$/,@cloneable)) {
                   4673:                                 $canclone = 1;
                   4674:                             }
                   4675:                         }
                   4676:                         unless ($canclone) {
                   4677:                             if ($cloneruname ne '' && $clonerudom ne '') {
                   4678:                                 if ($cc_clone{$unesc_key}) {
                   4679:                                     $canclone = 1;
                   4680:                                     $items->{'cloners'} .= ','.$cloneruname.':'.
                   4681:                                                            $clonerudom;
                   4682:                                     $valchange = 1;
                   4683:                                 }
                   4684:                             }
                   4685:                         }
                   4686:                     } elsif (defined($cloneruname)) {
                   4687:                         if ($cc_clone{$unesc_key}) {
                   4688:                             $canclone = 1;
                   4689:                             $items->{'cloners'} = $cloneruname.':'.$clonerudom;
                   4690:                             $valchange = 1;
                   4691:                         }
1.437     raeburn  4692:                         unless ($canclone) {
                   4693:                             if ($items->{'owner'} =~ /:/) {
                   4694:                                 if ($items->{'owner'} eq $cloner) {
                   4695:                                     $canclone = 1;
                   4696:                                 }
1.444     raeburn  4697:                             } elsif ($cloner eq $items->{'owner'}.':'.$udom) {
1.437     raeburn  4698:                                 $canclone = 1;
                   4699:                             }
                   4700:                             if ($canclone) {
                   4701:                                 $items->{'cloners'} = $cloneruname.':'.$clonerudom;
                   4702:                                 $valchange = 1;
                   4703:                             }
                   4704:                         }
1.419     raeburn  4705:                     }
                   4706:                 }
1.384     raeburn  4707:                 if ($unpack || !$rtn_as_hash) {
                   4708:                     $unesc_val{'descr'} = $items->{'description'};
                   4709:                     $unesc_val{'inst_code'} = $items->{'inst_code'};
                   4710:                     $unesc_val{'owner'} = $items->{'owner'};
                   4711:                     $unesc_val{'type'} = $items->{'type'};
1.419     raeburn  4712:                     $unesc_val{'cloners'} = $items->{'cloners'};
1.427     raeburn  4713:                     $unesc_val{'created'} = $items->{'created'};
                   4714:                     $unesc_val{'context'} = $items->{'context'};
1.404     raeburn  4715:                 }
                   4716:                 $selfenroll_types = $items->{'selfenroll_types'};
                   4717:                 $selfenroll_end = $items->{'selfenroll_end_date'};
1.427     raeburn  4718:                 $created = $items->{'created'};
                   4719:                 $context = $items->{'context'};
1.505     raeburn  4720:                 if ($hasuniquecode ne '.') {
                   4721:                     next unless ($items->{'uniquecode'});
                   4722:                 }
1.404     raeburn  4723:                 if ($selfenrollonly) {
                   4724:                     next if (!$selfenroll_types);
                   4725:                     if (($selfenroll_end > 0) && ($selfenroll_end <= $now)) {
                   4726:                         next;
1.397     raeburn  4727:                     }
1.404     raeburn  4728:                 }
1.427     raeburn  4729:                 if ($creationcontext ne '.') {
                   4730:                     next if (($context ne '') && ($context ne $creationcontext));  
                   4731:                 }
                   4732:                 if ($createdbefore > 0) {
                   4733:                     next if (($created eq '') || ($created > $createdbefore));   
                   4734:                 }
                   4735:                 if ($createdafter > 0) {
                   4736:                     next if (($created eq '') || ($created <= $createdafter)); 
                   4737:                 }
1.404     raeburn  4738:                 if ($catfilter ne '') {
1.406     raeburn  4739:                     next if ($items->{'categories'} eq '');
                   4740:                     my @categories = split('&',$items->{'categories'}); 
1.407     raeburn  4741:                     next if (@categories == 0);
                   4742:                     my @subcats = split('&',$catfilter);
                   4743:                     my $matchcat = 0;
                   4744:                     foreach my $cat (@categories) {
                   4745:                         if (grep(/^\Q$cat\E$/,@subcats)) {
                   4746:                             $matchcat = 1;
                   4747:                             last;
                   4748:                         }
                   4749:                     }
                   4750:                     next if (!$matchcat);
1.404     raeburn  4751:                 }
                   4752:                 if ($caller eq 'coursecatalog') {
1.405     raeburn  4753:                     if ($items->{'hidefromcat'} eq 'yes') {
                   4754:                         next if !$showhidden;
1.401     raeburn  4755:                     }
1.384     raeburn  4756:                 }
1.383     raeburn  4757:             } else {
1.401     raeburn  4758:                 next if ($catfilter ne '');
1.419     raeburn  4759:                 next if ($selfenrollonly);
1.427     raeburn  4760:                 next if ($createdbefore || $createdafter);
                   4761:                 next if ($creationcontext ne '.');
1.419     raeburn  4762:                 if ((defined($clonerudom)) && (defined($cloneruname)))  {
                   4763:                     if ($cc_clone{$unesc_key}) {
                   4764:                         $canclone = 1;
                   4765:                         $val{'cloners'} = &escape($cloneruname.':'.$clonerudom);
                   4766:                     }
                   4767:                 }
1.384     raeburn  4768:                 $is_hash =  0;
1.388     raeburn  4769:                 my @courseitems = split(/:/,$value);
1.403     raeburn  4770:                 $lasttime = pop(@courseitems);
1.402     raeburn  4771:                 if ($hashref->{$lasttime_key} eq '') {
                   4772:                     next if ($lasttime<$since);
                   4773:                 }
1.384     raeburn  4774: 	        ($val{'descr'},$val{'inst_code'},$val{'owner'},$val{'type'}) = @courseitems;
1.383     raeburn  4775:             }
1.419     raeburn  4776:             if ($cloneonly) {
                   4777:                next unless ($canclone);
                   4778:             }
1.266     raeburn  4779:             my $match = 1;
1.384     raeburn  4780: 	    if ($description ne '.') {
                   4781:                 if (!$is_hash) {
                   4782:                     $unesc_val{'descr'} = &unescape($val{'descr'});
                   4783:                 }
                   4784:                 if (eval{$unesc_val{'descr'} !~ /\Q$description\E/i}) {
1.266     raeburn  4785:                     $match = 0;
1.384     raeburn  4786:                 }
1.266     raeburn  4787:             }
1.384     raeburn  4788:             if ($instcodefilter ne '.') {
                   4789:                 if (!$is_hash) {
                   4790:                     $unesc_val{'inst_code'} = &unescape($val{'inst_code'});
                   4791:                 }
1.418     raeburn  4792:                 if ($regexp_ok == 1) {
1.384     raeburn  4793:                     if (eval{$unesc_val{'inst_code'} !~ /$instcodefilter/}) {
1.344     raeburn  4794:                         $match = 0;
                   4795:                     }
1.418     raeburn  4796:                 } elsif ($regexp_ok == -1) {
                   4797:                     if (eval{$unesc_val{'inst_code'} =~ /$instcodefilter/}) {
                   4798:                         $match = 0;
                   4799:                     }
1.344     raeburn  4800:                 } else {
1.384     raeburn  4801:                     if (eval{$unesc_val{'inst_code'} !~ /\Q$instcodefilter\E/i}) {
1.344     raeburn  4802:                         $match = 0;
                   4803:                     }
1.266     raeburn  4804:                 }
1.234     foxr     4805: 	    }
1.384     raeburn  4806:             if ($ownerfilter ne '.') {
                   4807:                 if (!$is_hash) {
                   4808:                     $unesc_val{'owner'} = &unescape($val{'owner'});
                   4809:                 }
1.336     raeburn  4810:                 if (($ownerunamefilter ne '') && ($ownerdomfilter ne '')) {
1.384     raeburn  4811:                     if ($unesc_val{'owner'} =~ /:/) {
                   4812:                         if (eval{$unesc_val{'owner'} !~ 
                   4813:                              /\Q$ownerunamefilter\E:\Q$ownerdomfilter\E$/i}) {
1.336     raeburn  4814:                             $match = 0;
                   4815:                         } 
                   4816:                     } else {
1.384     raeburn  4817:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336     raeburn  4818:                             $match = 0;
                   4819:                         }
                   4820:                     }
                   4821:                 } elsif ($ownerunamefilter ne '') {
1.384     raeburn  4822:                     if ($unesc_val{'owner'} =~ /:/) {
                   4823:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E:[^:]+$/i}) {
1.336     raeburn  4824:                              $match = 0;
                   4825:                         }
                   4826:                     } else {
1.384     raeburn  4827:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336     raeburn  4828:                             $match = 0;
                   4829:                         }
                   4830:                     }
                   4831:                 } elsif ($ownerdomfilter ne '') {
1.384     raeburn  4832:                     if ($unesc_val{'owner'} =~ /:/) {
                   4833:                         if (eval{$unesc_val{'owner'} !~ /^[^:]+:\Q$ownerdomfilter\E/}) {
1.336     raeburn  4834:                              $match = 0;
                   4835:                         }
                   4836:                     } else {
                   4837:                         if ($ownerdomfilter ne $udom) {
                   4838:                             $match = 0;
                   4839:                         }
                   4840:                     }
1.266     raeburn  4841:                 }
                   4842:             }
1.384     raeburn  4843:             if ($coursefilter ne '.') {
                   4844:                 if (eval{$unesc_key !~ /^$udom(_)\Q$coursefilter\E$/}) {
1.282     raeburn  4845:                     $match = 0;
                   4846:                 }
                   4847:             }
1.384     raeburn  4848:             if ($typefilter ne '.') {
                   4849:                 if (!$is_hash) {
                   4850:                     $unesc_val{'type'} = &unescape($val{'type'});
                   4851:                 }
                   4852:                 if ($unesc_val{'type'} eq '') {
1.333     raeburn  4853:                     if ($typefilter ne 'Course') {
                   4854:                         $match = 0;
                   4855:                     }
1.383     raeburn  4856:                 } else {
1.384     raeburn  4857:                     if (eval{$unesc_val{'type'} !~ /^\Q$typefilter\E$/}) {
1.333     raeburn  4858:                         $match = 0;
                   4859:                     }
                   4860:                 }
                   4861:             }
1.266     raeburn  4862:             if ($match == 1) {
1.384     raeburn  4863:                 if ($rtn_as_hash) {
                   4864:                     if ($is_hash) {
1.419     raeburn  4865:                         if ($valchange) {
                   4866:                             my $newvalue = &Apache::lonnet::freeze_escape($items);
                   4867:                             $qresult.=$key.'='.$newvalue.'&';
                   4868:                         } else {
                   4869:                             $qresult.=$key.'='.$value.'&';
                   4870:                         }
1.384     raeburn  4871:                     } else {
1.388     raeburn  4872:                         my %rtnhash = ( 'description' => &unescape($val{'descr'}),
                   4873:                                         'inst_code' => &unescape($val{'inst_code'}),
                   4874:                                         'owner'     => &unescape($val{'owner'}),
                   4875:                                         'type'      => &unescape($val{'type'}),
1.419     raeburn  4876:                                         'cloners'   => &unescape($val{'cloners'}),
1.384     raeburn  4877:                                       );
                   4878:                         my $items = &Apache::lonnet::freeze_escape(\%rtnhash);
                   4879:                         $qresult.=$key.'='.$items.'&';
                   4880:                     }
1.383     raeburn  4881:                 } else {
1.384     raeburn  4882:                     if ($is_hash) {
                   4883:                         $qresult .= $key.'='.&escape($unesc_val{'descr'}).':'.
                   4884:                                     &escape($unesc_val{'inst_code'}).':'.
                   4885:                                     &escape($unesc_val{'owner'}).'&';
                   4886:                     } else {
                   4887:                         $qresult .= $key.'='.$val{'descr'}.':'.$val{'inst_code'}.
                   4888:                                     ':'.$val{'owner'}.'&';
                   4889:                     }
1.383     raeburn  4890:                 }
1.266     raeburn  4891:             }
1.234     foxr     4892: 	}
1.311     albertel 4893: 	if (&untie_domain_hash($hashref)) {
1.234     foxr     4894: 	    chop($qresult);
1.387     albertel 4895: 	    &Reply($client, \$qresult, $userinput);
1.234     foxr     4896: 	} else {
                   4897: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4898: 		    "while attempting courseiddump\n", $userinput);
                   4899: 	}
                   4900:     } else {
                   4901: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4902: 		"while attempting courseiddump\n", $userinput);
                   4903:     }
                   4904:     return 1;
                   4905: }
                   4906: &register_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
1.238     foxr     4907: 
1.438     raeburn  4908: sub course_lastaccess_handler {
                   4909:     my ($cmd, $tail, $client) = @_;
                   4910:     my $userinput = "$cmd:$tail";
                   4911:     my ($cdom,$cnum) = split(':',$tail); 
                   4912:     my (%lastaccess,$qresult);
                   4913:     my $hashref = &tie_domain_hash($cdom, "nohist_courseids", &GDBM_WRCREAT());
                   4914:     if ($hashref) {
                   4915:         while (my ($key,$value) = each(%$hashref)) {
                   4916:             my ($unesc_key,$lasttime);
                   4917:             $unesc_key = &unescape($key);
                   4918:             if ($cnum) {
                   4919:                 next unless ($unesc_key =~ /\Q$cdom\E_\Q$cnum\E$/);
                   4920:             }
                   4921:             if ($unesc_key =~ /^lasttime:($LONCAPA::match_domain\_$LONCAPA::match_courseid)/) {
                   4922:                 $lastaccess{$1} = $value;
                   4923:             } else {
                   4924:                 my $items = &Apache::lonnet::thaw_unescape($value);
                   4925:                 if (ref($items) eq 'HASH') {
                   4926:                     unless ($lastaccess{$unesc_key}) {
                   4927:                         $lastaccess{$unesc_key} = '';
                   4928:                     }
                   4929:                 } else {
                   4930:                     my @courseitems = split(':',$value);
                   4931:                     $lastaccess{$unesc_key} = pop(@courseitems);
                   4932:                 }
                   4933:             }
                   4934:         }
                   4935:         foreach my $cid (sort(keys(%lastaccess))) {
                   4936:             $qresult.=&escape($cid).'='.$lastaccess{$cid}.'&'; 
                   4937:         }
                   4938:         if (&untie_domain_hash($hashref)) {
                   4939:             if ($qresult) {
                   4940:                 chop($qresult);
                   4941:             }
                   4942:             &Reply($client, \$qresult, $userinput);
                   4943:         } else {
                   4944:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4945:                     "while attempting lastacourseaccess\n", $userinput);
                   4946:         }
                   4947:     } else {
                   4948:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4949:                 "while attempting lastcourseaccess\n", $userinput);
                   4950:     }
                   4951:     return 1;
                   4952: }
                   4953: &register_handler("courselastaccess",\&course_lastaccess_handler, 0, 1, 0);
                   4954: 
1.561     raeburn  4955: sub course_sessions_handler {
                   4956:     my ($cmd, $tail, $client) = @_;
                   4957:     my $userinput = "$cmd:$tail";
                   4958:     my ($cdom,$cnum,$lastactivity) = split(':',$tail);
                   4959:     my $dbsuffix = '_'.$cdom.'_'.$cnum.'.db';
                   4960:     my (%sessions,$qresult);
                   4961:     my $now=time;
                   4962:     if (opendir(DIR,$perlvar{'lonIDsDir'})) {
                   4963:         my $filename;
                   4964:         while ($filename=readdir(DIR)) {
                   4965:             next if ($filename=~/^\./);
                   4966:             next if ($filename=~/^publicuser_/);
                   4967:             next if ($filename=~/^[a-f0-9]+_(linked|lti_\d+)\.id$/);
1.562     raeburn  4968:             if ($filename =~ /^($LONCAPA::match_username)_\d+_($LONCAPA::match_domain)_/) {
1.561     raeburn  4969:                 my ($uname,$udom) = ($1,$2);
1.562     raeburn  4970:                 next unless (-e "$perlvar{'lonDaemons'}/tmp/$uname$dbsuffix");
1.561     raeburn  4971:                 my $mtime = (stat("$perlvar{'lonIDsDir'}/$filename"))[9];
                   4972:                 if ($lastactivity < 0) {
1.563     raeburn  4973:                     next if ($mtime-$now > $lastactivity);
1.561     raeburn  4974:                 } else {
1.563     raeburn  4975:                     next if ($now-$mtime > $lastactivity);
1.561     raeburn  4976:                 }
                   4977:                 $sessions{$uname.':'.$udom} = $mtime;
                   4978:             }
                   4979:         }
                   4980:         closedir(DIR); 
                   4981:     }
                   4982:     foreach my $user (keys(%sessions)) {
                   4983:         $qresult.=&escape($user).'='.$sessions{$user}.'&';
                   4984:     }
                   4985:     if ($qresult) {
                   4986:         chop($qresult);
                   4987:     }
                   4988:     &Reply($client, \$qresult, $userinput);
                   4989:     return 1;
                   4990: }
                   4991: &register_handler("coursesessions",\&course_sessions_handler, 0, 1, 0);
                   4992: 
1.238     foxr     4993: #
1.348     raeburn  4994: # Puts an unencrypted entry in a namespace db file at the domain level 
                   4995: #
                   4996: # Parameters:
                   4997: #    $cmd      - The command that got us here.
                   4998: #    $tail     - Tail of the command (remaining parameters).
                   4999: #    $client   - File descriptor connected to client.
                   5000: # Returns
                   5001: #     0        - Requested to exit, caller should shut down.
                   5002: #     1        - Continue processing.
                   5003: #  Side effects:
                   5004: #     reply is written to $client.
                   5005: #
                   5006: sub put_domain_handler {
                   5007:     my ($cmd,$tail,$client) = @_;
                   5008: 
                   5009:     my $userinput = "$cmd:$tail";
                   5010: 
                   5011:     my ($udom,$namespace,$what) =split(/:/,$tail,3);
                   5012:     chomp($what);
                   5013:     my @pairs=split(/\&/,$what);
                   5014:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_WRCREAT(),
                   5015:                                    "P", $what);
                   5016:     if ($hashref) {
                   5017:         foreach my $pair (@pairs) {
                   5018:             my ($key,$value)=split(/=/,$pair);
                   5019:             $hashref->{$key}=$value;
                   5020:         }
                   5021:         if (&untie_domain_hash($hashref)) {
                   5022:             &Reply($client, "ok\n", $userinput);
                   5023:         } else {
                   5024:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5025:                      "while attempting putdom\n", $userinput);
                   5026:         }
                   5027:     } else {
                   5028:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5029:                   "while attempting putdom\n", $userinput);
                   5030:     }
                   5031: 
                   5032:     return 1;
                   5033: }
                   5034: &register_handler("putdom", \&put_domain_handler, 0, 1, 0);
                   5035: 
1.517     raeburn  5036: # Updates one or more entries in clickers.db file at the domain level
                   5037: #
                   5038: # Parameters:
                   5039: #    $cmd      - The command that got us here.
                   5040: #    $tail     - Tail of the command (remaining parameters).
                   5041: #                In this case a colon separated list containing:
                   5042: #                (a) the domain for which we are updating the entries,
                   5043: #                (b) the action required -- add or del -- and
                   5044: #                (c) a &-separated list of entries to add or delete.
                   5045: #    $client   - File descriptor connected to client.
                   5046: # Returns
                   5047: #     1        - Continue processing.
                   5048: #     0        - Requested to exit, caller should shut down.
                   5049: #  Side effects:
                   5050: #     reply is written to $client.
                   5051: #
                   5052: 
                   5053: 
                   5054: sub update_clickers {
                   5055:     my ($cmd, $tail, $client)  = @_;
                   5056: 
                   5057:     my $userinput = "$cmd:$tail";
                   5058:     my ($udom,$action,$what) =split(/:/,$tail,3);
                   5059:     chomp($what);
                   5060: 
                   5061:     my $hashref = &tie_domain_hash($udom, "clickers", &GDBM_WRCREAT(),
                   5062:                                  "U","$action:$what");
                   5063: 
                   5064:     if (!$hashref) {
                   5065:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5066:                   "while attempting updateclickers\n", $userinput);
                   5067:         return 1;
                   5068:     }
                   5069: 
                   5070:     my @pairs=split(/\&/,$what);
                   5071:     foreach my $pair (@pairs) {
                   5072:         my ($key,$value)=split(/=/,$pair);
                   5073:         if ($action eq 'add') {
                   5074:             if (exists($hashref->{$key})) {
                   5075:                 my @newvals = split(/,/,&unescape($value));
                   5076:                 my @currvals = split(/,/,&unescape($hashref->{$key}));
                   5077:                 my @merged = sort(keys(%{{map { $_ => 1 } (@newvals,@currvals)}}));
                   5078:                 $hashref->{$key}=&escape(join(',',@merged));
                   5079:             } else {
                   5080:                 $hashref->{$key}=$value;
                   5081:             }
                   5082:         } elsif ($action eq 'del') {
                   5083:             if (exists($hashref->{$key})) {
                   5084:                 my %current;
                   5085:                 map { $current{$_} = 1; } split(/,/,&unescape($hashref->{$key}));
                   5086:                 map { delete($current{$_}); } split(/,/,&unescape($value));
                   5087:                 if (keys(%current)) {
                   5088:                     $hashref->{$key}=&escape(join(',',sort(keys(%current))));
                   5089:                 } else {
                   5090:                     delete($hashref->{$key});
                   5091:                 }
                   5092:             }
                   5093:         }
                   5094:     }
                   5095:     if (&untie_user_hash($hashref)) {
                   5096:         &Reply( $client, "ok\n", $userinput);
                   5097:     } else {
                   5098:         &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   5099:                  "while attempting put\n",
                   5100:                  $userinput);
                   5101:     }
                   5102:     return 1;
                   5103: }
                   5104: &register_handler("updateclickers", \&update_clickers, 0, 1, 0);
                   5105: 
                   5106: 
                   5107: # Deletes one or more entries in a namespace db file at the domain level
                   5108: #
                   5109: # Parameters:
                   5110: #    $cmd      - The command that got us here.
                   5111: #    $tail     - Tail of the command (remaining parameters).
                   5112: #                In this case a colon separated list containing:
                   5113: #                (a) the domain for which we are deleting the entries,
                   5114: #                (b) &-separated list of keys to delete.  
                   5115: #    $client   - File descriptor connected to client.
                   5116: # Returns
                   5117: #     1        - Continue processing.
                   5118: #     0        - Requested to exit, caller should shut down.
                   5119: #  Side effects:
                   5120: #     reply is written to $client.
                   5121: #
                   5122: 
                   5123: sub del_domain_handler {
                   5124:     my ($cmd,$tail,$client) = @_;
                   5125: 
                   5126:     my $userinput = "$cmd:$tail";
                   5127: 
                   5128:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   5129:     chomp($what);
                   5130:     my $hashref = &tie_domain_hash($udom,$namespace,&GDBM_WRCREAT(),
                   5131:                                    "D", $what);
                   5132:     if ($hashref) {
                   5133:         my @keys=split(/\&/,$what);
                   5134:         foreach my $key (@keys) {
                   5135:             delete($hashref->{$key});
                   5136:         }
                   5137:         if (&untie_user_hash($hashref)) {
                   5138:             &Reply($client, "ok\n", $userinput);
                   5139:         } else {
                   5140:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5141:                     "while attempting deldom\n", $userinput);
                   5142:         }
                   5143:     } else {
                   5144:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5145:                  "while attempting deldom\n", $userinput);
                   5146:     }
                   5147:     return 1;
                   5148: }
                   5149: &register_handler("deldom", \&del_domain_handler, 0, 1, 0);
                   5150: 
                   5151: 
1.348     raeburn  5152: # Unencrypted get from the namespace database file at the domain level.
                   5153: # This function retrieves a keyed item from a specific named database in the
                   5154: # domain directory.
                   5155: #
                   5156: # Parameters:
1.565     raeburn  5157: #   $cmd             - Command request keyword (getdom).
1.348     raeburn  5158: #   $tail            - Tail of the command.  This is a colon separated list
                   5159: #                      consisting of the domain and the 'namespace' 
                   5160: #                      which selects the gdbm file to do the lookup in,
                   5161: #                      & separated list of keys to lookup.  Note that
                   5162: #                      the values are returned as an & separated list too.
                   5163: #   $client          - File descriptor open on the client.
                   5164: # Returns:
                   5165: #   1       - Continue processing.
                   5166: #   0       - Exit.
                   5167: #  Side effects:
                   5168: #     reply is written to $client.
                   5169: #
                   5170: 
                   5171: sub get_domain_handler {
                   5172:     my ($cmd, $tail, $client) = @_;
                   5173: 
1.536     raeburn  5174:     my $userinput = "$cmd:$tail";
                   5175: 
                   5176:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
1.573     raeburn  5177:     if (($namespace =~ /^enc/) || ($namespace eq 'private')) {
1.536     raeburn  5178:         &Failure( $client, "refused\n", $userinput);
                   5179:     } else {
1.565     raeburn  5180:         my $res = LONCAPA::Lond::get_dom($userinput);
                   5181:         if ($res =~ /^error:/) {
                   5182:             &Failure($client, \$res, $userinput);
1.536     raeburn  5183:         } else {
1.565     raeburn  5184:             &Reply($client, \$res, $userinput);
1.536     raeburn  5185:         }
                   5186:     }
                   5187: 
                   5188:     return 1;
                   5189: }
                   5190: &register_handler("getdom", \&get_domain_handler, 0, 1, 0);
                   5191: 
1.572     raeburn  5192: #
                   5193: # Encrypted get from the namespace database file at the domain level.
                   5194: # This function retrieves a keyed item from a specific named database in the
                   5195: # domain directory.
                   5196: #
                   5197: # Parameters:
                   5198: #   $cmd             - Command request keyword (egetdom).
                   5199: #   $tail            - Tail of the command.  This is a colon separated list
                   5200: #                      consisting of the domain and the 'namespace'
                   5201: #                      which selects the gdbm file to do the lookup in,
                   5202: #                      & separated list of keys to lookup.  Note that
                   5203: #                      the values are returned as an & separated list too.
                   5204: #   $client          - File descriptor open on the client.
                   5205: # Returns:
                   5206: #   1       - Continue processing.
                   5207: #   0       - Exit.
                   5208: #  Side effects:
                   5209: #     reply is encrypted before being written to $client.
                   5210: #
1.536     raeburn  5211: sub encrypted_get_domain_handler {
                   5212:     my ($cmd, $tail, $client) = @_;
                   5213: 
                   5214:     my $userinput = "$cmd:$tail";
1.348     raeburn  5215: 
1.573     raeburn  5216:     my ($udom,$namespace,$what) = split(/:/,$tail,3);
                   5217:     if ($namespace eq 'private') {
                   5218:         &Failure( $client, "refused\n", $userinput);
1.565     raeburn  5219:     } else {
1.573     raeburn  5220:         my $res = LONCAPA::Lond::get_dom($userinput);
                   5221:         if ($res =~ /^error:/) {
                   5222:             &Failure($client, \$res, $userinput);
                   5223:         } else {
                   5224:             if ($cipher) {
                   5225:                 my $cmdlength=length($res);
                   5226:                 $res.="         ";
                   5227:                 my $encres='';
                   5228:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   5229:                     $encres.= unpack("H16",
                   5230:                                      $cipher->encrypt(substr($res,
                   5231:                                                              $encidx,
                   5232:                                                              8)));
                   5233:                 }
                   5234:                 &Reply( $client,"enc:$cmdlength:$encres\n",$userinput);
                   5235:             } else {
                   5236:                 &Failure( $client, "error:no_key\n",$userinput);
1.536     raeburn  5237:             }
1.348     raeburn  5238:         }
                   5239:     }
                   5240:     return 1;
                   5241: }
1.536     raeburn  5242: &register_handler("egetdom", \&encrypted_get_domain_handler, 1, 1, 0);
1.348     raeburn  5243: 
1.420     raeburn  5244: #
1.572     raeburn  5245: # Encrypted get from the namespace database file at the domain level.
                   5246: # This function retrieves a keyed item from a specific named database in the
                   5247: # domain directory.
                   5248: #
                   5249: # Parameters:
                   5250: #   $cmd             - Command request keyword (lti).
                   5251: #   $tail            - Tail of the command.  This is a colon-separated list
                   5252: #                      consisting of the domain, coursenum, if for LTI-
                   5253: #                      enabled deep-linking to course content using
                   5254: #                      link protection configured within a course,
                   5255: #                      context (=deeplink) if for LTI-enabled deep-linking
                   5256: #                      to course content using LTI Provider settings
                   5257: #                      configured within a course's domain, the (escaped)
                   5258: #                      launch URL, the (escaped) method (typically POST),
                   5259: #                      and a frozen hash of the LTI launch parameters
                   5260: #                      from the LTI payload.
                   5261: #   $client          - File descriptor open on the client.
                   5262: # Returns:
                   5263: #   1       - Continue processing.
                   5264: #   0       - Exit.
                   5265: #  Side effects:
                   5266: #     The reply will contain an LTI itemID, if the signed LTI payload
                   5267: #     could be verified using the consumer key and the shared secret 
                   5268: #     available for that key (for the itemID) for either the course or domain, 
                   5269: #     depending on values for cnum and context. The reply is encrypted before 
                   5270: #     being written to $client.
                   5271: #
                   5272: sub lti_handler {
                   5273:     my ($cmd, $tail, $client) = @_;
                   5274: 
                   5275:     my $userinput = "$cmd:$tail";
                   5276: 
                   5277:     my ($cdom,$cnum,$context,$escurl,$escmethod,$items) = split(/:/,$tail);
                   5278:     my $url = &unescape($escurl);
                   5279:     my $method = &unescape($escmethod);
                   5280:     my $params = &Apache::lonnet::thaw_unescape($items);
                   5281:     my $res;
                   5282:     if ($cnum ne '') {
                   5283:         $res = &LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
                   5284:     } else {
                   5285:         $res = &LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
                   5286:     }
                   5287:     if ($res =~ /^error:/) {
                   5288:         &Failure($client, \$res, $userinput);
                   5289:     } else {
                   5290:         if ($cipher) {
                   5291:             my $cmdlength=length($res);
                   5292:             $res.="         ";
                   5293:             my $encres='';
                   5294:             for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   5295:                 $encres.= unpack("H16",
                   5296:                                  $cipher->encrypt(substr($res,
                   5297:                                                          $encidx,
                   5298:                                                          8)));
                   5299:             }
                   5300:             &Reply( $client,"enc:$cmdlength:$encres\n",$userinput);
                   5301:         } else {
                   5302:             &Failure( $client, "error:no_key\n",$userinput);
                   5303:         }
                   5304:     }
                   5305:     return 1;
                   5306: }
                   5307: &register_handler("lti", \&lti_handler, 1, 1, 0);
                   5308: 
                   5309: #
1.238     foxr     5310: #  Puts an id to a domains id database. 
                   5311: #
                   5312: #  Parameters:
                   5313: #   $cmd     - The command that triggered us.
                   5314: #   $tail    - Remainder of the request other than the command. This is a 
                   5315: #              colon separated list containing:
                   5316: #              $domain  - The domain for which we are writing the id.
                   5317: #              $pairs  - The id info to write... this is and & separated list
                   5318: #                        of keyword=value.
                   5319: #   $client  - Socket open on the client.
                   5320: #  Returns:
                   5321: #    1   - Continue processing.
                   5322: #  Side effects:
                   5323: #     reply is written to $client.
                   5324: #
                   5325: sub put_id_handler {
                   5326:     my ($cmd,$tail,$client) = @_;
                   5327: 
                   5328: 
                   5329:     my $userinput = "$cmd:$tail";
                   5330: 
                   5331:     my ($udom,$what)=split(/:/,$tail);
                   5332:     chomp($what);
                   5333:     my @pairs=split(/\&/,$what);
                   5334:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   5335: 				   "P", $what);
                   5336:     if ($hashref) {
                   5337: 	foreach my $pair (@pairs) {
                   5338: 	    my ($key,$value)=split(/=/,$pair);
                   5339: 	    $hashref->{$key}=$value;
                   5340: 	}
1.311     albertel 5341: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     5342: 	    &Reply($client, "ok\n", $userinput);
                   5343: 	} else {
                   5344: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5345: 		     "while attempting idput\n", $userinput);
                   5346: 	}
                   5347:     } else {
                   5348: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5349: 		  "while attempting idput\n", $userinput);
                   5350:     }
                   5351: 
                   5352:     return 1;
                   5353: }
1.263     albertel 5354: &register_handler("idput", \&put_id_handler, 0, 1, 0);
1.238     foxr     5355: 
                   5356: #
                   5357: #  Retrieves a set of id values from the id database.
                   5358: #  Returns an & separated list of results, one for each requested id to the
                   5359: #  client.
                   5360: #
                   5361: # Parameters:
                   5362: #   $cmd       - Command keyword that caused us to be dispatched.
                   5363: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5364: #               domain - the domain whose id table we dump
                   5365: #               ids      Consists of an & separated list of
                   5366: #                        id keywords whose values will be fetched.
                   5367: #                        nonexisting keywords will have an empty value.
                   5368: #   $client    - Socket open on the client.
                   5369: #
                   5370: # Returns:
                   5371: #    1 - indicating processing should continue.
                   5372: # Side effects:
                   5373: #   An & separated list of results is written to $client.
                   5374: #
                   5375: sub get_id_handler {
                   5376:     my ($cmd, $tail, $client) = @_;
                   5377: 
                   5378:     
                   5379:     my $userinput = "$client:$tail";
                   5380:     
                   5381:     my ($udom,$what)=split(/:/,$tail);
                   5382:     chomp($what);
                   5383:     my @queries=split(/\&/,$what);
                   5384:     my $qresult='';
                   5385:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
                   5386:     if ($hashref) {
                   5387: 	for (my $i=0;$i<=$#queries;$i++) {
                   5388: 	    $qresult.="$hashref->{$queries[$i]}&";
                   5389: 	}
1.311     albertel 5390: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     5391: 	    $qresult=~s/\&$//;
1.387     albertel 5392: 	    &Reply($client, \$qresult, $userinput);
1.238     foxr     5393: 	} else {
                   5394: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5395: 		      "while attempting idget\n",$userinput);
                   5396: 	}
                   5397:     } else {
                   5398: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5399: 		 "while attempting idget\n",$userinput);
                   5400:     }
                   5401:     
                   5402:     return 1;
                   5403: }
1.263     albertel 5404: &register_handler("idget", \&get_id_handler, 0, 1, 0);
1.238     foxr     5405: 
1.501     raeburn  5406: #   Deletes one or more ids in a domain's id database.
                   5407: #
                   5408: #   Parameters:
                   5409: #       $cmd                  - Command keyword (iddel).
                   5410: #       $tail                 - Command tail.  In this case a colon
                   5411: #                               separated list containing:
                   5412: #                               The domain for which we are deleting the id(s).
                   5413: #                               &-separated list of id(s) to delete.
                   5414: #       $client               - File open on client socket.
                   5415: # Returns:
                   5416: #     1   - Continue processing
                   5417: #     0   - Exit server.
                   5418: #     
                   5419: #
                   5420: 
                   5421: sub del_id_handler {
                   5422:     my ($cmd,$tail,$client) = @_;
                   5423: 
                   5424:     my $userinput = "$cmd:$tail";
                   5425: 
                   5426:     my ($udom,$what)=split(/:/,$tail);
                   5427:     chomp($what);
                   5428:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   5429:                                    "D", $what);
                   5430:     if ($hashref) {
                   5431:         my @keys=split(/\&/,$what);
                   5432:         foreach my $key (@keys) {
                   5433:             delete($hashref->{$key});
                   5434:         }
                   5435:         if (&untie_user_hash($hashref)) {
                   5436:             &Reply($client, "ok\n", $userinput);
                   5437:         } else {
                   5438:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5439:                     "while attempting iddel\n", $userinput);
                   5440:         }
                   5441:     } else {
                   5442:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5443:                  "while attempting iddel\n", $userinput);
                   5444:     }
                   5445:     return 1;
                   5446: }
                   5447: &register_handler("iddel", \&del_id_handler, 0, 1, 0);
                   5448: 
1.238     foxr     5449: #
1.299     raeburn  5450: # Puts broadcast e-mail sent by Domain Coordinator in nohist_dcmail database 
                   5451: #
                   5452: # Parameters
                   5453: #   $cmd       - Command keyword that caused us to be dispatched.
                   5454: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5455: #               domain - the domain whose dcmail we are recording
                   5456: #               email    Consists of key=value pair 
                   5457: #                        where key is unique msgid
                   5458: #                        and value is message (in XML)
                   5459: #   $client    - Socket open on the client.
                   5460: #
                   5461: # Returns:
                   5462: #    1 - indicating processing should continue.
                   5463: # Side effects
                   5464: #     reply is written to $client.
                   5465: #
                   5466: sub put_dcmail_handler {
                   5467:     my ($cmd,$tail,$client) = @_;
                   5468:     my $userinput = "$cmd:$tail";
1.463     foxr     5469: 
                   5470: 
1.299     raeburn  5471:     my ($udom,$what)=split(/:/,$tail);
                   5472:     chomp($what);
                   5473:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   5474:     if ($hashref) {
                   5475:         my ($key,$value)=split(/=/,$what);
                   5476:         $hashref->{$key}=$value;
                   5477:     }
1.311     albertel 5478:     if (&untie_domain_hash($hashref)) {
1.299     raeburn  5479:         &Reply($client, "ok\n", $userinput);
                   5480:     } else {
                   5481:         &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5482:                  "while attempting dcmailput\n", $userinput);
                   5483:     }
                   5484:     return 1;
                   5485: }
                   5486: &register_handler("dcmailput", \&put_dcmail_handler, 0, 1, 0);
                   5487: 
                   5488: #
                   5489: # Retrieves broadcast e-mail from nohist_dcmail database
                   5490: # Returns to client an & separated list of key=value pairs,
                   5491: # where key is msgid and value is message information.
                   5492: #
                   5493: # Parameters
                   5494: #   $cmd       - Command keyword that caused us to be dispatched.
                   5495: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5496: #               domain - the domain whose dcmail table we dump
                   5497: #               startfilter - beginning of time window 
                   5498: #               endfilter - end of time window
                   5499: #               sendersfilter - & separated list of username:domain 
                   5500: #                 for senders to search for.
                   5501: #   $client    - Socket open on the client.
                   5502: #
                   5503: # Returns:
                   5504: #    1 - indicating processing should continue.
                   5505: # Side effects
                   5506: #     reply (& separated list of msgid=messageinfo pairs) is 
                   5507: #     written to $client.
                   5508: #
                   5509: sub dump_dcmail_handler {
                   5510:     my ($cmd, $tail, $client) = @_;
                   5511:                                                                                 
                   5512:     my $userinput = "$cmd:$tail";
                   5513:     my ($udom,$startfilter,$endfilter,$sendersfilter) = split(/:/,$tail);
                   5514:     chomp($sendersfilter);
                   5515:     my @senders = ();
                   5516:     if (defined($startfilter)) {
                   5517:         $startfilter=&unescape($startfilter);
                   5518:     } else {
                   5519:         $startfilter='.';
                   5520:     }
                   5521:     if (defined($endfilter)) {
                   5522:         $endfilter=&unescape($endfilter);
                   5523:     } else {
                   5524:         $endfilter='.';
                   5525:     }
                   5526:     if (defined($sendersfilter)) {
                   5527:         $sendersfilter=&unescape($sendersfilter);
1.300     albertel 5528: 	@senders = map { &unescape($_) } split(/\&/,$sendersfilter);
1.299     raeburn  5529:     }
                   5530: 
                   5531:     my $qresult='';
                   5532:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   5533:     if ($hashref) {
                   5534:         while (my ($key,$value) = each(%$hashref)) {
                   5535:             my $match = 1;
1.303     albertel 5536:             my ($timestamp,$subj,$uname,$udom) = 
                   5537: 		split(/:/,&unescape(&unescape($key)),5); # yes, twice really
1.299     raeburn  5538:             $subj = &unescape($subj);
                   5539:             unless ($startfilter eq '.' || !defined($startfilter)) {
                   5540:                 if ($timestamp < $startfilter) {
                   5541:                     $match = 0;
                   5542:                 }
                   5543:             }
                   5544:             unless ($endfilter eq '.' || !defined($endfilter)) {
                   5545:                 if ($timestamp > $endfilter) {
                   5546:                     $match = 0;
                   5547:                 }
                   5548:             }
                   5549:             unless (@senders < 1) {
                   5550:                 unless (grep/^$uname:$udom$/,@senders) {
                   5551:                     $match = 0;
                   5552:                 }
                   5553:             }
                   5554:             if ($match == 1) {
                   5555:                 $qresult.=$key.'='.$value.'&';
                   5556:             }
                   5557:         }
1.311     albertel 5558:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5559:             chop($qresult);
1.387     albertel 5560:             &Reply($client, \$qresult, $userinput);
1.299     raeburn  5561:         } else {
                   5562:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5563:                     "while attempting dcmaildump\n", $userinput);
                   5564:         }
                   5565:     } else {
                   5566:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5567:                 "while attempting dcmaildump\n", $userinput);
                   5568:     }
                   5569:     return 1;
                   5570: }
                   5571: 
                   5572: &register_handler("dcmaildump", \&dump_dcmail_handler, 0, 1, 0);
                   5573: 
                   5574: #
                   5575: # Puts domain roles in nohist_domainroles database
                   5576: #
                   5577: # Parameters
                   5578: #   $cmd       - Command keyword that caused us to be dispatched.
                   5579: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5580: #               domain - the domain whose roles we are recording  
                   5581: #               role -   Consists of key=value pair
                   5582: #                        where key is unique role
                   5583: #                        and value is start/end date information
                   5584: #   $client    - Socket open on the client.
                   5585: #
                   5586: # Returns:
                   5587: #    1 - indicating processing should continue.
                   5588: # Side effects
                   5589: #     reply is written to $client.
                   5590: #
                   5591: 
                   5592: sub put_domainroles_handler {
                   5593:     my ($cmd,$tail,$client) = @_;
                   5594: 
                   5595:     my $userinput = "$cmd:$tail";
                   5596:     my ($udom,$what)=split(/:/,$tail);
                   5597:     chomp($what);
                   5598:     my @pairs=split(/\&/,$what);
                   5599:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   5600:     if ($hashref) {
                   5601:         foreach my $pair (@pairs) {
                   5602:             my ($key,$value)=split(/=/,$pair);
                   5603:             $hashref->{$key}=$value;
                   5604:         }
1.311     albertel 5605:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5606:             &Reply($client, "ok\n", $userinput);
                   5607:         } else {
                   5608:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5609:                      "while attempting domroleput\n", $userinput);
                   5610:         }
                   5611:     } else {
                   5612:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5613:                   "while attempting domroleput\n", $userinput);
                   5614:     }
                   5615:                                                                                   
                   5616:     return 1;
                   5617: }
                   5618: 
                   5619: &register_handler("domroleput", \&put_domainroles_handler, 0, 1, 0);
                   5620: 
                   5621: #
                   5622: # Retrieves domain roles from nohist_domainroles database
                   5623: # Returns to client an & separated list of key=value pairs,
                   5624: # where key is role and value is start and end date information.
                   5625: #
                   5626: # Parameters
                   5627: #   $cmd       - Command keyword that caused us to be dispatched.
                   5628: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5629: #               domain - the domain whose domain roles table we dump
                   5630: #   $client    - Socket open on the client.
                   5631: #
                   5632: # Returns:
                   5633: #    1 - indicating processing should continue.
                   5634: # Side effects
                   5635: #     reply (& separated list of role=start/end info pairs) is
                   5636: #     written to $client.
                   5637: #
                   5638: sub dump_domainroles_handler {
                   5639:     my ($cmd, $tail, $client) = @_;
                   5640:                                                                                            
                   5641:     my $userinput = "$cmd:$tail";
                   5642:     my ($udom,$startfilter,$endfilter,$rolesfilter) = split(/:/,$tail);
                   5643:     chomp($rolesfilter);
                   5644:     my @roles = ();
                   5645:     if (defined($startfilter)) {
                   5646:         $startfilter=&unescape($startfilter);
                   5647:     } else {
                   5648:         $startfilter='.';
                   5649:     }
                   5650:     if (defined($endfilter)) {
                   5651:         $endfilter=&unescape($endfilter);
                   5652:     } else {
                   5653:         $endfilter='.';
                   5654:     }
                   5655:     if (defined($rolesfilter)) {
                   5656:         $rolesfilter=&unescape($rolesfilter);
1.300     albertel 5657: 	@roles = split(/\&/,$rolesfilter);
1.299     raeburn  5658:     }
1.421     raeburn  5659: 
1.299     raeburn  5660:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   5661:     if ($hashref) {
                   5662:         my $qresult = '';
                   5663:         while (my ($key,$value) = each(%$hashref)) {
                   5664:             my $match = 1;
1.421     raeburn  5665:             my ($end,$start) = split(/:/,&unescape($value));
1.299     raeburn  5666:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,&unescape($key));
1.421     raeburn  5667:             unless (@roles < 1) {
                   5668:                 unless (grep/^\Q$trole\E$/,@roles) {
                   5669:                     $match = 0;
                   5670:                     next;
                   5671:                 }
                   5672:             }
1.299     raeburn  5673:             unless ($startfilter eq '.' || !defined($startfilter)) {
1.415     raeburn  5674:                 if ((defined($start)) && ($start >= $startfilter)) {
1.299     raeburn  5675:                     $match = 0;
1.421     raeburn  5676:                     next;
1.299     raeburn  5677:                 }
                   5678:             }
                   5679:             unless ($endfilter eq '.' || !defined($endfilter)) {
1.421     raeburn  5680:                 if ((defined($end)) && (($end > 0) && ($end <= $endfilter))) {
1.299     raeburn  5681:                     $match = 0;
1.421     raeburn  5682:                     next;
1.299     raeburn  5683:                 }
                   5684:             }
                   5685:             if ($match == 1) {
                   5686:                 $qresult.=$key.'='.$value.'&';
                   5687:             }
                   5688:         }
1.311     albertel 5689:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5690:             chop($qresult);
1.387     albertel 5691:             &Reply($client, \$qresult, $userinput);
1.299     raeburn  5692:         } else {
                   5693:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5694:                     "while attempting domrolesdump\n", $userinput);
                   5695:         }
                   5696:     } else {
                   5697:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5698:                 "while attempting domrolesdump\n", $userinput);
                   5699:     }
                   5700:     return 1;
                   5701: }
                   5702: 
                   5703: &register_handler("domrolesdump", \&dump_domainroles_handler, 0, 1, 0);
                   5704: 
                   5705: 
1.238     foxr     5706: #  Process the tmpput command I'm not sure what this does.. Seems to
                   5707: #  create a file in the lonDaemons/tmp directory of the form $id.tmp
                   5708: # where Id is the client's ip concatenated with a sequence number.
                   5709: # The file will contain some value that is passed in.  Is this e.g.
                   5710: # a login token?
                   5711: #
                   5712: # Parameters:
                   5713: #    $cmd     - The command that got us dispatched.
                   5714: #    $tail    - The remainder of the request following $cmd:
                   5715: #               In this case this will be the contents of the file.
                   5716: #    $client  - Socket connected to the client.
                   5717: # Returns:
                   5718: #    1 indicating processing can continue.
                   5719: # Side effects:
                   5720: #   A file is created in the local filesystem.
                   5721: #   A reply is sent to the client.
                   5722: sub tmp_put_handler {
                   5723:     my ($cmd, $what, $client) = @_;
                   5724: 
                   5725:     my $userinput = "$cmd:$what";	# Reconstruct for logging.
                   5726: 
1.347     raeburn  5727:     my ($record,$context) = split(/:/,$what);
                   5728:     if ($context ne '') {
                   5729:         chomp($context);
                   5730:         $context = &unescape($context);
                   5731:     }
                   5732:     my ($id,$store);
1.238     foxr     5733:     $tmpsnum++;
1.569     raeburn  5734:     my $numtries = 0;
                   5735:     my $execdir=$perlvar{'lonDaemons'};
                   5736:     if (($context eq 'resetpw') || ($context eq 'createaccount') ||
                   5737:         ($context eq 'sso') || ($context eq 'link') || ($context eq 'retry')) {
                   5738:         $id = &md5_hex(&md5_hex(time.{}.rand().$$.$tmpsnum));
                   5739:         while ((-e "$execdir/tmp/$id.tmp") && ($numtries <10)) {
                   5740:             undef($id);
                   5741:             $id = &md5_hex(&md5_hex(time.{}.rand().$$.$tmpsnum));
                   5742:             $numtries ++;
                   5743:         }
1.347     raeburn  5744:     } else {
                   5745:         $id = $$.'_'.$clientip.'_'.$tmpsnum;
                   5746:     }
1.238     foxr     5747:     $id=~s/\W/\_/g;
1.347     raeburn  5748:     $record=~s/\n//g;
1.569     raeburn  5749:     if (($id ne '') &&
                   5750:         ($store=IO::File->new(">$execdir/tmp/$id.tmp"))) {
1.347     raeburn  5751: 	print $store $record;
1.238     foxr     5752: 	close $store;
1.387     albertel 5753: 	&Reply($client, \$id, $userinput);
1.238     foxr     5754:     } else {
                   5755: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   5756: 		  "while attempting tmpput\n", $userinput);
                   5757:     }
                   5758:     return 1;
                   5759:   
                   5760: }
                   5761: &register_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
1.263     albertel 5762: 
1.238     foxr     5763: #   Processes the tmpget command.  This command returns the contents
                   5764: #  of a temporary resource file(?) created via tmpput.
                   5765: #
                   5766: # Paramters:
                   5767: #    $cmd      - Command that got us dispatched.
                   5768: #    $id       - Tail of the command, contain the id of the resource
                   5769: #                we want to fetch.
                   5770: #    $client   - socket open on the client.
                   5771: # Return:
                   5772: #    1         - Inidcating processing can continue.
                   5773: # Side effects:
                   5774: #   A reply is sent to the client.
                   5775: #
                   5776: sub tmp_get_handler {
                   5777:     my ($cmd, $id, $client) = @_;
                   5778: 
                   5779:     my $userinput = "$cmd:$id"; 
                   5780:     
                   5781: 
                   5782:     $id=~s/\W/\_/g;
                   5783:     my $store;
                   5784:     my $execdir=$perlvar{'lonDaemons'};
                   5785:     if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
                   5786: 	my $reply=<$store>;
1.387     albertel 5787: 	&Reply( $client, \$reply, $userinput);
1.238     foxr     5788: 	close $store;
                   5789:     } else {
                   5790: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   5791: 		  "while attempting tmpget\n", $userinput);
                   5792:     }
                   5793: 
                   5794:     return 1;
                   5795: }
                   5796: &register_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
1.263     albertel 5797: 
1.238     foxr     5798: #
                   5799: #  Process the tmpdel command.  This command deletes a temp resource
                   5800: #  created by the tmpput command.
                   5801: #
                   5802: # Parameters:
                   5803: #   $cmd      - Command that got us here.
                   5804: #   $id       - Id of the temporary resource created.
                   5805: #   $client   - socket open on the client process.
                   5806: #
                   5807: # Returns:
                   5808: #   1     - Indicating processing should continue.
                   5809: # Side Effects:
                   5810: #   A file is deleted
                   5811: #   A reply is sent to the client.
                   5812: sub tmp_del_handler {
                   5813:     my ($cmd, $id, $client) = @_;
                   5814:     
                   5815:     my $userinput= "$cmd:$id";
                   5816:     
                   5817:     chomp($id);
                   5818:     $id=~s/\W/\_/g;
                   5819:     my $execdir=$perlvar{'lonDaemons'};
                   5820:     if (unlink("$execdir/tmp/$id.tmp")) {
                   5821: 	&Reply($client, "ok\n", $userinput);
                   5822:     } else {
                   5823: 	&Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
                   5824: 		  "while attempting tmpdel\n", $userinput);
                   5825:     }
                   5826:     
                   5827:     return 1;
                   5828: 
                   5829: }
                   5830: &register_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
1.263     albertel 5831: 
1.238     foxr     5832: #
1.564     raeburn  5833: #  Process the updatebalcookie command.  This command updates a
                   5834: #  cookie in the lonBalancedir directory on a load balancer node.
                   5835: #
                   5836: # Parameters:
                   5837: #   $cmd      - Command that got us here.
                   5838: #   $tail     - Tail of the request (escaped cookie: escaped current entry)
                   5839: #
                   5840: #   $client   - socket open on the client process.
                   5841: #
                   5842: # Returns:
                   5843: #   1     - Indicating processing should continue.
                   5844: # Side Effects:
                   5845: #   A cookie file is updated from the lonBalancedir directory
                   5846: #   A reply is sent to the client.
                   5847: #
                   5848: sub update_balcookie_handler {
                   5849:     my ($cmd, $tail, $client) = @_;
                   5850: 
                   5851:     my $userinput= "$cmd:$tail";
                   5852:     chomp($tail);
                   5853:     my ($cookie,$lastentry) = map { &unescape($_) } (split(/:/,$tail));
                   5854: 
                   5855:     my $updatedone;
                   5856:     if ($cookie =~ /^$LONCAPA::match_domain\_$LONCAPA::match_username\_[a-f0-9]{32}$/) {
                   5857:         my $execdir=$perlvar{'lonBalanceDir'};
                   5858:         if (-e "$execdir/$cookie.id") {
                   5859:             my $doupdate;
                   5860:             if (open(my $fh,'<',"$execdir/$cookie.id")) {
                   5861:                 while (my $line = <$fh>) {
                   5862:                     chomp($line);
                   5863:                     if ($line eq $lastentry) {
                   5864:                         $doupdate = 1;
                   5865:                         last;
                   5866:                     }
                   5867:                 }
                   5868:                 close($fh);
                   5869:             }
                   5870:             if ($doupdate) {
                   5871:                 if (open(my $fh,'>',"$execdir/$cookie.id")) {
                   5872:                     print $fh $clientname;
                   5873:                     close($fh);
                   5874:                     $updatedone = 1;
                   5875:                 }
                   5876:             }
                   5877:         }
                   5878:     }
                   5879:     if ($updatedone) {
                   5880:         &Reply($client, "ok\n", $userinput);
                   5881:     } else {
                   5882:         &Failure( $client, "error: ".($!+0)."file update failed ".
                   5883:                   "while attempting updatebalcookie\n", $userinput);
                   5884:     }
                   5885:     return 1;
                   5886: }
                   5887: &register_handler("updatebalcookie", \&update_balcookie_handler, 0, 1, 0);
                   5888: 
                   5889: #
1.551     raeburn  5890: #  Process the delbalcookie command. This command deletes a balancer
1.564     raeburn  5891: #  cookie in the lonBalancedir directory on a load balancer node.
1.551     raeburn  5892: #
                   5893: # Parameters:
                   5894: #   $cmd      - Command that got us here.
                   5895: #   $cookie   - Cookie to be deleted.
                   5896: #   $client   - socket open on the client process.
                   5897: #
                   5898: # Returns:
                   5899: #   1     - Indicating processing should continue.
                   5900: # Side Effects:
                   5901: #   A cookie file is deleted from the lonBalancedir directory
                   5902: #   A reply is sent to the client.
                   5903: sub del_balcookie_handler {
                   5904:     my ($cmd, $cookie, $client) = @_;
                   5905: 
                   5906:     my $userinput= "$cmd:$cookie";
                   5907: 
                   5908:     chomp($cookie);
1.564     raeburn  5909:     $cookie = &unescape($cookie);
1.551     raeburn  5910:     my $deleted = '';
                   5911:     if ($cookie =~ /^$LONCAPA::match_domain\_$LONCAPA::match_username\_[a-f0-9]{32}$/) {
                   5912:         my $execdir=$perlvar{'lonBalanceDir'};
                   5913:         if (-e "$execdir/$cookie.id") {
                   5914:             if (open(my $fh,'<',"$execdir/$cookie.id")) {
                   5915:                 my $dodelete;
                   5916:                 while (my $line = <$fh>) {
                   5917:                     chomp($line);
                   5918:                     if ($line eq $clientname) {
                   5919:                         $dodelete = 1;
1.554     raeburn  5920:                         last;
1.551     raeburn  5921:                     }
                   5922:                 }
1.554     raeburn  5923:                 close($fh);
1.551     raeburn  5924:                 if ($dodelete) {
                   5925:                     if (unlink("$execdir/$cookie.id")) {
                   5926:                         $deleted = 1;
                   5927:                     }
                   5928:                 }
                   5929:             }
                   5930:         }
                   5931:     }
                   5932:     if ($deleted) {
                   5933:         &Reply($client, "ok\n", $userinput);
                   5934:     } else {
                   5935:         &Failure( $client, "error: ".($!+0)."Unlinking cookie file Failed ".
                   5936:                   "while attempting delbalcookie\n", $userinput);
                   5937:     }
                   5938:     return 1;
                   5939: }
                   5940: &register_handler("delbalcookie", \&del_balcookie_handler, 0, 1, 0);
                   5941: 
                   5942: #
1.246     foxr     5943: #   Processes the setannounce command.  This command
                   5944: #   creates a file named announce.txt in the top directory of
                   5945: #   the documentn root and sets its contents.  The announce.txt file is
                   5946: #   printed in its entirety at the LonCAPA login page.  Note:
                   5947: #   once the announcement.txt fileis created it cannot be deleted.
                   5948: #   However, setting the contents of the file to empty removes the
                   5949: #   announcement from the login page of loncapa so who cares.
                   5950: #
                   5951: # Parameters:
                   5952: #    $cmd          - The command that got us dispatched.
                   5953: #    $announcement - The text of the announcement.
                   5954: #    $client       - Socket open on the client process.
                   5955: # Retunrns:
                   5956: #   1             - Indicating request processing should continue
                   5957: # Side Effects:
                   5958: #   The file {DocRoot}/announcement.txt is created.
                   5959: #   A reply is sent to $client.
                   5960: #
                   5961: sub set_announce_handler {
                   5962:     my ($cmd, $announcement, $client) = @_;
                   5963:   
                   5964:     my $userinput    = "$cmd:$announcement";
                   5965: 
                   5966:     chomp($announcement);
                   5967:     $announcement=&unescape($announcement);
                   5968:     if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
                   5969: 				'/announcement.txt')) {
                   5970: 	print $store $announcement;
                   5971: 	close $store;
                   5972: 	&Reply($client, "ok\n", $userinput);
                   5973:     } else {
                   5974: 	&Failure($client, "error: ".($!+0)."\n", $userinput);
                   5975:     }
                   5976: 
                   5977:     return 1;
                   5978: }
                   5979: &register_handler("setannounce", \&set_announce_handler, 0, 1, 0);
1.263     albertel 5980: 
1.246     foxr     5981: #
                   5982: #  Return the version of the daemon.  This can be used to determine
                   5983: #  the compatibility of cross version installations or, alternatively to
                   5984: #  simply know who's out of date and who isn't.  Note that the version
                   5985: #  is returned concatenated with the tail.
                   5986: # Parameters:
                   5987: #   $cmd        - the request that dispatched to us.
                   5988: #   $tail       - Tail of the request (client's version?).
                   5989: #   $client     - Socket open on the client.
                   5990: #Returns:
                   5991: #   1 - continue processing requests.
                   5992: # Side Effects:
                   5993: #   Replies with version to $client.
                   5994: sub get_version_handler {
                   5995:     my ($cmd, $tail, $client) = @_;
                   5996: 
                   5997:     my $userinput  = $cmd.$tail;
                   5998:     
                   5999:     &Reply($client, &version($userinput)."\n", $userinput);
                   6000: 
                   6001: 
                   6002:     return 1;
                   6003: }
                   6004: &register_handler("version", \&get_version_handler, 0, 1, 0);
1.263     albertel 6005: 
1.246     foxr     6006: #  Set the current host and domain.  This is used to support
                   6007: #  multihomed systems.  Each IP of the system, or even separate daemons
                   6008: #  on the same IP can be treated as handling a separate lonCAPA virtual
                   6009: #  machine.  This command selects the virtual lonCAPA.  The client always
                   6010: #  knows the right one since it is lonc and it is selecting the domain/system
                   6011: #  from the hosts.tab file.
                   6012: # Parameters:
                   6013: #    $cmd      - Command that dispatched us.
                   6014: #    $tail     - Tail of the command (domain/host requested).
                   6015: #    $socket   - Socket open on the client.
                   6016: #
                   6017: # Returns:
                   6018: #     1   - Indicates the program should continue to process requests.
                   6019: # Side-effects:
                   6020: #     The default domain/system context is modified for this daemon.
                   6021: #     a reply is sent to the client.
                   6022: #
                   6023: sub set_virtual_host_handler {
                   6024:     my ($cmd, $tail, $socket) = @_;
                   6025:   
                   6026:     my $userinput  ="$cmd:$tail";
                   6027: 
                   6028:     &Reply($client, &sethost($userinput)."\n", $userinput);
                   6029: 
                   6030: 
                   6031:     return 1;
                   6032: }
1.247     albertel 6033: &register_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
1.246     foxr     6034: 
                   6035: #  Process a request to exit:
                   6036: #   - "bye" is sent to the client.
                   6037: #   - The client socket is shutdown and closed.
                   6038: #   - We indicate to the caller that we should exit.
                   6039: # Formal Parameters:
                   6040: #   $cmd                - The command that got us here.
                   6041: #   $tail               - Tail of the command (empty).
                   6042: #   $client             - Socket open on the tail.
                   6043: # Returns:
                   6044: #   0      - Indicating the program should exit!!
                   6045: #
                   6046: sub exit_handler {
                   6047:     my ($cmd, $tail, $client) = @_;
                   6048: 
                   6049:     my $userinput = "$cmd:$tail";
                   6050: 
                   6051:     &logthis("Client $clientip ($clientname) hanging up: $userinput");
                   6052:     &Reply($client, "bye\n", $userinput);
                   6053:     $client->shutdown(2);        # shutdown the socket forcibly.
                   6054:     $client->close();
                   6055: 
                   6056:     return 0;
                   6057: }
1.248     foxr     6058: &register_handler("exit", \&exit_handler, 0,1,1);
                   6059: &register_handler("init", \&exit_handler, 0,1,1);
                   6060: &register_handler("quit", \&exit_handler, 0,1,1);
                   6061: 
                   6062: #  Determine if auto-enrollment is enabled.
                   6063: #  Note that the original had what I believe to be a defect.
                   6064: #  The original returned 0 if the requestor was not a registerd client.
                   6065: #  It should return "refused".
                   6066: # Formal Parameters:
                   6067: #   $cmd       - The command that invoked us.
                   6068: #   $tail      - The tail of the command (Extra command parameters.
                   6069: #   $client    - The socket open on the client that issued the request.
                   6070: # Returns:
                   6071: #    1         - Indicating processing should continue.
                   6072: #
                   6073: sub enrollment_enabled_handler {
                   6074:     my ($cmd, $tail, $client) = @_;
                   6075:     my $userinput = $cmd.":".$tail; # For logging purposes.
                   6076: 
                   6077:     
1.337     albertel 6078:     my ($cdom) = split(/:/, $tail, 2);   # Domain we're asking about.
                   6079: 
1.248     foxr     6080:     my $outcome  = &localenroll::run($cdom);
1.387     albertel 6081:     &Reply($client, \$outcome, $userinput);
1.248     foxr     6082: 
                   6083:     return 1;
                   6084: }
                   6085: &register_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
                   6086: 
1.417     raeburn  6087: #
1.423     raeburn  6088: #   Validate an institutional code used for a LON-CAPA course.          
1.417     raeburn  6089: #
                   6090: # Formal Parameters:
                   6091: #   $cmd          - The command request that got us dispatched.
                   6092: #   $tail         - The tail of the command.  In this case,
                   6093: #                   this is a colon separated set of words that will be split
                   6094: #                   into:
1.424     raeburn  6095: #                        $dom      - The domain for which the check of 
                   6096: #                                    institutional course code will occur.
                   6097: #
                   6098: #                        $instcode - The institutional code for the course
                   6099: #                                    being requested, or validated for rights
                   6100: #                                    to request.
                   6101: #
                   6102: #                        $owner    - The course requestor (who will be the
                   6103: #                                    course owner, in the form username:domain
                   6104: #
1.417     raeburn  6105: #   $client       - Socket open on the client.
                   6106: # Returns:
                   6107: #    1           - Indicating processing should continue.
                   6108: #
                   6109: sub validate_instcode_handler {
                   6110:     my ($cmd, $tail, $client) = @_;
                   6111:     my $userinput = "$cmd:$tail";
1.423     raeburn  6112:     my ($dom,$instcode,$owner) = split(/:/, $tail);
1.422     raeburn  6113:     $instcode = &unescape($instcode);
                   6114:     $owner = &unescape($owner);
1.498     raeburn  6115:     my ($outcome,$description,$credits) = 
1.426     raeburn  6116:         &localenroll::validate_instcode($dom,$instcode,$owner);
1.498     raeburn  6117:     my $result = &escape($outcome).'&'.&escape($description).'&'.
                   6118:                  &escape($credits);
1.426     raeburn  6119:     &Reply($client, \$result, $userinput);
1.417     raeburn  6120: 
                   6121:     return 1;
                   6122: }
                   6123: &register_handler("autovalidateinstcode", \&validate_instcode_handler, 0, 1, 0);
                   6124: 
1.566     raeburn  6125: #
                   6126: #  Validate co-owner for cross-listed institutional code and
                   6127: #  institutional course code itself used for a LON-CAPA course.
                   6128: #
                   6129: # Formal Parameters:
                   6130: #   $cmd          - The command request that got us dispatched.
                   6131: #   $tail         - The tail of the command.  In this case,
                   6132: #                   this is a colon separated string containing:
                   6133: #      $dom            - Course's LON-CAPA domain
                   6134: #      $instcode       - Institutional course code for the course
                   6135: #      $inst_xlist     - Institutional course Id for the crosslisting
                   6136: #      $coowner        - Username of co-owner
                   6137: #      (values for all but $dom have been escaped). 
                   6138: #
                   6139: #   $client       - Socket open on the client.
                   6140: # Returns:
                   6141: #    1           - Indicating processing should continue.
                   6142: #
                   6143: sub validate_instcrosslist_handler  {
                   6144:     my ($cmd, $tail, $client) = @_;
                   6145:     my $userinput = "$cmd:$tail";
                   6146:     my ($dom,$instcode,$inst_xlist,$coowner) = split(/:/,$tail);
                   6147:     $instcode = &unescape($instcode);
                   6148:     $inst_xlist = &unescape($inst_xlist);
                   6149:     $coowner = &unescape($coowner);
                   6150:     my $outcome = &localenroll::validate_crosslist_access($dom,$instcode,
                   6151:                                                           $inst_xlist,$coowner);
                   6152:     &Reply($client, \$outcome, $userinput);
                   6153: 
                   6154:     return 1;
                   6155: }
                   6156: &register_handler("autovalidateinstcrosslist", \&validate_instcrosslist_handler, 0, 1, 0);
                   6157: 
1.248     foxr     6158: #   Get the official sections for which auto-enrollment is possible.
                   6159: #   Since the admin people won't know about 'unofficial sections' 
                   6160: #   we cannot auto-enroll on them.
                   6161: # Formal Parameters:
                   6162: #    $cmd     - The command request that got us dispatched here.
                   6163: #    $tail    - The remainder of the request.  In our case this
                   6164: #               will be split into:
                   6165: #               $coursecode   - The course name from the admin point of view.
                   6166: #               $cdom         - The course's domain(?).
                   6167: #    $client  - Socket open on the client.
                   6168: # Returns:
                   6169: #    1    - Indiciting processing should continue.
                   6170: #
                   6171: sub get_sections_handler {
                   6172:     my ($cmd, $tail, $client) = @_;
                   6173:     my $userinput = "$cmd:$tail";
                   6174: 
                   6175:     my ($coursecode, $cdom) = split(/:/, $tail);
                   6176:     my @secs = &localenroll::get_sections($coursecode,$cdom);
                   6177:     my $seclist = &escape(join(':',@secs));
                   6178: 
1.387     albertel 6179:     &Reply($client, \$seclist, $userinput);
1.248     foxr     6180:     
                   6181: 
                   6182:     return 1;
                   6183: }
                   6184: &register_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
                   6185: 
                   6186: #   Validate the owner of a new course section.  
                   6187: #
                   6188: # Formal Parameters:
                   6189: #   $cmd      - Command that got us dispatched.
                   6190: #   $tail     - the remainder of the command.  For us this consists of a
                   6191: #               colon separated string containing:
                   6192: #                  $inst    - Course Id from the institutions point of view.
                   6193: #                  $owner   - Proposed owner of the course.
                   6194: #                  $cdom    - Domain of the course (from the institutions
                   6195: #                             point of view?)..
                   6196: #   $client   - Socket open on the client.
                   6197: #
                   6198: # Returns:
                   6199: #   1        - Processing should continue.
                   6200: #
                   6201: sub validate_course_owner_handler {
                   6202:     my ($cmd, $tail, $client)  = @_;
                   6203:     my $userinput = "$cmd:$tail";
1.470     raeburn  6204:     my ($inst_course_id, $owner, $cdom, $coowners) = split(/:/, $tail);
                   6205:     
1.336     raeburn  6206:     $owner = &unescape($owner);
1.470     raeburn  6207:     $coowners = &unescape($coowners);
                   6208:     my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom,$coowners);
1.387     albertel 6209:     &Reply($client, \$outcome, $userinput);
1.248     foxr     6210: 
                   6211: 
                   6212: 
                   6213:     return 1;
                   6214: }
                   6215: &register_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
1.263     albertel 6216: 
1.248     foxr     6217: #
                   6218: #   Validate a course section in the official schedule of classes
                   6219: #   from the institutions point of view (part of autoenrollment).
                   6220: #
                   6221: # Formal Parameters:
                   6222: #   $cmd          - The command request that got us dispatched.
                   6223: #   $tail         - The tail of the command.  In this case,
                   6224: #                   this is a colon separated set of words that will be split
                   6225: #                   into:
                   6226: #                        $inst_course_id - The course/section id from the
                   6227: #                                          institutions point of view.
                   6228: #                        $cdom           - The domain from the institutions
                   6229: #                                          point of view.
                   6230: #   $client       - Socket open on the client.
                   6231: # Returns:
                   6232: #    1           - Indicating processing should continue.
                   6233: #
                   6234: sub validate_course_section_handler {
                   6235:     my ($cmd, $tail, $client) = @_;
                   6236:     my $userinput = "$cmd:$tail";
                   6237:     my ($inst_course_id, $cdom) = split(/:/, $tail);
                   6238: 
                   6239:     my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
1.387     albertel 6240:     &Reply($client, \$outcome, $userinput);
1.248     foxr     6241: 
                   6242: 
                   6243:     return 1;
                   6244: }
                   6245: &register_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
                   6246: 
                   6247: #
1.340     raeburn  6248: #   Validate course owner's access to enrollment data for specific class section. 
                   6249: #   
                   6250: #
                   6251: # Formal Parameters:
                   6252: #    $cmd     - The command request that got us dispatched.
                   6253: #    $tail    - The tail of the command.   In this case this is a colon separated
1.542     raeburn  6254: #               set of values that will be split into:
1.340     raeburn  6255: #               $inst_class  - Institutional code for the specific class section   
1.542     raeburn  6256: #               $ownerlist   - An escaped comma-separated list of username:domain 
                   6257: #                              of the course owner, and co-owner(s).
1.340     raeburn  6258: #               $cdom        - The domain of the course from the institution's
                   6259: #                              point of view.
                   6260: #    $client  - The socket open on the client.
                   6261: # Returns:
                   6262: #    1 - continue processing.
                   6263: #
                   6264: 
                   6265: sub validate_class_access_handler {
                   6266:     my ($cmd, $tail, $client) = @_;
                   6267:     my $userinput = "$cmd:$tail";
1.383     raeburn  6268:     my ($inst_class,$ownerlist,$cdom) = split(/:/, $tail);
1.392     raeburn  6269:     my $owners = &unescape($ownerlist);
1.341     albertel 6270:     my $outcome;
                   6271:     eval {
                   6272: 	local($SIG{__DIE__})='DEFAULT';
1.392     raeburn  6273: 	$outcome=&localenroll::check_section($inst_class,$owners,$cdom);
1.341     albertel 6274:     };
1.387     albertel 6275:     &Reply($client,\$outcome, $userinput);
1.340     raeburn  6276: 
                   6277:     return 1;
                   6278: }
                   6279: &register_handler("autovalidateclass_sec", \&validate_class_access_handler, 0, 1, 0);
                   6280: 
                   6281: #
1.567     raeburn  6282: #    Modify institutional sections (using customized &instsec_reformat()
                   6283: #    routine in localenroll.pm), to either clutter or declutter, for  
                   6284: #    purposes of ensuring an institutional course section (string) can
                   6285: #    be unambiguously separated into institutional course and section.
                   6286: #
                   6287: # Formal Parameters:
                   6288: #    $cmd     - The command request that got us dispatched.
                   6289: #    $tail    - The tail of the command.   In this case this is a colon separated
                   6290: #               set of values that will be split into:
                   6291: #               $cdom        - The LON-CAPA domain of the course.
                   6292: #               $action      - Either: clutter or declutter
                   6293: #                              clutter adds character(s) to eliminate ambiguity
                   6294: #                              declutter removes the added characters (e.g., for
                   6295: #                              display of the institutional course section string.
                   6296: #               $info        - A frozen hash in which keys are: 
                   6297: #                              LON-CAPA course number:Institutional course code
                   6298: #                              and values are a reference to an array of the
                   6299: #                              items to modify -- either institutional sections,
                   6300: #                              or institutional course sections (for crosslistings). 
                   6301: #    $client  - The socket open on the client.
                   6302: # Returns:
                   6303: #    1 - continue processing.
                   6304: #   
                   6305: 
                   6306: sub instsec_reformat_handler {
                   6307:     my ($cmd, $tail, $client) = @_;
                   6308:     my $userinput = "$cmd:$tail";
                   6309:     my ($cdom,$action,$info) = split(/:/,$tail);
                   6310:     my $instsecref = &Apache::lonnet::thaw_unescape($info);
                   6311:     my ($outcome,$result);
                   6312:     eval {
                   6313:         local($SIG{__DIE__})='DEFAULT';
                   6314:         $outcome=&localenroll::instsec_reformat($cdom,$action,$instsecref);
                   6315:         if ($outcome eq 'ok') {
                   6316:             if (ref($instsecref) eq 'HASH') {
                   6317:                 foreach my $key (keys(%{$instsecref})) {
                   6318:                     $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($instsecref->{$key}).'&';
                   6319:                 }
                   6320:                 $result =~ s/\&$//;
                   6321:             }
                   6322:         }
                   6323:     };
                   6324:     if (!$@) {
                   6325:         if ($outcome eq 'ok') {
                   6326:             &Reply( $client, \$result, $userinput);
                   6327:         } else {
                   6328:             &Reply($client,\$outcome, $userinput);
                   6329:         }
                   6330:     } else {
                   6331:         &Failure($client,"unknown_cmd\n",$userinput);
                   6332:     }
                   6333:     return 1;
                   6334: }
                   6335: &register_handler("autoinstsecreformat",\&instsec_reformat_handler, 0, 1, 0);
                   6336: 
                   6337: #
1.542     raeburn  6338: #   Validate course owner or co-owners(s) access to enrollment data for all sections
                   6339: #   and crosslistings for a particular course.
                   6340: #
                   6341: #
                   6342: # Formal Parameters:
                   6343: #    $cmd     - The command request that got us dispatched.
                   6344: #    $tail    - The tail of the command.   In this case this is a colon separated
                   6345: #               set of values that will be split into:
                   6346: #               $ownerlist   - An escaped comma-separated list of username:domain
                   6347: #                              of the course owner, and co-owner(s).
                   6348: #               $cdom        - The domain of the course from the institution's
                   6349: #                              point of view.
                   6350: #               $classes     - Frozen hash of institutional course sections and
                   6351: #                              crosslistings.
                   6352: #    $client  - The socket open on the client.
                   6353: # Returns:
                   6354: #    1 - continue processing.
                   6355: #
                   6356: 
                   6357: sub validate_classes_handler {
                   6358:     my ($cmd, $tail, $client) = @_;
                   6359:     my $userinput = "$cmd:$tail";
                   6360:     my ($ownerlist,$cdom,$classes) = split(/:/, $tail);
                   6361:     my $classesref = &Apache::lonnet::thaw_unescape($classes);
                   6362:     my $owners = &unescape($ownerlist);
                   6363:     my $result;
                   6364:     eval {
                   6365:         local($SIG{__DIE__})='DEFAULT';
                   6366:         my %validations;
                   6367:         my $response = &localenroll::check_instclasses($owners,$cdom,$classesref,
                   6368:                                                        \%validations);
                   6369:         if ($response eq 'ok') {
                   6370:             foreach my $key (keys(%validations)) {
                   6371:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
                   6372:             }
                   6373:             $result =~ s/\&$//;
                   6374:         } else {
                   6375:             $result = 'error';
                   6376:         }
                   6377:     };
                   6378:     if (!$@) {
                   6379:         &Reply($client, \$result, $userinput);
                   6380:     } else {
                   6381:         &Failure($client,"unknown_cmd\n",$userinput);
                   6382:     }
                   6383:     return 1;
                   6384: }
                   6385: &register_handler("autovalidateinstclasses", \&validate_classes_handler, 0, 1, 0);
                   6386: 
                   6387: #
1.340     raeburn  6388: #   Create a password for a new LON-CAPA user added by auto-enrollment.
                   6389: #   Only used for case where authentication method for new user is localauth
1.248     foxr     6390: #
                   6391: # Formal Parameters:
                   6392: #    $cmd     - The command request that got us dispatched.
                   6393: #    $tail    - The tail of the command.   In this case this is a colon separated
                   6394: #               set of words that will be split into:
1.340     raeburn  6395: #               $authparam - An authentication parameter (localauth parameter).
1.248     foxr     6396: #               $cdom      - The domain of the course from the institution's
                   6397: #                            point of view.
                   6398: #    $client  - The socket open on the client.
                   6399: # Returns:
                   6400: #    1 - continue processing.
                   6401: #
                   6402: sub create_auto_enroll_password_handler {
                   6403:     my ($cmd, $tail, $client) = @_;
                   6404:     my $userinput = "$cmd:$tail";
                   6405: 
                   6406:     my ($authparam, $cdom) = split(/:/, $userinput);
                   6407: 
                   6408:     my ($create_passwd,$authchk);
                   6409:     ($authparam,
                   6410:      $create_passwd,
                   6411:      $authchk) = &localenroll::create_password($authparam,$cdom);
                   6412: 
                   6413:     &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
                   6414: 	   $userinput);
                   6415: 
                   6416: 
                   6417:     return 1;
                   6418: }
                   6419: &register_handler("autocreatepassword", \&create_auto_enroll_password_handler, 
                   6420: 		  0, 1, 0);
                   6421: 
1.522     raeburn  6422: sub auto_export_grades_handler {
                   6423:     my ($cmd, $tail, $client) = @_;
                   6424:     my $userinput = "$cmd:$tail";
                   6425:     my ($cdom,$cnum,$info,$data) = split(/:/,$tail);
                   6426:     my $inforef = &Apache::lonnet::thaw_unescape($info);
                   6427:     my $dataref = &Apache::lonnet::thaw_unescape($data);
                   6428:     my ($outcome,$result);;
                   6429:     eval {
                   6430:         local($SIG{__DIE__})='DEFAULT';
                   6431:         my %rtnhash;
                   6432:         $outcome=&localenroll::export_grades($cdom,$cnum,$inforef,$dataref,\%rtnhash);
                   6433:         if ($outcome eq 'ok') {
                   6434:             foreach my $key (keys(%rtnhash)) {
                   6435:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
                   6436:             }
                   6437:             $result =~ s/\&$//;
                   6438:         }
                   6439:     };
                   6440:     if (!$@) {
                   6441:         if ($outcome eq 'ok') {
                   6442:             if ($cipher) {
                   6443:                 my $cmdlength=length($result);
                   6444:                 $result.="         ";
                   6445:                 my $encresult='';
                   6446:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   6447:                     $encresult.= unpack("H16",
                   6448:                                         $cipher->encrypt(substr($result,
                   6449:                                                                 $encidx,
                   6450:                                                                 8)));
                   6451:                 }
                   6452:                 &Reply( $client, "enc:$cmdlength:$encresult\n", $userinput);
                   6453:             } else {
                   6454:                 &Failure( $client, "error:no_key\n", $userinput);
                   6455:             }
                   6456:         } else {
                   6457:             &Reply($client, "$outcome\n", $userinput);
                   6458:         }
                   6459:     } else {
                   6460:         &Failure($client,"export_error\n",$userinput);
                   6461:     }
                   6462:     return 1;
                   6463: }
                   6464: &register_handler("autoexportgrades", \&auto_export_grades_handler,
1.536     raeburn  6465:                   1, 1, 0);
1.522     raeburn  6466: 
1.248     foxr     6467: #   Retrieve and remove temporary files created by/during autoenrollment.
                   6468: #
                   6469: # Formal Parameters:
                   6470: #    $cmd      - The command that got us dispatched.
                   6471: #    $tail     - The tail of the command.  In our case this is a colon 
                   6472: #                separated list that will be split into:
1.526     raeburn  6473: #                $filename - The name of the file to retrieve.
1.248     foxr     6474: #                            The filename is given as a path relative to
                   6475: #                            the LonCAPA temp file directory.
                   6476: #    $client   - Socket open on the client.
                   6477: #
                   6478: # Returns:
                   6479: #   1     - Continue processing.
                   6480: sub retrieve_auto_file_handler {
                   6481:     my ($cmd, $tail, $client)    = @_;
                   6482:     my $userinput                = "cmd:$tail";
                   6483: 
                   6484:     my ($filename)   = split(/:/, $tail);
                   6485: 
                   6486:     my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
1.521     raeburn  6487: 
                   6488:     if ($filename =~m{/\.\./}) {
                   6489:         &Failure($client, "refused\n", $userinput);
1.526     raeburn  6490:     } elsif ($filename !~ /^$LONCAPA::match_domain\_$LONCAPA::match_courseid\_.+_classlist\.xml$/) {
                   6491:         &Failure($client, "refused\n", $userinput);
1.521     raeburn  6492:     } elsif ( (-e $source) && ($filename ne '') ) {
1.248     foxr     6493: 	my $reply = '';
                   6494: 	if (open(my $fh,$source)) {
                   6495: 	    while (<$fh>) {
                   6496: 		chomp($_);
                   6497: 		$_ =~ s/^\s+//g;
                   6498: 		$_ =~ s/\s+$//g;
                   6499: 		$reply .= $_;
                   6500: 	    }
                   6501: 	    close($fh);
                   6502: 	    &Reply($client, &escape($reply)."\n", $userinput);
                   6503: 
                   6504: #   Does this have to be uncommented??!?  (RF).
                   6505: #
                   6506: #                                unlink($source);
                   6507: 	} else {
                   6508: 	    &Failure($client, "error\n", $userinput);
                   6509: 	}
                   6510:     } else {
                   6511: 	&Failure($client, "error\n", $userinput);
                   6512:     }
                   6513:     
                   6514: 
                   6515:     return 1;
                   6516: }
                   6517: &register_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
                   6518: 
1.423     raeburn  6519: sub crsreq_checks_handler {
                   6520:     my ($cmd, $tail, $client) = @_;
                   6521:     my $userinput = "$cmd:$tail";
                   6522:     my $dom = $tail;
                   6523:     my $result;
1.519     raeburn  6524:     my @reqtypes = ('official','unofficial','community','textbook','placement');
1.423     raeburn  6525:     eval {
                   6526:         local($SIG{__DIE__})='DEFAULT';
                   6527:         my %validations;
1.424     raeburn  6528:         my $response = &localenroll::crsreq_checks($dom,\@reqtypes,
                   6529:                                                    \%validations);
1.423     raeburn  6530:         if ($response eq 'ok') { 
                   6531:             foreach my $key (keys(%validations)) {
                   6532:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
                   6533:             }
                   6534:             $result =~ s/\&$//;
                   6535:         } else {
                   6536:             $result = 'error';
                   6537:         }
                   6538:     };
                   6539:     if (!$@) {
                   6540:         &Reply($client, \$result, $userinput);
                   6541:     } else {
                   6542:         &Failure($client,"unknown_cmd\n",$userinput);
                   6543:     }
                   6544:     return 1;
                   6545: }
                   6546: &register_handler("autocrsreqchecks", \&crsreq_checks_handler, 0, 1, 0);
                   6547: 
                   6548: sub validate_crsreq_handler {
                   6549:     my ($cmd, $tail, $client) = @_;
                   6550:     my $userinput = "$cmd:$tail";
1.508     raeburn  6551:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$customdata) = split(/:/, $tail);
1.423     raeburn  6552:     $instcode = &unescape($instcode);
                   6553:     $owner = &unescape($owner);
                   6554:     $crstype = &unescape($crstype);
                   6555:     $inststatuslist = &unescape($inststatuslist);
                   6556:     $instcode = &unescape($instcode);
                   6557:     $instseclist = &unescape($instseclist);
1.508     raeburn  6558:     my $custominfo = &Apache::lonnet::thaw_unescape($customdata);
1.423     raeburn  6559:     my $outcome;
                   6560:     eval {
                   6561:         local($SIG{__DIE__})='DEFAULT';
                   6562:         $outcome = &localenroll::validate_crsreq($dom,$owner,$crstype,
                   6563:                                                  $inststatuslist,$instcode,
1.508     raeburn  6564:                                                  $instseclist,$custominfo);
1.423     raeburn  6565:     };
                   6566:     if (!$@) {
                   6567:         &Reply($client, \$outcome, $userinput);
                   6568:     } else {
                   6569:         &Failure($client,"unknown_cmd\n",$userinput);
                   6570:     }
                   6571:     return 1;
                   6572: }
                   6573: &register_handler("autocrsreqvalidation", \&validate_crsreq_handler, 0, 1, 0);
                   6574: 
1.506     raeburn  6575: sub crsreq_update_handler {
                   6576:     my ($cmd, $tail, $client) = @_;
                   6577:     my $userinput = "$cmd:$tail";
1.509     raeburn  6578:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,$code,
                   6579:         $accessstart,$accessend,$infohashref) =
1.506     raeburn  6580:         split(/:/, $tail);
                   6581:     $crstype = &unescape($crstype);
                   6582:     $action = &unescape($action);
                   6583:     $ownername = &unescape($ownername);
                   6584:     $ownerdomain = &unescape($ownerdomain);
                   6585:     $fullname = &unescape($fullname);
                   6586:     $title = &unescape($title);
                   6587:     $code = &unescape($code);
1.509     raeburn  6588:     $accessstart = &unescape($accessstart);
                   6589:     $accessend = &unescape($accessend);
1.506     raeburn  6590:     my $incoming = &Apache::lonnet::thaw_unescape($infohashref);
                   6591:     my ($result,$outcome);
                   6592:     eval {
                   6593:         local($SIG{__DIE__})='DEFAULT';
                   6594:         my %rtnhash;
                   6595:         $outcome = &localenroll::crsreq_updates($cdom,$cnum,$crstype,$action,
                   6596:                                                 $ownername,$ownerdomain,$fullname,
1.509     raeburn  6597:                                                 $title,$code,$accessstart,$accessend,
                   6598:                                                 $incoming,\%rtnhash);
1.506     raeburn  6599:         if ($outcome eq 'ok') {
1.515     raeburn  6600:             my @posskeys = qw(createdweb createdmsg createdcustomized createdactions queuedweb queuedmsg formitems reviewweb validationjs onload javascript);
1.506     raeburn  6601:             foreach my $key (keys(%rtnhash)) {
                   6602:                 if (grep(/^\Q$key\E/,@posskeys)) {
                   6603:                     $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
                   6604:                 }
                   6605:             }
                   6606:             $result =~ s/\&$//;
                   6607:         }
                   6608:     };
                   6609:     if (!$@) {
                   6610:         if ($outcome eq 'ok') {
                   6611:             &Reply($client, \$result, $userinput);
                   6612:         } else {
                   6613:             &Reply($client, "format_error\n", $userinput);
                   6614:         }
                   6615:     } else {
                   6616:         &Failure($client,"unknown_cmd\n",$userinput);
                   6617:     }
                   6618:     return 1;
                   6619: }
                   6620: &register_handler("autocrsrequpdate", \&crsreq_update_handler, 0, 1, 0);
                   6621: 
1.248     foxr     6622: #
                   6623: #   Read and retrieve institutional code format (for support form).
                   6624: # Formal Parameters:
                   6625: #    $cmd        - Command that dispatched us.
                   6626: #    $tail       - Tail of the command.  In this case it conatins 
                   6627: #                  the course domain and the coursename.
                   6628: #    $client     - Socket open on the client.
                   6629: # Returns:
                   6630: #    1     - Continue processing.
                   6631: #
                   6632: sub get_institutional_code_format_handler {
                   6633:     my ($cmd, $tail, $client)   = @_;
                   6634:     my $userinput               = "$cmd:$tail";
                   6635: 
                   6636:     my $reply;
                   6637:     my($cdom,$course) = split(/:/,$tail);
                   6638:     my @pairs = split/\&/,$course;
                   6639:     my %instcodes = ();
                   6640:     my %codes = ();
                   6641:     my @codetitles = ();
                   6642:     my %cat_titles = ();
                   6643:     my %cat_order = ();
                   6644:     foreach (@pairs) {
                   6645: 	my ($key,$value) = split/=/,$_;
                   6646: 	$instcodes{&unescape($key)} = &unescape($value);
                   6647:     }
                   6648:     my $formatreply = &localenroll::instcode_format($cdom,
                   6649: 						    \%instcodes,
                   6650: 						    \%codes,
                   6651: 						    \@codetitles,
                   6652: 						    \%cat_titles,
                   6653: 						    \%cat_order);
                   6654:     if ($formatreply eq 'ok') {
1.365     albertel 6655: 	my $codes_str = &Apache::lonnet::hash2str(%codes);
                   6656: 	my $codetitles_str = &Apache::lonnet::array2str(@codetitles);
                   6657: 	my $cat_titles_str = &Apache::lonnet::hash2str(%cat_titles);
                   6658: 	my $cat_order_str = &Apache::lonnet::hash2str(%cat_order);
1.248     foxr     6659: 	&Reply($client,
                   6660: 	       $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
                   6661: 	       .$cat_order_str."\n",
                   6662: 	       $userinput);
                   6663:     } else {
                   6664: 	# this else branch added by RF since if not ok, lonc will
                   6665: 	# hang waiting on reply until timeout.
                   6666: 	#
                   6667: 	&Reply($client, "format_error\n", $userinput);
                   6668:     }
                   6669:     
                   6670:     return 1;
                   6671: }
1.265     albertel 6672: &register_handler("autoinstcodeformat",
                   6673: 		  \&get_institutional_code_format_handler,0,1,0);
1.246     foxr     6674: 
1.345     raeburn  6675: sub get_institutional_defaults_handler {
                   6676:     my ($cmd, $tail, $client)   = @_;
                   6677:     my $userinput               = "$cmd:$tail";
                   6678: 
                   6679:     my $dom = $tail;
                   6680:     my %defaults_hash;
                   6681:     my @code_order;
                   6682:     my $outcome;
                   6683:     eval {
                   6684:         local($SIG{__DIE__})='DEFAULT';
                   6685:         $outcome = &localenroll::instcode_defaults($dom,\%defaults_hash,
                   6686:                                                    \@code_order);
                   6687:     };
                   6688:     if (!$@) {
                   6689:         if ($outcome eq 'ok') {
                   6690:             my $result='';
                   6691:             while (my ($key,$value) = each(%defaults_hash)) {
                   6692:                 $result.=&escape($key).'='.&escape($value).'&';
                   6693:             }
                   6694:             $result .= 'code_order='.&escape(join('&',@code_order));
1.387     albertel 6695:             &Reply($client,\$result,$userinput);
1.345     raeburn  6696:         } else {
                   6697:             &Reply($client,"error\n", $userinput);
                   6698:         }
                   6699:     } else {
                   6700:         &Failure($client,"unknown_cmd\n",$userinput);
                   6701:     }
                   6702: }
                   6703: &register_handler("autoinstcodedefaults",
                   6704:                   \&get_institutional_defaults_handler,0,1,0);
                   6705: 
1.416     raeburn  6706: sub get_possible_instcodes_handler {
                   6707:     my ($cmd, $tail, $client)   = @_;
                   6708:     my $userinput               = "$cmd:$tail";
                   6709: 
                   6710:     my $reply;
                   6711:     my $cdom = $tail;
1.417     raeburn  6712:     my (@codetitles,%cat_titles,%cat_order,@code_order);
1.416     raeburn  6713:     my $formatreply = &localenroll::possible_instcodes($cdom,
                   6714:                                                        \@codetitles,
                   6715:                                                        \%cat_titles,
1.417     raeburn  6716:                                                        \%cat_order,
                   6717:                                                        \@code_order);
1.416     raeburn  6718:     if ($formatreply eq 'ok') {
                   6719:         my $result = join('&',map {&escape($_);} (@codetitles)).':';
1.417     raeburn  6720:         $result .= join('&',map {&escape($_);} (@code_order)).':';
1.416     raeburn  6721:         foreach my $key (keys(%cat_titles)) {
                   6722:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_titles{$key}).'&';
                   6723:         }
                   6724:         $result =~ s/\&$//;
                   6725:         $result .= ':';
                   6726:         foreach my $key (keys(%cat_order)) {
                   6727:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_order{$key}).'&';
                   6728:         }
                   6729:         $result =~ s/\&$//;
                   6730:         &Reply($client,\$result,$userinput);
                   6731:     } else {
                   6732:         &Reply($client, "format_error\n", $userinput);
                   6733:     }
                   6734:     return 1;
                   6735: }
                   6736: &register_handler("autopossibleinstcodes",
                   6737:                   \&get_possible_instcodes_handler,0,1,0);
                   6738: 
1.381     raeburn  6739: sub get_institutional_user_rules {
                   6740:     my ($cmd, $tail, $client)   = @_;
                   6741:     my $userinput               = "$cmd:$tail";
                   6742:     my $dom = &unescape($tail);
                   6743:     my (%rules_hash,@rules_order);
                   6744:     my $outcome;
                   6745:     eval {
                   6746:         local($SIG{__DIE__})='DEFAULT';
                   6747:         $outcome = &localenroll::username_rules($dom,\%rules_hash,\@rules_order);
                   6748:     };
                   6749:     if (!$@) {
                   6750:         if ($outcome eq 'ok') {
                   6751:             my $result;
                   6752:             foreach my $key (keys(%rules_hash)) {
                   6753:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6754:             }
                   6755:             $result =~ s/\&$//;
                   6756:             $result .= ':';
                   6757:             if (@rules_order > 0) {
                   6758:                 foreach my $item (@rules_order) {
                   6759:                     $result .= &escape($item).'&';
                   6760:                 }
                   6761:             }
                   6762:             $result =~ s/\&$//;
1.387     albertel 6763:             &Reply($client,\$result,$userinput);
1.381     raeburn  6764:         } else {
                   6765:             &Reply($client,"error\n", $userinput);
                   6766:         }
                   6767:     } else {
                   6768:         &Failure($client,"unknown_cmd\n",$userinput);
                   6769:     }
                   6770: }
                   6771: &register_handler("instuserrules",\&get_institutional_user_rules,0,1,0);
                   6772: 
1.389     raeburn  6773: sub get_institutional_id_rules {
                   6774:     my ($cmd, $tail, $client)   = @_;
                   6775:     my $userinput               = "$cmd:$tail";
                   6776:     my $dom = &unescape($tail);
                   6777:     my (%rules_hash,@rules_order);
                   6778:     my $outcome;
                   6779:     eval {
                   6780:         local($SIG{__DIE__})='DEFAULT';
                   6781:         $outcome = &localenroll::id_rules($dom,\%rules_hash,\@rules_order);
                   6782:     };
                   6783:     if (!$@) {
                   6784:         if ($outcome eq 'ok') {
                   6785:             my $result;
                   6786:             foreach my $key (keys(%rules_hash)) {
                   6787:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6788:             }
                   6789:             $result =~ s/\&$//;
                   6790:             $result .= ':';
                   6791:             if (@rules_order > 0) {
                   6792:                 foreach my $item (@rules_order) {
                   6793:                     $result .= &escape($item).'&';
                   6794:                 }
                   6795:             }
                   6796:             $result =~ s/\&$//;
                   6797:             &Reply($client,\$result,$userinput);
                   6798:         } else {
                   6799:             &Reply($client,"error\n", $userinput);
                   6800:         }
                   6801:     } else {
                   6802:         &Failure($client,"unknown_cmd\n",$userinput);
                   6803:     }
                   6804: }
                   6805: &register_handler("instidrules",\&get_institutional_id_rules,0,1,0);
                   6806: 
1.397     raeburn  6807: sub get_institutional_selfcreate_rules {
1.396     raeburn  6808:     my ($cmd, $tail, $client)   = @_;
                   6809:     my $userinput               = "$cmd:$tail";
                   6810:     my $dom = &unescape($tail);
                   6811:     my (%rules_hash,@rules_order);
                   6812:     my $outcome;
                   6813:     eval {
                   6814:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  6815:         $outcome = &localenroll::selfcreate_rules($dom,\%rules_hash,\@rules_order);
1.396     raeburn  6816:     };
                   6817:     if (!$@) {
                   6818:         if ($outcome eq 'ok') {
                   6819:             my $result;
                   6820:             foreach my $key (keys(%rules_hash)) {
                   6821:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6822:             }
                   6823:             $result =~ s/\&$//;
                   6824:             $result .= ':';
                   6825:             if (@rules_order > 0) {
                   6826:                 foreach my $item (@rules_order) {
                   6827:                     $result .= &escape($item).'&';
                   6828:                 }
                   6829:             }
                   6830:             $result =~ s/\&$//;
                   6831:             &Reply($client,\$result,$userinput);
                   6832:         } else {
                   6833:             &Reply($client,"error\n", $userinput);
                   6834:         }
                   6835:     } else {
                   6836:         &Failure($client,"unknown_cmd\n",$userinput);
                   6837:     }
                   6838: }
1.397     raeburn  6839: &register_handler("instemailrules",\&get_institutional_selfcreate_rules,0,1,0);
1.396     raeburn  6840: 
1.575   ! raeburn  6841: sub get_unamemap_rules {
        !          6842:     my ($cmd, $tail, $client)   = @_;
        !          6843:     my $userinput               = "$cmd:$tail";
        !          6844:     my $dom = &unescape($tail);
        !          6845:     my (%rules_hash,@rules_order);
        !          6846:     my $outcome;
        !          6847:     eval {
        !          6848:         local($SIG{__DIE__})='DEFAULT';
        !          6849:         $outcome = &localenroll::unamemap_rules($dom,\%rules_hash,\@rules_order);
        !          6850:     };
        !          6851:     if (!$@) {
        !          6852:         if ($outcome eq 'ok') {
        !          6853:             my $result;
        !          6854:             foreach my $key (keys(%rules_hash)) {
        !          6855:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
        !          6856:             }
        !          6857:             $result =~ s/\&$//;
        !          6858:             $result .= ':';
        !          6859:             if (@rules_order > 0) {
        !          6860:                 foreach my $item (@rules_order) {
        !          6861:                     $result .= &escape($item).'&';
        !          6862:                 }
        !          6863:             }
        !          6864:             $result =~ s/\&$//;
        !          6865:             &Reply($client,\$result,$userinput);
        !          6866:         } else {
        !          6867:             &Reply($client,"error\n", $userinput);
        !          6868:         }
        !          6869:     } else {
        !          6870:         &Failure($client,"unknown_cmd\n",$userinput);
        !          6871:     }
        !          6872: }
        !          6873: &register_handler("unamemaprules",\&get_unamemap_rules,0,1,0);
1.381     raeburn  6874: 
                   6875: sub institutional_username_check {
                   6876:     my ($cmd, $tail, $client)   = @_;
                   6877:     my $userinput               = "$cmd:$tail";
                   6878:     my %rulecheck;
                   6879:     my $outcome;
                   6880:     my ($udom,$uname,@rules) = split(/:/,$tail);
                   6881:     $udom = &unescape($udom);
                   6882:     $uname = &unescape($uname);
                   6883:     @rules = map {&unescape($_);} (@rules);
                   6884:     eval {
                   6885:         local($SIG{__DIE__})='DEFAULT';
                   6886:         $outcome = &localenroll::username_check($udom,$uname,\@rules,\%rulecheck);
                   6887:     };
                   6888:     if (!$@) {
                   6889:         if ($outcome eq 'ok') {
                   6890:             my $result='';
                   6891:             foreach my $key (keys(%rulecheck)) {
                   6892:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6893:             }
1.387     albertel 6894:             &Reply($client,\$result,$userinput);
1.381     raeburn  6895:         } else {
                   6896:             &Reply($client,"error\n", $userinput);
                   6897:         }
                   6898:     } else {
                   6899:         &Failure($client,"unknown_cmd\n",$userinput);
                   6900:     }
                   6901: }
                   6902: &register_handler("instrulecheck",\&institutional_username_check,0,1,0);
                   6903: 
1.389     raeburn  6904: sub institutional_id_check {
                   6905:     my ($cmd, $tail, $client)   = @_;
                   6906:     my $userinput               = "$cmd:$tail";
                   6907:     my %rulecheck;
                   6908:     my $outcome;
                   6909:     my ($udom,$id,@rules) = split(/:/,$tail);
                   6910:     $udom = &unescape($udom);
                   6911:     $id = &unescape($id);
                   6912:     @rules = map {&unescape($_);} (@rules);
                   6913:     eval {
                   6914:         local($SIG{__DIE__})='DEFAULT';
                   6915:         $outcome = &localenroll::id_check($udom,$id,\@rules,\%rulecheck);
                   6916:     };
                   6917:     if (!$@) {
                   6918:         if ($outcome eq 'ok') {
                   6919:             my $result='';
                   6920:             foreach my $key (keys(%rulecheck)) {
                   6921:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6922:             }
                   6923:             &Reply($client,\$result,$userinput);
                   6924:         } else {
                   6925:             &Reply($client,"error\n", $userinput);
                   6926:         }
                   6927:     } else {
                   6928:         &Failure($client,"unknown_cmd\n",$userinput);
                   6929:     }
                   6930: }
                   6931: &register_handler("instidrulecheck",\&institutional_id_check,0,1,0);
1.345     raeburn  6932: 
1.397     raeburn  6933: sub institutional_selfcreate_check {
1.396     raeburn  6934:     my ($cmd, $tail, $client)   = @_;
                   6935:     my $userinput               = "$cmd:$tail";
                   6936:     my %rulecheck;
                   6937:     my $outcome;
                   6938:     my ($udom,$email,@rules) = split(/:/,$tail);
                   6939:     $udom = &unescape($udom);
                   6940:     $email = &unescape($email);
                   6941:     @rules = map {&unescape($_);} (@rules);
                   6942:     eval {
                   6943:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  6944:         $outcome = &localenroll::selfcreate_check($udom,$email,\@rules,\%rulecheck);
1.396     raeburn  6945:     };
                   6946:     if (!$@) {
                   6947:         if ($outcome eq 'ok') {
                   6948:             my $result='';
                   6949:             foreach my $key (keys(%rulecheck)) {
                   6950:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6951:             }
                   6952:             &Reply($client,\$result,$userinput);
                   6953:         } else {
                   6954:             &Reply($client,"error\n", $userinput);
                   6955:         }
                   6956:     } else {
                   6957:         &Failure($client,"unknown_cmd\n",$userinput);
                   6958:     }
                   6959: }
1.397     raeburn  6960: &register_handler("instselfcreatecheck",\&institutional_selfcreate_check,0,1,0);
1.396     raeburn  6961: 
1.317     raeburn  6962: # Get domain specific conditions for import of student photographs to a course
                   6963: #
                   6964: # Retrieves information from photo_permission subroutine in localenroll.
                   6965: # Returns outcome (ok) if no processing errors, and whether course owner is 
                   6966: # required to accept conditions of use (yes/no).
                   6967: #
                   6968: #    
                   6969: sub photo_permission_handler {
                   6970:     my ($cmd, $tail, $client)   = @_;
                   6971:     my $userinput               = "$cmd:$tail";
                   6972:     my $cdom = $tail;
                   6973:     my ($perm_reqd,$conditions);
1.320     albertel 6974:     my $outcome;
                   6975:     eval {
                   6976: 	local($SIG{__DIE__})='DEFAULT';
                   6977: 	$outcome = &localenroll::photo_permission($cdom,\$perm_reqd,
                   6978: 						  \$conditions);
                   6979:     };
                   6980:     if (!$@) {
                   6981: 	&Reply($client, &escape($outcome.':'.$perm_reqd.':'. $conditions)."\n",
                   6982: 	       $userinput);
                   6983:     } else {
                   6984: 	&Failure($client,"unknown_cmd\n",$userinput);
                   6985:     }
                   6986:     return 1;
1.317     raeburn  6987: }
                   6988: &register_handler("autophotopermission",\&photo_permission_handler,0,1,0);
                   6989: 
                   6990: #
                   6991: # Checks if student photo is available for a user in the domain, in the user's
                   6992: # directory (in /userfiles/internal/studentphoto.jpg).
                   6993: # Uses localstudentphoto:fetch() to ensure there is an up to date copy of
                   6994: # the student's photo.   
                   6995: 
                   6996: sub photo_check_handler {
                   6997:     my ($cmd, $tail, $client)   = @_;
                   6998:     my $userinput               = "$cmd:$tail";
                   6999:     my ($udom,$uname,$pid) = split(/:/,$tail);
                   7000:     $udom = &unescape($udom);
                   7001:     $uname = &unescape($uname);
                   7002:     $pid = &unescape($pid);
                   7003:     my $path=&propath($udom,$uname).'/userfiles/internal/';
                   7004:     if (!-e $path) {
                   7005:         &mkpath($path);
                   7006:     }
                   7007:     my $response;
                   7008:     my $result = &localstudentphoto::fetch($udom,$uname,$pid,\$response);
                   7009:     $result .= ':'.$response;
                   7010:     &Reply($client, &escape($result)."\n",$userinput);
1.320     albertel 7011:     return 1;
1.317     raeburn  7012: }
                   7013: &register_handler("autophotocheck",\&photo_check_handler,0,1,0);
                   7014: 
                   7015: #
                   7016: # Retrieve information from localenroll about whether to provide a button     
                   7017: # for users who have enbled import of student photos to initiate an 
                   7018: # update of photo files for registered students. Also include 
                   7019: # comment to display alongside button.  
                   7020: 
                   7021: sub photo_choice_handler {
                   7022:     my ($cmd, $tail, $client) = @_;
                   7023:     my $userinput             = "$cmd:$tail";
                   7024:     my $cdom                  = &unescape($tail);
1.320     albertel 7025:     my ($update,$comment);
                   7026:     eval {
                   7027: 	local($SIG{__DIE__})='DEFAULT';
                   7028: 	($update,$comment)    = &localenroll::manager_photo_update($cdom);
                   7029:     };
                   7030:     if (!$@) {
                   7031: 	&Reply($client,&escape($update).':'.&escape($comment)."\n",$userinput);
                   7032:     } else {
                   7033: 	&Failure($client,"unknown_cmd\n",$userinput);
                   7034:     }
                   7035:     return 1;
1.317     raeburn  7036: }
                   7037: &register_handler("autophotochoice",\&photo_choice_handler,0,1,0);
                   7038: 
1.265     albertel 7039: #
                   7040: # Gets a student's photo to exist (in the correct image type) in the user's 
                   7041: # directory.
                   7042: # Formal Parameters:
                   7043: #    $cmd     - The command request that got us dispatched.
                   7044: #    $tail    - A colon separated set of words that will be split into:
                   7045: #               $domain - student's domain
                   7046: #               $uname  - student username
                   7047: #               $type   - image type desired
                   7048: #    $client  - The socket open on the client.
                   7049: # Returns:
                   7050: #    1 - continue processing.
1.317     raeburn  7051: 
1.265     albertel 7052: sub student_photo_handler {
                   7053:     my ($cmd, $tail, $client) = @_;
1.317     raeburn  7054:     my ($domain,$uname,$ext,$type) = split(/:/, $tail);
1.265     albertel 7055: 
1.317     raeburn  7056:     my $path=&propath($domain,$uname). '/userfiles/internal/';
                   7057:     my $filename = 'studentphoto.'.$ext;
                   7058:     if ($type eq 'thumbnail') {
                   7059:         $filename = 'studentphoto_tn.'.$ext;
                   7060:     }
                   7061:     if (-e $path.$filename) {
1.265     albertel 7062: 	&Reply($client,"ok\n","$cmd:$tail");
                   7063: 	return 1;
                   7064:     }
                   7065:     &mkpath($path);
1.317     raeburn  7066:     my $file;
                   7067:     if ($type eq 'thumbnail') {
1.320     albertel 7068: 	eval {
                   7069: 	    local($SIG{__DIE__})='DEFAULT';
                   7070: 	    $file=&localstudentphoto::fetch_thumbnail($domain,$uname);
                   7071: 	};
1.317     raeburn  7072:     } else {
                   7073:         $file=&localstudentphoto::fetch($domain,$uname);
                   7074:     }
1.265     albertel 7075:     if (!$file) {
                   7076: 	&Failure($client,"unavailable\n","$cmd:$tail");
                   7077: 	return 1;
                   7078:     }
1.317     raeburn  7079:     if (!-e $path.$filename) { &convert_photo($file,$path.$filename); }
                   7080:     if (-e $path.$filename) {
1.265     albertel 7081: 	&Reply($client,"ok\n","$cmd:$tail");
                   7082: 	return 1;
                   7083:     }
                   7084:     &Failure($client,"unable_to_convert\n","$cmd:$tail");
                   7085:     return 1;
                   7086: }
                   7087: &register_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
1.246     foxr     7088: 
1.361     raeburn  7089: sub inst_usertypes_handler {
                   7090:     my ($cmd, $domain, $client) = @_;
                   7091:     my $res;
                   7092:     my $userinput = $cmd.":".$domain; # For logging purposes.
1.370     albertel 7093:     my (%typeshash,@order,$result);
                   7094:     eval {
                   7095: 	local($SIG{__DIE__})='DEFAULT';
                   7096: 	$result=&localenroll::inst_usertypes($domain,\%typeshash,\@order);
                   7097:     };
                   7098:     if ($result eq 'ok') {
1.361     raeburn  7099:         if (keys(%typeshash) > 0) {
                   7100:             foreach my $key (keys(%typeshash)) {
                   7101:                 $res.=&escape($key).'='.&escape($typeshash{$key}).'&';
                   7102:             }
                   7103:         }
                   7104:         $res=~s/\&$//;
                   7105:         $res .= ':';
                   7106:         if (@order > 0) {
                   7107:             foreach my $item (@order) {
                   7108:                 $res .= &escape($item).'&';
                   7109:             }
                   7110:         }
                   7111:         $res=~s/\&$//;
                   7112:     }
1.387     albertel 7113:     &Reply($client, \$res, $userinput);
1.361     raeburn  7114:     return 1;
                   7115: }
                   7116: &register_handler("inst_usertypes", \&inst_usertypes_handler, 0, 1, 0);
                   7117: 
1.264     albertel 7118: # mkpath makes all directories for a file, expects an absolute path with a
                   7119: # file or a trailing / if just a dir is passed
                   7120: # returns 1 on success 0 on failure
                   7121: sub mkpath {
                   7122:     my ($file)=@_;
                   7123:     my @parts=split(/\//,$file,-1);
                   7124:     my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
                   7125:     for (my $i=3;$i<= ($#parts-1);$i++) {
1.265     albertel 7126: 	$now.='/'.$parts[$i]; 
1.264     albertel 7127: 	if (!-e $now) {
                   7128: 	    if  (!mkdir($now,0770)) { return 0; }
                   7129: 	}
                   7130:     }
                   7131:     return 1;
                   7132: }
                   7133: 
1.207     foxr     7134: #---------------------------------------------------------------
                   7135: #
                   7136: #   Getting, decoding and dispatching requests:
                   7137: #
                   7138: #
                   7139: #   Get a Request:
                   7140: #   Gets a Request message from the client.  The transaction
                   7141: #   is defined as a 'line' of text.  We remove the new line
                   7142: #   from the text line.  
1.226     foxr     7143: #
1.211     albertel 7144: sub get_request {
1.207     foxr     7145:     my $input = <$client>;
                   7146:     chomp($input);
1.226     foxr     7147: 
1.234     foxr     7148:     &Debug("get_request: Request = $input\n");
1.207     foxr     7149: 
                   7150:     &status('Processing '.$clientname.':'.$input);
                   7151: 
                   7152:     return $input;
                   7153: }
1.212     foxr     7154: #---------------------------------------------------------------
                   7155: #
                   7156: #  Process a request.  This sub should shrink as each action
                   7157: #  gets farmed out into a separat sub that is registered 
                   7158: #  with the dispatch hash.  
                   7159: #
                   7160: # Parameters:
                   7161: #    user_input   - The request received from the client (lonc).
1.525     raeburn  7162: #
1.212     foxr     7163: # Returns:
                   7164: #    true to keep processing, false if caller should exit.
                   7165: #
                   7166: sub process_request {
1.525     raeburn  7167:     my ($userinput) = @_; # Easier for now to break style than to
                   7168:                           # fix all the userinput -> user_input.
1.212     foxr     7169:     my $wasenc    = 0;		# True if request was encrypted.
                   7170: # ------------------------------------------------------------ See if encrypted
1.322     albertel 7171:     # for command
                   7172:     # sethost:<server>
                   7173:     # <command>:<args>
                   7174:     #   we just send it to the processor
                   7175:     # for
                   7176:     # sethost:<server>:<command>:<args>
                   7177:     #  we do the implict set host and then do the command
                   7178:     if ($userinput =~ /^sethost:/) {
                   7179: 	(my $cmd,my $newid,$userinput) = split(':',$userinput,3);
                   7180: 	if (defined($userinput)) {
                   7181: 	    &sethost("$cmd:$newid");
                   7182: 	} else {
                   7183: 	    $userinput = "$cmd:$newid";
                   7184: 	}
                   7185:     }
                   7186: 
1.212     foxr     7187:     if ($userinput =~ /^enc/) {
                   7188: 	$userinput = decipher($userinput);
                   7189: 	$wasenc=1;
                   7190: 	if(!$userinput) {	# Cipher not defined.
1.251     foxr     7191: 	    &Failure($client, "error: Encrypted data without negotated key\n");
1.212     foxr     7192: 	    return 0;
                   7193: 	}
                   7194:     }
                   7195:     Debug("process_request: $userinput\n");
                   7196:     
1.213     foxr     7197:     #  
                   7198:     #   The 'correct way' to add a command to lond is now to
                   7199:     #   write a sub to execute it and Add it to the command dispatch
                   7200:     #   hash via a call to register_handler..  The comments to that
                   7201:     #   sub should give you enough to go on to show how to do this
                   7202:     #   along with the examples that are building up as this code
                   7203:     #   is getting refactored.   Until all branches of the
                   7204:     #   if/elseif monster below have been factored out into
                   7205:     #   separate procesor subs, if the dispatch hash is missing
                   7206:     #   the command keyword, we will fall through to the remainder
                   7207:     #   of the if/else chain below in order to keep this thing in 
                   7208:     #   working order throughout the transmogrification.
                   7209: 
                   7210:     my ($command, $tail) = split(/:/, $userinput, 2);
                   7211:     chomp($command);
                   7212:     chomp($tail);
                   7213:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
1.214     foxr     7214:     $command =~ s/(\r)//;	# And this too for parameterless commands.
                   7215:     if(!$tail) {
                   7216: 	$tail ="";		# defined but blank.
                   7217:     }
1.213     foxr     7218: 
                   7219:     &Debug("Command received: $command, encoded = $wasenc");
                   7220: 
                   7221:     if(defined $Dispatcher{$command}) {
                   7222: 
                   7223: 	my $dispatch_info = $Dispatcher{$command};
                   7224: 	my $handler       = $$dispatch_info[0];
                   7225: 	my $need_encode   = $$dispatch_info[1];
                   7226: 	my $client_types  = $$dispatch_info[2];
                   7227: 	Debug("Matched dispatch hash: mustencode: $need_encode "
                   7228: 	      ."ClientType $client_types");
                   7229:       
                   7230: 	#  Validate the request:
                   7231:       
                   7232: 	my $ok = 1;
                   7233: 	my $requesterprivs = 0;
                   7234: 	if(&isClient()) {
                   7235: 	    $requesterprivs |= $CLIENT_OK;
                   7236: 	}
                   7237: 	if(&isManager()) {
                   7238: 	    $requesterprivs |= $MANAGER_OK;
                   7239: 	}
                   7240: 	if($need_encode && (!$wasenc)) {
                   7241: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
                   7242: 	    $ok = 0;
                   7243: 	}
                   7244: 	if(($client_types & $requesterprivs) == 0) {
                   7245: 	    Debug("Client not privileged to do this operation");
                   7246: 	    $ok = 0;
                   7247: 	}
1.525     raeburn  7248:         if ($ok) {
1.535     raeburn  7249:             my $realcommand = $command;
                   7250:             if ($command eq 'querysend') {
                   7251:                 my ($query,$rest)=split(/\:/,$tail,2);
                   7252:                 $query=~s/\n*$//g;
                   7253:                 my @possqueries = 
                   7254:                     qw(userlog courselog fetchenrollment institutionalphotos usersearch instdirsearch getinstuser getmultinstusers);
                   7255:                 if (grep(/^\Q$query\E$/,@possqueries)) {
                   7256:                     $command .= '_'.$query;
                   7257:                 } elsif ($query eq 'prepare activity log') {
                   7258:                     $command .= '_activitylog';
                   7259:                 }
                   7260:             }
1.525     raeburn  7261:             if (ref($trust{$command}) eq 'HASH') {
                   7262:                 my $donechecks;
                   7263:                 if ($trust{$command}{'anywhere'}) {
                   7264:                    $donechecks = 1;
                   7265:                 } elsif ($trust{$command}{'manageronly'}) {
                   7266:                     unless (&isManager()) {
                   7267:                         $ok = 0;
                   7268:                     }
                   7269:                     $donechecks = 1;
                   7270:                 } elsif ($trust{$command}{'institutiononly'}) {
                   7271:                     unless ($clientsameinst) {
                   7272:                         $ok = 0;
                   7273:                     }
                   7274:                     $donechecks = 1;
                   7275:                 } elsif ($clientsameinst) {
                   7276:                     $donechecks = 1;
                   7277:                 }
                   7278:                 unless ($donechecks) {
                   7279:                     foreach my $rule (keys(%{$trust{$command}})) {
                   7280:                         next if ($rule eq 'remote');
                   7281:                         if ($trust{$command}{$rule}) {
                   7282:                             if ($clientprohibited{$rule}) {
                   7283:                                 $ok = 0;
                   7284:                             } else {
                   7285:                                 $ok = 1;
                   7286:                                 $donechecks = 1;
                   7287:                                 last;
                   7288:                             }
                   7289:                         }
                   7290:                     }
                   7291:                 }
                   7292:                 unless ($donechecks) {
                   7293:                     if ($trust{$command}{'remote'}) {
                   7294:                         if ($clientremoteok) {
                   7295:                             $ok = 1;
                   7296:                         } else {
                   7297:                             $ok = 0;
                   7298:                         } 
                   7299:                     }
                   7300:                 }
                   7301:             }
1.535     raeburn  7302:             $command = $realcommand;
1.525     raeburn  7303:         }
1.213     foxr     7304: 
                   7305: 	if($ok) {
                   7306: 	    Debug("Dispatching to handler $command $tail");
                   7307: 	    my $keep_going = &$handler($command, $tail, $client);
                   7308: 	    return $keep_going;
                   7309: 	} else {
                   7310: 	    Debug("Refusing to dispatch because client did not match requirements");
                   7311: 	    Failure($client, "refused\n", $userinput);
                   7312: 	    return 1;
                   7313: 	}
1.525     raeburn  7314:     }
1.213     foxr     7315: 
1.262     foxr     7316:     print $client "unknown_cmd\n";
1.212     foxr     7317: # -------------------------------------------------------------------- complete
                   7318:     Debug("process_request - returning 1");
                   7319:     return 1;
                   7320: }
1.207     foxr     7321: #
                   7322: #   Decipher encoded traffic
                   7323: #  Parameters:
                   7324: #     input      - Encoded data.
                   7325: #  Returns:
                   7326: #     Decoded data or undef if encryption key was not yet negotiated.
                   7327: #  Implicit input:
                   7328: #     cipher  - This global holds the negotiated encryption key.
                   7329: #
1.211     albertel 7330: sub decipher {
1.207     foxr     7331:     my ($input)  = @_;
                   7332:     my $output = '';
1.212     foxr     7333:     
                   7334:     
1.207     foxr     7335:     if($cipher) {
                   7336: 	my($enc, $enclength, $encinput) = split(/:/, $input);
                   7337: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
                   7338: 	    $output .= 
                   7339: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
                   7340: 	}
                   7341: 	return substr($output, 0, $enclength);
                   7342:     } else {
                   7343: 	return undef;
                   7344:     }
                   7345: }
                   7346: 
                   7347: #
                   7348: #   Register a command processor.  This function is invoked to register a sub
                   7349: #   to process a request.  Once registered, the ProcessRequest sub can automatically
                   7350: #   dispatch requests to an appropriate sub, and do the top level validity checking
                   7351: #   as well:
                   7352: #    - Is the keyword recognized.
                   7353: #    - Is the proper client type attempting the request.
                   7354: #    - Is the request encrypted if it has to be.
                   7355: #   Parameters:
                   7356: #    $request_name         - Name of the request being registered.
                   7357: #                           This is the command request that will match
                   7358: #                           against the hash keywords to lookup the information
                   7359: #                           associated with the dispatch information.
                   7360: #    $procedure           - Reference to a sub to call to process the request.
                   7361: #                           All subs get called as follows:
                   7362: #                             Procedure($cmd, $tail, $replyfd, $key)
                   7363: #                             $cmd    - the actual keyword that invoked us.
                   7364: #                             $tail   - the tail of the request that invoked us.
                   7365: #                             $replyfd- File descriptor connected to the client
                   7366: #    $must_encode          - True if the request must be encoded to be good.
                   7367: #    $client_ok            - True if it's ok for a client to request this.
                   7368: #    $manager_ok           - True if it's ok for a manager to request this.
                   7369: # Side effects:
                   7370: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
                   7371: #      - On failure, the program will die as it's a bad internal bug to try to 
                   7372: #        register a duplicate command handler.
                   7373: #
1.211     albertel 7374: sub register_handler {
1.212     foxr     7375:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
1.207     foxr     7376: 
                   7377:     #  Don't allow duplication#
                   7378:    
                   7379:     if (defined $Dispatcher{$request_name}) {
                   7380: 	die "Attempting to define a duplicate request handler for $request_name\n";
                   7381:     }
                   7382:     #   Build the client type mask:
                   7383:     
                   7384:     my $client_type_mask = 0;
                   7385:     if($client_ok) {
                   7386: 	$client_type_mask  |= $CLIENT_OK;
                   7387:     }
                   7388:     if($manager_ok) {
                   7389: 	$client_type_mask  |= $MANAGER_OK;
                   7390:     }
                   7391:    
                   7392:     #  Enter the hash:
                   7393:       
                   7394:     my @entry = ($procedure, $must_encode, $client_type_mask);
                   7395:    
                   7396:     $Dispatcher{$request_name} = \@entry;
                   7397:    
                   7398: }
                   7399: 
                   7400: 
                   7401: #------------------------------------------------------------------
                   7402: 
                   7403: 
                   7404: 
                   7405: 
1.141     foxr     7406: #
1.96      foxr     7407: #  Convert an error return code from lcpasswd to a string value.
                   7408: #
                   7409: sub lcpasswdstrerror {
                   7410:     my $ErrorCode = shift;
1.97      foxr     7411:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96      foxr     7412: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
                   7413:     } else {
1.98      foxr     7414: 	return $passwderrors[$ErrorCode];
1.96      foxr     7415:     }
                   7416: }
                   7417: 
1.23      harris41 7418: # grabs exception and records it to log before exiting
                   7419: sub catchexception {
1.27      albertel 7420:     my ($error)=@_;
1.25      www      7421:     $SIG{'QUIT'}='DEFAULT';
                   7422:     $SIG{__DIE__}='DEFAULT';
1.165     albertel 7423:     &status("Catching exception");
1.190     albertel 7424:     &logthis("<font color='red'>CRITICAL: "
1.373     albertel 7425:      ."ABNORMAL EXIT. Child $$ for server ".$perlvar{'lonHostID'}." died through "
1.27      albertel 7426:      ."a crash with this error msg->[$error]</font>");
1.57      www      7427:     &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27      albertel 7428:     if ($client) { print $client "error: $error\n"; }
1.59      www      7429:     $server->close();
1.27      albertel 7430:     die($error);
1.23      harris41 7431: }
1.63      www      7432: sub timeout {
1.165     albertel 7433:     &status("Handling Timeout");
1.190     albertel 7434:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
1.63      www      7435:     &catchexception('Timeout');
                   7436: }
1.22      harris41 7437: # -------------------------------- Set signal handlers to record abnormal exits
                   7438: 
1.226     foxr     7439: 
1.22      harris41 7440: $SIG{'QUIT'}=\&catchexception;
                   7441: $SIG{__DIE__}=\&catchexception;
                   7442: 
1.81      matthew  7443: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95      harris41 7444: &status("Read loncapa.conf and loncapa_apache.conf");
                   7445: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141     foxr     7446: %perlvar=%{$perlvarref};
1.80      harris41 7447: undef $perlvarref;
1.19      www      7448: 
1.35      harris41 7449: # ----------------------------- Make sure this process is running from user=www
                   7450: my $wwwid=getpwnam('www');
                   7451: if ($wwwid!=$<) {
1.134     albertel 7452:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   7453:    my $subj="LON: $currenthostid User ID mismatch";
1.550     raeburn  7454:    system("echo 'User ID mismatch.  lond must be run as user www.' |".
                   7455:           " mail -s '$subj' $emailto > /dev/null");
1.35      harris41 7456:    exit 1;
                   7457: }
                   7458: 
1.19      www      7459: # --------------------------------------------- Check if other instance running
                   7460: 
                   7461: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
                   7462: 
                   7463: if (-e $pidfile) {
                   7464:    my $lfh=IO::File->new("$pidfile");
                   7465:    my $pide=<$lfh>;
                   7466:    chomp($pide);
1.29      harris41 7467:    if (kill 0 => $pide) { die "already running"; }
1.19      www      7468: }
1.1       albertel 7469: 
                   7470: # ------------------------------------------------------------- Read hosts file
                   7471: 
                   7472: 
                   7473: 
                   7474: # establish SERVER socket, bind and listen.
                   7475: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
                   7476:                                 Type      => SOCK_STREAM,
                   7477:                                 Proto     => 'tcp',
1.469     foxr     7478:                                 ReuseAddr     => 1,
1.1       albertel 7479:                                 Listen    => 10 )
1.29      harris41 7480:   or die "making socket: $@\n";
1.1       albertel 7481: 
                   7482: # --------------------------------------------------------- Do global variables
                   7483: 
                   7484: # global variables
                   7485: 
1.134     albertel 7486: my %children               = ();       # keys are current child process IDs
1.1       albertel 7487: 
                   7488: sub REAPER {                        # takes care of dead children
                   7489:     $SIG{CHLD} = \&REAPER;
1.165     albertel 7490:     &status("Handling child death");
1.178     foxr     7491:     my $pid;
                   7492:     do {
                   7493: 	$pid = waitpid(-1,&WNOHANG());
                   7494: 	if (defined($children{$pid})) {
                   7495: 	    &logthis("Child $pid died");
                   7496: 	    delete($children{$pid});
1.183     albertel 7497: 	} elsif ($pid > 0) {
1.178     foxr     7498: 	    &logthis("Unknown Child $pid died");
                   7499: 	}
                   7500:     } while ( $pid > 0 );
                   7501:     foreach my $child (keys(%children)) {
                   7502: 	$pid = waitpid($child,&WNOHANG());
                   7503: 	if ($pid > 0) {
                   7504: 	    &logthis("Child $child - $pid looks like we missed it's death");
                   7505: 	    delete($children{$pid});
                   7506: 	}
1.176     albertel 7507:     }
1.165     albertel 7508:     &status("Finished Handling child death");
1.1       albertel 7509: }
                   7510: 
                   7511: sub HUNTSMAN {                      # signal handler for SIGINT
1.165     albertel 7512:     &status("Killing children (INT)");
1.1       albertel 7513:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
                   7514:     kill 'INT' => keys %children;
1.59      www      7515:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1       albertel 7516:     my $execdir=$perlvar{'lonDaemons'};
                   7517:     unlink("$execdir/logs/lond.pid");
1.190     albertel 7518:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.165     albertel 7519:     &status("Done killing children");
1.1       albertel 7520:     exit;                           # clean up with dignity
                   7521: }
                   7522: 
                   7523: sub HUPSMAN {                      # signal handler for SIGHUP
                   7524:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
1.165     albertel 7525:     &status("Killing children for restart (HUP)");
1.1       albertel 7526:     kill 'INT' => keys %children;
1.59      www      7527:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.190     albertel 7528:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.134     albertel 7529:     my $execdir=$perlvar{'lonDaemons'};
1.30      harris41 7530:     unlink("$execdir/logs/lond.pid");
1.165     albertel 7531:     &status("Restarting self (HUP)");
1.1       albertel 7532:     exec("$execdir/lond");         # here we go again
                   7533: }
                   7534: 
1.144     foxr     7535: #
1.148     foxr     7536: #  Reload the Apache daemon's state.
1.150     foxr     7537: #  This is done by invoking /home/httpd/perl/apachereload
                   7538: #  a setuid perl script that can be root for us to do this job.
1.148     foxr     7539: #
                   7540: sub ReloadApache {
1.473     raeburn  7541: # --------------------------- Handle case of another apachereload process (locking)
1.474     raeburn  7542:     if (&LONCAPA::try_to_lock('/tmp/lock_apachereload')) {
                   7543:         my $execdir = $perlvar{'lonDaemons'};
                   7544:         my $script  = $execdir."/apachereload";
                   7545:         system($script);
                   7546:         unlink('/tmp/lock_apachereload'); #  Remove the lock file.
                   7547:     }
1.148     foxr     7548: }
                   7549: 
                   7550: #
1.144     foxr     7551: #   Called in response to a USR2 signal.
                   7552: #   - Reread hosts.tab
                   7553: #   - All children connected to hosts that were removed from hosts.tab
                   7554: #     are killed via SIGINT
                   7555: #   - All children connected to previously existing hosts are sent SIGUSR1
                   7556: #   - Our internal hosts hash is updated to reflect the new contents of
                   7557: #     hosts.tab causing connections from hosts added to hosts.tab to
                   7558: #     now be honored.
                   7559: #
                   7560: sub UpdateHosts {
1.165     albertel 7561:     &status("Reload hosts.tab");
1.147     foxr     7562:     logthis('<font color="blue"> Updating connections </font>');
1.148     foxr     7563:     #
                   7564:     #  The %children hash has the set of IP's we currently have children
                   7565:     #  on.  These need to be matched against records in the hosts.tab
                   7566:     #  Any ip's no longer in the table get killed off they correspond to
                   7567:     #  either dropped or changed hosts.  Note that the re-read of the table
                   7568:     #  will take care of new and changed hosts as connections come into being.
                   7569: 
1.371     albertel 7570:     &Apache::lonnet::reset_hosts_info();
1.532     raeburn  7571:     my %active;
1.148     foxr     7572: 
1.368     albertel 7573:     foreach my $child (keys(%children)) {
1.148     foxr     7574: 	my $childip = $children{$child};
1.374     albertel 7575: 	if ($childip ne '127.0.0.1'
                   7576: 	    && !defined(&Apache::lonnet::get_hosts_from_ip($childip))) {
1.149     foxr     7577: 	    logthis('<font color="blue"> UpdateHosts killing child '
                   7578: 		    ." $child for ip $childip </font>");
1.148     foxr     7579: 	    kill('INT', $child);
1.149     foxr     7580: 	} else {
1.532     raeburn  7581:             $active{$child} = $childip;
1.149     foxr     7582: 	    logthis('<font color="green"> keeping child for ip '
                   7583: 		    ." $childip (pid=$child) </font>");
1.148     foxr     7584: 	}
                   7585:     }
1.532     raeburn  7586: 
                   7587:     my %oldconf = %secureconf;
                   7588:     my %connchange;
1.555     raeburn  7589:     if (lonssl::Read_Connect_Config(\%secureconf,\%perlvar,\%crlchecked) eq 'ok') {
1.545     raeburn  7590:         logthis('<font color="blue"> Reloaded SSL connection rules and cleared CRL checking history </font>');
1.532     raeburn  7591:     } else {
1.545     raeburn  7592:         logthis('<font color="yellow"> Failed to reload SSL connection rules and clear CRL checking history </font>');
1.532     raeburn  7593:     }
                   7594:     if ((ref($oldconf{'connfrom'}) eq 'HASH') && (ref($secureconf{'connfrom'}) eq 'HASH')) {
                   7595:         foreach my $type ('dom','intdom','other') {
                   7596:             if ((($oldconf{'connfrom'}{$type} eq 'no') && ($secureconf{'connfrom'}{$type} eq 'req')) ||
                   7597:                 (($oldconf{'connfrom'}{$type} eq 'req') && ($secureconf{'connfrom'}{$type} eq 'no'))) {
                   7598:                 $connchange{$type} = 1;
                   7599:             }
                   7600:         }
                   7601:     }
                   7602:     if (keys(%connchange)) {
                   7603:         foreach my $child (keys(%active)) {
                   7604:             my $childip = $active{$child};
                   7605:             if ($childip ne '127.0.0.1') {
                   7606:                 my $childhostname  = gethostbyaddr(Socket::inet_aton($childip),AF_INET);
                   7607:                 if ($childhostname ne '') {
                   7608:                     my $childlonhost = &Apache::lonnet::get_server_homeID($childhostname);
                   7609:                     my ($samedom,$sameinst) = &set_client_info($childlonhost);
                   7610:                     if ($samedom) {
                   7611:                         if ($connchange{'dom'}) {
                   7612:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7613:                                    ." $child for ip $childip </font>");
                   7614:                             kill('INT', $child);
                   7615:                         }
                   7616:                     } elsif ($sameinst) {
                   7617:                         if ($connchange{'intdom'}) {
                   7618:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7619:                                    ." $child for ip $childip </font>");
                   7620:                            kill('INT', $child);
                   7621:                         }
                   7622:                     } else {
                   7623:                         if ($connchange{'other'}) {
                   7624:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7625:                                    ." $child for ip $childip </font>");
                   7626:                             kill('INT', $child);
                   7627:                         }
                   7628:                     }
                   7629:                 }
                   7630:             }
                   7631:         }
                   7632:     }
1.148     foxr     7633:     ReloadApache;
1.165     albertel 7634:     &status("Finished reloading hosts.tab");
1.144     foxr     7635: }
                   7636: 
1.57      www      7637: sub checkchildren {
1.165     albertel 7638:     &status("Checking on the children (sending signals)");
1.57      www      7639:     &initnewstatus();
                   7640:     &logstatus();
                   7641:     &logthis('Going to check on the children');
1.134     albertel 7642:     my $docdir=$perlvar{'lonDocRoot'};
1.61      harris41 7643:     foreach (sort keys %children) {
1.221     albertel 7644: 	#sleep 1;
1.57      www      7645:         unless (kill 'USR1' => $_) {
                   7646: 	    &logthis ('Child '.$_.' is dead');
                   7647:             &logstatus($$.' is dead');
1.221     albertel 7648: 	    delete($children{$_});
1.57      www      7649:         } 
1.61      harris41 7650:     }
1.63      www      7651:     sleep 5;
1.212     foxr     7652:     $SIG{ALRM} = sub { Debug("timeout"); 
                   7653: 		       die "timeout";  };
1.113     albertel 7654:     $SIG{__DIE__} = 'DEFAULT';
1.165     albertel 7655:     &status("Checking on the children (waiting for reports)");
1.63      www      7656:     foreach (sort keys %children) {
                   7657:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113     albertel 7658:           eval {
                   7659:             alarm(300);
1.63      www      7660: 	    &logthis('Child '.$_.' did not respond');
1.67      albertel 7661: 	    kill 9 => $_;
1.131     albertel 7662: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   7663: 	    #$subj="LON: $currenthostid killed lond process $_";
                   7664: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
                   7665: 	    #$execdir=$perlvar{'lonDaemons'};
                   7666: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.221     albertel 7667: 	    delete($children{$_});
1.113     albertel 7668: 	    alarm(0);
                   7669: 	  }
1.63      www      7670:         }
                   7671:     }
1.113     albertel 7672:     $SIG{ALRM} = 'DEFAULT';
1.155     albertel 7673:     $SIG{__DIE__} = \&catchexception;
1.165     albertel 7674:     &status("Finished checking children");
1.221     albertel 7675:     &logthis('Finished Checking children');
1.57      www      7676: }
                   7677: 
1.1       albertel 7678: # --------------------------------------------------------------------- Logging
                   7679: 
                   7680: sub logthis {
                   7681:     my $message=shift;
                   7682:     my $execdir=$perlvar{'lonDaemons'};
                   7683:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
                   7684:     my $now=time;
                   7685:     my $local=localtime($now);
1.58      www      7686:     $lastlog=$local.': '.$message;
1.1       albertel 7687:     print $fh "$local ($$): $message\n";
                   7688: }
                   7689: 
1.77      foxr     7690: # ------------------------- Conditional log if $DEBUG true.
                   7691: sub Debug {
                   7692:     my $message = shift;
                   7693:     if($DEBUG) {
                   7694: 	&logthis($message);
                   7695:     }
                   7696: }
1.161     foxr     7697: 
                   7698: #
                   7699: #   Sub to do replies to client.. this gives a hook for some
                   7700: #   debug tracing too:
                   7701: #  Parameters:
                   7702: #     fd      - File open on client.
                   7703: #     reply   - Text to send to client.
                   7704: #     request - Original request from client.
                   7705: #
1.490     droeschl 7706: #NOTE $reply must be terminated by exactly *one* \n. If $reply is a reference
                   7707: #this is done automatically ($$reply must not contain any \n in this case). 
                   7708: #If $reply is a string the caller has to ensure this.
1.161     foxr     7709: sub Reply {
1.192     foxr     7710:     my ($fd, $reply, $request) = @_;
1.387     albertel 7711:     if (ref($reply)) {
                   7712: 	print $fd $$reply;
                   7713: 	print $fd "\n";
                   7714: 	if ($DEBUG) { Debug("Request was $request  Reply was $$reply"); }
                   7715:     } else {
                   7716: 	print $fd $reply;
                   7717: 	if ($DEBUG) { Debug("Request was $request  Reply was $reply"); }
                   7718:     }
1.212     foxr     7719:     $Transactions++;
                   7720: }
                   7721: 
                   7722: 
                   7723: #
                   7724: #    Sub to report a failure.
                   7725: #    This function:
                   7726: #     -   Increments the failure statistic counters.
                   7727: #     -   Invokes Reply to send the error message to the client.
                   7728: # Parameters:
                   7729: #    fd       - File descriptor open on the client
                   7730: #    reply    - Reply text to emit.
                   7731: #    request  - The original request message (used by Reply
                   7732: #               to debug if that's enabled.
                   7733: # Implicit outputs:
                   7734: #    $Failures- The number of failures is incremented.
                   7735: #    Reply (invoked here) sends a message to the 
                   7736: #    client:
                   7737: #
                   7738: sub Failure {
                   7739:     my $fd      = shift;
                   7740:     my $reply   = shift;
                   7741:     my $request = shift;
                   7742:    
                   7743:     $Failures++;
                   7744:     Reply($fd, $reply, $request);      # That's simple eh?
1.161     foxr     7745: }
1.57      www      7746: # ------------------------------------------------------------------ Log status
                   7747: 
                   7748: sub logstatus {
1.178     foxr     7749:     &status("Doing logging");
                   7750:     my $docdir=$perlvar{'lonDocRoot'};
                   7751:     {
                   7752: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
1.200     matthew  7753:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
1.178     foxr     7754:         $fh->close();
                   7755:     }
1.221     albertel 7756:     &status("Finished $$.txt");
                   7757:     {
                   7758: 	open(LOG,">>$docdir/lon-status/londstatus.txt");
                   7759: 	flock(LOG,LOCK_EX);
                   7760: 	print LOG $$."\t".$clientname."\t".$currenthostid."\t"
                   7761: 	    .$status."\t".$lastlog."\t $keymode\n";
1.275     albertel 7762: 	flock(LOG,LOCK_UN);
1.221     albertel 7763: 	close(LOG);
                   7764:     }
1.178     foxr     7765:     &status("Finished logging");
1.57      www      7766: }
                   7767: 
                   7768: sub initnewstatus {
                   7769:     my $docdir=$perlvar{'lonDocRoot'};
                   7770:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
1.460     foxr     7771:     my $now=time();
1.57      www      7772:     my $local=localtime($now);
                   7773:     print $fh "LOND status $local - parent $$\n\n";
1.64      www      7774:     opendir(DIR,"$docdir/lon-status/londchld");
1.134     albertel 7775:     while (my $filename=readdir(DIR)) {
1.64      www      7776:         unlink("$docdir/lon-status/londchld/$filename");
                   7777:     }
                   7778:     closedir(DIR);
1.57      www      7779: }
                   7780: 
                   7781: # -------------------------------------------------------------- Status setting
                   7782: 
                   7783: sub status {
                   7784:     my $what=shift;
                   7785:     my $now=time;
                   7786:     my $local=localtime($now);
1.178     foxr     7787:     $status=$local.': '.$what;
                   7788:     $0='lond: '.$what.' '.$local;
1.57      www      7789: }
1.11      www      7790: 
1.13      www      7791: # -------------------------------------------------------------- Talk to lonsql
                   7792: 
1.234     foxr     7793: sub sql_reply {
1.12      harris41 7794:     my ($cmd)=@_;
1.234     foxr     7795:     my $answer=&sub_sql_reply($cmd);
                   7796:     if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
1.12      harris41 7797:     return $answer;
                   7798: }
                   7799: 
1.234     foxr     7800: sub sub_sql_reply {
1.12      harris41 7801:     my ($cmd)=@_;
                   7802:     my $unixsock="mysqlsock";
                   7803:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
                   7804:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                   7805:                                       Type    => SOCK_STREAM,
                   7806:                                       Timeout => 10)
                   7807:        or return "con_lost";
1.319     www      7808:     print $sclient "$cmd:$currentdomainid\n";
1.12      harris41 7809:     my $answer=<$sclient>;
                   7810:     chomp($answer);
                   7811:     if (!$answer) { $answer="con_lost"; }
                   7812:     return $answer;
                   7813: }
                   7814: 
1.1       albertel 7815: # --------------------------------------- Is this the home server of an author?
1.11      www      7816: 
1.1       albertel 7817: sub ishome {
                   7818:     my $author=shift;
                   7819:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   7820:     my ($udom,$uname)=split(/\//,$author);
                   7821:     my $proname=propath($udom,$uname);
                   7822:     if (-e $proname) {
                   7823: 	return 'owner';
                   7824:     } else {
                   7825:         return 'not_owner';
                   7826:     }
                   7827: }
                   7828: 
                   7829: # ======================================================= Continue main program
                   7830: # ---------------------------------------------------- Fork once and dissociate
                   7831: 
1.134     albertel 7832: my $fpid=fork;
1.1       albertel 7833: exit if $fpid;
1.29      harris41 7834: die "Couldn't fork: $!" unless defined ($fpid);
1.1       albertel 7835: 
1.29      harris41 7836: POSIX::setsid() or die "Can't start new session: $!";
1.1       albertel 7837: 
                   7838: # ------------------------------------------------------- Write our PID on disk
                   7839: 
1.134     albertel 7840: my $execdir=$perlvar{'lonDaemons'};
1.1       albertel 7841: open (PIDSAVE,">$execdir/logs/lond.pid");
                   7842: print PIDSAVE "$$\n";
                   7843: close(PIDSAVE);
1.190     albertel 7844: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.57      www      7845: &status('Starting');
1.1       albertel 7846: 
1.106     foxr     7847: 
1.1       albertel 7848: 
                   7849: # ----------------------------------------------------- Install signal handlers
                   7850: 
1.57      www      7851: 
1.1       albertel 7852: $SIG{CHLD} = \&REAPER;
                   7853: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   7854: $SIG{HUP}  = \&HUPSMAN;
1.57      www      7855: $SIG{USR1} = \&checkchildren;
1.144     foxr     7856: $SIG{USR2} = \&UpdateHosts;
1.106     foxr     7857: 
1.148     foxr     7858: #  Read the host hashes:
1.368     albertel 7859: &Apache::lonnet::load_hosts_tab();
1.447     raeburn  7860: my %iphost = &Apache::lonnet::get_iphost(1);
1.106     foxr     7861: 
1.480     raeburn  7862: $dist=`$perlvar{'lonDaemons'}/distprobe`;
1.286     albertel 7863: 
1.471     raeburn  7864: my $arch = `uname -i`;
1.475     raeburn  7865: chomp($arch);
1.471     raeburn  7866: if ($arch eq 'unknown') {
                   7867:     $arch = `uname -m`;
1.475     raeburn  7868:     chomp($arch);
1.471     raeburn  7869: }
                   7870: 
1.555     raeburn  7871: unless (lonssl::Read_Connect_Config(\%secureconf,\%perlvar,\%crlchecked) eq 'ok') {
1.532     raeburn  7872:     &logthis('<font color="blue">No connectionrules table. Will fallback to loncapa.conf</font>');
                   7873: }
                   7874: 
1.106     foxr     7875: # --------------------------------------------------------------
                   7876: #   Accept connections.  When a connection comes in, it is validated
                   7877: #   and if good, a child process is created to process transactions
                   7878: #   along the connection.
                   7879: 
1.1       albertel 7880: while (1) {
1.165     albertel 7881:     &status('Starting accept');
1.106     foxr     7882:     $client = $server->accept() or next;
1.165     albertel 7883:     &status('Accepted '.$client.' off to spawn');
1.386     albertel 7884:     make_new_child($client);
1.165     albertel 7885:     &status('Finished spawning');
1.1       albertel 7886: }
                   7887: 
1.212     foxr     7888: sub make_new_child {
                   7889:     my $pid;
                   7890: #    my $cipher;     # Now global
                   7891:     my $sigset;
1.178     foxr     7892: 
1.212     foxr     7893:     $client = shift;
                   7894:     &status('Starting new child '.$client);
                   7895:     &logthis('<font color="green"> Attempting to start child ('.$client.
                   7896: 	     ")</font>");    
                   7897:     # block signal for fork
                   7898:     $sigset = POSIX::SigSet->new(SIGINT);
                   7899:     sigprocmask(SIG_BLOCK, $sigset)
                   7900:         or die "Can't block SIGINT for fork: $!\n";
1.178     foxr     7901: 
1.212     foxr     7902:     die "fork: $!" unless defined ($pid = fork);
1.178     foxr     7903: 
1.212     foxr     7904:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
                   7905: 	                               # connection liveness.
1.178     foxr     7906: 
1.212     foxr     7907:     #
                   7908:     #  Figure out who we're talking to so we can record the peer in 
                   7909:     #  the pid hash.
                   7910:     #
                   7911:     my $caller = getpeername($client);
                   7912:     my ($port,$iaddr);
                   7913:     if (defined($caller) && length($caller) > 0) {
                   7914: 	($port,$iaddr)=unpack_sockaddr_in($caller);
                   7915:     } else {
                   7916: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
                   7917:     }
                   7918:     if (defined($iaddr)) {
                   7919: 	$clientip  = inet_ntoa($iaddr);
                   7920: 	Debug("Connected with $clientip");
                   7921:     } else {
                   7922: 	&logthis("Unable to determine clientip");
                   7923: 	$clientip='Unavailable';
                   7924:     }
                   7925:     
                   7926:     if ($pid) {
                   7927:         # Parent records the child's birth and returns.
                   7928:         sigprocmask(SIG_UNBLOCK, $sigset)
                   7929:             or die "Can't unblock SIGINT for fork: $!\n";
                   7930:         $children{$pid} = $clientip;
                   7931:         &status('Started child '.$pid);
1.462     foxr     7932: 	close($client);
1.212     foxr     7933:         return;
                   7934:     } else {
                   7935:         # Child can *not* return from this subroutine.
                   7936:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
                   7937:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
                   7938:                                 #don't get intercepted
                   7939:         $SIG{USR1}= \&logstatus;
                   7940:         $SIG{ALRM}= \&timeout;
1.468     foxr     7941: 	#
                   7942: 	# Block sigpipe as it gets thrownon socket disconnect and we want to 
                   7943: 	# deal with that as a read faiure instead.
                   7944: 	#
                   7945: 	my $blockset = POSIX::SigSet->new(SIGPIPE);
                   7946: 	sigprocmask(SIG_BLOCK, $blockset);
                   7947: 
1.212     foxr     7948:         $lastlog='Forked ';
                   7949:         $status='Forked';
1.178     foxr     7950: 
1.212     foxr     7951:         # unblock signals
                   7952:         sigprocmask(SIG_UNBLOCK, $sigset)
                   7953:             or die "Can't unblock SIGINT for fork: $!\n";
1.178     foxr     7954: 
1.212     foxr     7955: #        my $tmpsnum=0;            # Now global
                   7956: #---------------------------------------------------- kerberos 5 initialization
                   7957:         &Authen::Krb5::init_context();
1.511     raeburn  7958: 
                   7959:         my $no_ets;
1.571     raeburn  7960:         if ($dist =~ /^(?:centos|rhes|scientific|oracle|rocky|alma)(\d+)/) {
1.511     raeburn  7961:             if ($1 >= 7) {
                   7962:                 $no_ets = 1;
                   7963:             }
                   7964:         } elsif ($dist =~ /^suse(\d+\.\d+)$/) {
                   7965:             if (($1 eq '9.3') || ($1 >= 12.2)) {
                   7966:                 $no_ets = 1; 
                   7967:             }
1.514     raeburn  7968:         } elsif ($dist =~ /^sles(\d+)$/) {
                   7969:             if ($1 > 11) {
                   7970:                 $no_ets = 1;
                   7971:             }
1.511     raeburn  7972:         } elsif ($dist =~ /^fedora(\d+)$/) {
                   7973:             if ($1 < 7) {
                   7974:                 $no_ets = 1;
                   7975:             }
                   7976:         }
                   7977:         unless ($no_ets) {
1.286     albertel 7978: 	    &Authen::Krb5::init_ets();
                   7979: 	}
1.209     albertel 7980: 
1.212     foxr     7981: 	&status('Accepted connection');
                   7982: # =============================================================================
                   7983:             # do something with the connection
                   7984: # -----------------------------------------------------------------------------
                   7985: 	# see if we know client and 'check' for spoof IP by ineffective challenge
1.178     foxr     7986: 
1.278     albertel 7987: 	my $outsideip=$clientip;
                   7988: 	if ($clientip eq '127.0.0.1') {
1.368     albertel 7989: 	    $outsideip=&Apache::lonnet::get_host_ip($perlvar{'lonHostID'});
1.278     albertel 7990: 	}
1.412     foxr     7991: 	&ReadManagerTable();
1.368     albertel 7992: 	my $clientrec=defined(&Apache::lonnet::get_hosts_from_ip($outsideip));
1.278     albertel 7993: 	my $ismanager=($managers{$outsideip}    ne undef);
1.432     raeburn  7994: 	$clientname  = "[unknown]";
1.212     foxr     7995: 	if($clientrec) {	# Establish client type.
                   7996: 	    $ConnectionType = "client";
1.368     albertel 7997: 	    $clientname = (&Apache::lonnet::get_hosts_from_ip($outsideip))[-1];
1.212     foxr     7998: 	    if($ismanager) {
                   7999: 		$ConnectionType = "both";
                   8000: 	    }
                   8001: 	} else {
                   8002: 	    $ConnectionType = "manager";
1.278     albertel 8003: 	    $clientname = $managers{$outsideip};
1.212     foxr     8004: 	}
1.556     raeburn  8005: 	my $clientok;
1.178     foxr     8006: 
1.212     foxr     8007: 	if ($clientrec || $ismanager) {
                   8008: 	    &status("Waiting for init from $clientip $clientname");
                   8009: 	    &logthis('<font color="yellow">INFO: Connection, '.
                   8010: 		     $clientip.
                   8011: 		  " ($clientname) connection type = $ConnectionType </font>" );
                   8012: 	    &status("Connecting $clientip  ($clientname))"); 
                   8013: 	    my $remotereq=<$client>;
                   8014: 	    chomp($remotereq);
                   8015: 	    Debug("Got init: $remotereq");
1.337     albertel 8016: 
1.212     foxr     8017: 	    if ($remotereq =~ /^init/) {
                   8018: 		&sethost("sethost:$perlvar{'lonHostID'}");
                   8019: 		#
                   8020: 		#  If the remote is attempting a local init... give that a try:
                   8021: 		#
1.432     raeburn  8022: 		(my $i, my $inittype, $clientversion) = split(/:/, $remotereq);
1.492     droeschl 8023:         # For LON-CAPA 2.9, the  client session will have sent its LON-CAPA
                   8024:         # version when initiating the connection. For LON-CAPA 2.8 and older,
                   8025:         # the version is retrieved from the global %loncaparevs in lonnet.pm.            
1.494     droeschl 8026:         # $clientversion contains path to keyfile if $inittype eq 'local'
                   8027:         # it's overridden below in this case
1.492     droeschl 8028:         $clientversion ||= $Apache::lonnet::loncaparevs{$clientname};
1.209     albertel 8029: 
1.212     foxr     8030: 		# If the connection type is ssl, but I didn't get my
                   8031: 		# certificate files yet, then I'll drop  back to 
                   8032: 		# insecure (if allowed).
1.532     raeburn  8033: 
                   8034:                 if ($inittype eq "ssl") {
                   8035:                     my $context;
                   8036:                     if ($clientsamedom) {
                   8037:                         $context = 'dom';
                   8038:                         if ($secureconf{'connfrom'}{'dom'} eq 'no') {
                   8039:                             $inittype = "";
                   8040:                         }
                   8041:                     } elsif ($clientsameinst) {
                   8042:                         $context = 'intdom';
                   8043:                         if ($secureconf{'connfrom'}{'intdom'} eq 'no') {
                   8044:                             $inittype = "";
                   8045:                         }
                   8046:                     } else {
                   8047:                         $context = 'other';
                   8048:                         if ($secureconf{'connfrom'}{'other'} eq 'no') {
                   8049:                             $inittype = "";
                   8050:                         }
                   8051:                     }
                   8052:                     if ($inittype eq '') {
                   8053:                         &logthis("<font color=\"blue\"> Domain config set "
                   8054:                                 ."to no ssl for $clientname (context: $context)"
                   8055:                                 ." -- trying insecure auth</font>");
                   8056:                     }
                   8057:                 }
                   8058: 
1.212     foxr     8059: 		if($inittype eq "ssl") {
                   8060: 		    my ($ca, $cert) = lonssl::CertificateFile;
                   8061: 		    my $kfile       = lonssl::KeyFile;
                   8062: 		    if((!$ca)   || 
                   8063: 		       (!$cert) || 
                   8064: 		       (!$kfile)) {
                   8065: 			$inittype = ""; # This forces insecure attempt.
                   8066: 			&logthis("<font color=\"blue\"> Certificates not "
                   8067: 				 ."installed -- trying insecure auth</font>");
1.224     foxr     8068: 		    } else {	# SSL certificates are in place so
1.212     foxr     8069: 		    }		# Leave the inittype alone.
                   8070: 		}
                   8071: 
                   8072: 		if($inittype eq "local") {
1.432     raeburn  8073:                     $clientversion = $perlvar{'lonVersion'};
1.212     foxr     8074: 		    my $key = LocalConnection($client, $remotereq);
                   8075: 		    if($key) {
                   8076: 			Debug("Got local key $key");
                   8077: 			$clientok     = 1;
                   8078: 			my $cipherkey = pack("H32", $key);
                   8079: 			$cipher       = new IDEA($cipherkey);
                   8080: 			print $client "ok:local\n";
1.442     www      8081: 			&logthis('<font color="green">'
1.212     foxr     8082: 				 . "Successful local authentication </font>");
                   8083: 			$keymode = "local"
1.178     foxr     8084: 		    } else {
1.212     foxr     8085: 			Debug("Failed to get local key");
                   8086: 			$clientok = 0;
                   8087: 			shutdown($client, 3);
                   8088: 			close $client;
1.178     foxr     8089: 		    }
1.212     foxr     8090: 		} elsif ($inittype eq "ssl") {
1.532     raeburn  8091: 		    my $key = SSLConnection($client,$clientname);
1.212     foxr     8092: 		    if ($key) {
                   8093: 			$clientok = 1;
                   8094: 			my $cipherkey = pack("H32", $key);
                   8095: 			$cipher       = new IDEA($cipherkey);
                   8096: 			&logthis('<font color="green">'
                   8097: 				 ."Successfull ssl authentication with $clientname </font>");
                   8098: 			$keymode = "ssl";
                   8099: 	     
1.178     foxr     8100: 		    } else {
1.212     foxr     8101: 			$clientok = 0;
                   8102: 			close $client;
1.178     foxr     8103: 		    }
1.212     foxr     8104: 	   
                   8105: 		} else {
                   8106: 		    my $ok = InsecureConnection($client);
                   8107: 		    if($ok) {
                   8108: 			$clientok = 1;
                   8109: 			&logthis('<font color="green">'
                   8110: 				 ."Successful insecure authentication with $clientname </font>");
                   8111: 			print $client "ok\n";
                   8112: 			$keymode = "insecure";
1.178     foxr     8113: 		    } else {
1.212     foxr     8114: 			&logthis('<font color="yellow">'
                   8115: 				  ."Attempted insecure connection disallowed </font>");
                   8116: 			close $client;
                   8117: 			$clientok = 0;
1.178     foxr     8118: 		    }
                   8119: 		}
1.212     foxr     8120: 	    } else {
                   8121: 		&logthis(
                   8122: 			 "<font color='blue'>WARNING: "
                   8123: 			 ."$clientip failed to initialize: >$remotereq< </font>");
                   8124: 		&status('No init '.$clientip);
                   8125: 	    }
                   8126: 	} else {
                   8127: 	    &logthis(
                   8128: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
                   8129: 	    &status('Hung up on '.$clientip);
                   8130: 	}
                   8131:  
                   8132: 	if ($clientok) {
                   8133: # ---------------- New known client connecting, could mean machine online again
1.368     albertel 8134: 	    if (&Apache::lonnet::get_host_ip($currenthostid) ne $clientip 
1.367     albertel 8135: 		&& $clientip ne '127.0.0.1') {
1.375     albertel 8136: 		&Apache::lonnet::reconlonc($clientname);
1.212     foxr     8137: 	    }
                   8138: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
                   8139: 	    &status('Will listen to '.$clientname);
                   8140: # ------------------------------------------------------------ Process requests
                   8141: 	    my $keep_going = 1;
                   8142: 	    my $user_input;
1.556     raeburn  8143: 
1.212     foxr     8144: 	    while(($user_input = get_request) && $keep_going) {
                   8145: 		alarm(120);
                   8146: 		Debug("Main: Got $user_input\n");
                   8147: 		$keep_going = &process_request($user_input);
1.178     foxr     8148: 		alarm(0);
1.569     raeburn  8149: 		&status('Listening to '.$clientname." ($keymode)");
1.161     foxr     8150: 	    }
1.212     foxr     8151: 
1.59      www      8152: # --------------------------------------------- client unknown or fishy, refuse
1.212     foxr     8153: 	}  else {
1.161     foxr     8154: 	    print $client "refused\n";
                   8155: 	    $client->close();
1.190     albertel 8156: 	    &logthis("<font color='blue'>WARNING: "
1.161     foxr     8157: 		     ."Rejected client $clientip, closing connection</font>");
                   8158: 	}
1.525     raeburn  8159:     }
1.161     foxr     8160:     
1.1       albertel 8161: # =============================================================================
1.161     foxr     8162:     
1.190     albertel 8163:     &logthis("<font color='red'>CRITICAL: "
1.161     foxr     8164: 	     ."Disconnect from $clientip ($clientname)</font>");    
1.569     raeburn  8165: 
                   8166: 
1.161     foxr     8167:     # this exit is VERY important, otherwise the child will become
                   8168:     # a producer of more and more children, forking yourself into
                   8169:     # process death.
                   8170:     exit;
1.106     foxr     8171:     
1.78      foxr     8172: }
1.532     raeburn  8173: 
                   8174: #
                   8175: #  Used to determine if a particular client is from the same domain
1.556     raeburn  8176: #  as the current server, or from the same internet domain, and
                   8177: #  also if the client can host sessions for the domain's users.
                   8178: #  A hash is populated with keys set to commands sent by the client
                   8179: #  which may not be executed for this domain.
1.532     raeburn  8180: #
                   8181: #  Optional input -- the client to check for domain and internet domain.
                   8182: #  If not specified, defaults to the package variable: $clientname
                   8183: #
                   8184: #  If called in array context will not set package variables, but will
                   8185: #  instead return an array of two values - (a) true if client is in the
1.556     raeburn  8186: #  same domain as the server, and (b) true if client is in the same 
                   8187: #  internet domain.
1.532     raeburn  8188: #
                   8189: #  If called in scalar context, sets package variables for current client:
                   8190: #
1.556     raeburn  8191: #  $clienthomedom    - LonCAPA domain of homeID for client.
                   8192: #  $clientsamedom    - LonCAPA domain same for this host and client.
                   8193: #  $clientintdom     - LonCAPA "internet domain" for client.
                   8194: #  $clientsameinst   - LonCAPA "internet domain" same for this host & client.
                   8195: #  $clientremoteok   - If current domain permits hosting on this client: 1
                   8196: #  %clientprohibited - Commands prohibited for domain's users for this client.
                   8197: #
                   8198: #  if the host and client have the same "internet domain", then the value
                   8199: #  of $clientremoteok is not used, and no commands are prohibited.
1.532     raeburn  8200: #
                   8201: #  returns 1 to indicate package variables have been set for current client.
                   8202: #
                   8203: 
                   8204: sub set_client_info {
                   8205:     my ($lonhost) = @_;
                   8206:     $lonhost ||= $clientname;
                   8207:     my $clienthost = &Apache::lonnet::hostname($lonhost);
                   8208:     my $clientserverhomeID = &Apache::lonnet::get_server_homeID($clienthost);
                   8209:     my $homedom = &Apache::lonnet::host_domain($clientserverhomeID);
                   8210:     my $samedom = 0;
1.557     raeburn  8211:     if ($perlvar{'lonDefDomain'} eq $homedom) {
1.532     raeburn  8212:         $samedom = 1;
                   8213:     }
                   8214:     my $intdom = &Apache::lonnet::internet_dom($clientserverhomeID);
                   8215:     my $sameinst = 0;
                   8216:     if ($intdom ne '') {
                   8217:         my $internet_names = &Apache::lonnet::get_internet_names($currenthostid);
                   8218:         if (ref($internet_names) eq 'ARRAY') {
                   8219:             if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   8220:                 $sameinst = 1;
                   8221:             }
                   8222:         }
                   8223:     }
                   8224:     if (wantarray) {
                   8225:         return ($samedom,$sameinst);
                   8226:     } else {
                   8227:         $clienthomedom = $homedom;
                   8228:         $clientsamedom = $samedom;
                   8229:         $clientintdom = $intdom;
                   8230:         $clientsameinst = $sameinst;
1.556     raeburn  8231:         if ($clientsameinst) {
                   8232:             undef($clientremoteok);
                   8233:             undef(%clientprohibited);
                   8234:         } else {
                   8235:             $clientremoteok = &get_remote_hostable($currentdomainid);
                   8236:             %clientprohibited = &get_prohibited($currentdomainid);
                   8237:         }
1.532     raeburn  8238:         return 1;
                   8239:     }
                   8240: }
                   8241: 
1.261     foxr     8242: #
                   8243: #   Determine if a user is an author for the indicated domain.
                   8244: #
                   8245: # Parameters:
                   8246: #    domain          - domain to check in .
                   8247: #    user            - Name of user to check.
                   8248: #
                   8249: # Return:
                   8250: #     1             - User is an author for domain.
                   8251: #     0             - User is not an author for domain.
                   8252: sub is_author {
                   8253:     my ($domain, $user) = @_;
                   8254: 
                   8255:     &Debug("is_author: $user @ $domain");
                   8256: 
                   8257:     my $hashref = &tie_user_hash($domain, $user, "roles",
                   8258: 				 &GDBM_READER());
                   8259: 
                   8260:     #  Author role should show up as a key /domain/_au
1.78      foxr     8261: 
1.321     albertel 8262:     my $value;
1.487     foxr     8263:     if ($hashref) {
1.78      foxr     8264: 
1.487     foxr     8265: 	my $key    = "/$domain/_au";
                   8266: 	if (defined($hashref)) {
                   8267: 	    $value = $hashref->{$key};
                   8268: 	    if(!untie_user_hash($hashref)) {
                   8269: 		return 'error: ' .  ($!+0)." untie (GDBM) Failed";
                   8270: 	    }
                   8271: 	}
                   8272: 	
                   8273: 	if(defined($value)) {
                   8274: 	    &Debug("$user @ $domain is an author");
                   8275: 	}
                   8276:     } else {
                   8277: 	return 'error: '.($!+0)." tie (GDBM) Failed";
1.261     foxr     8278:     }
                   8279: 
                   8280:     return defined($value);
                   8281: }
1.78      foxr     8282: #
                   8283: #   Checks to see if the input roleput request was to set
1.482     www      8284: # an author role.  If so, creates construction space 
1.78      foxr     8285: # Parameters:
                   8286: #    request   - The request sent to the rolesput subchunk.
                   8287: #                We're looking for  /domain/_au
                   8288: #    domain    - The domain in which the user is having roles doctored.
                   8289: #    user      - Name of the user for which the role is being put.
                   8290: #    authtype  - The authentication type associated with the user.
                   8291: #
1.289     albertel 8292: sub manage_permissions {
1.192     foxr     8293:     my ($request, $domain, $user, $authtype) = @_;
1.78      foxr     8294:     # See if the request is of the form /$domain/_au
1.289     albertel 8295:     if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
1.484     raeburn  8296:         my $path=$perlvar{'lonDocRoot'}."/priv/$domain";
1.482     www      8297:         unless (-e $path) {        
                   8298:            mkdir($path);
                   8299:         }
                   8300:         unless (-e $path.'/'.$user) {
                   8301:            mkdir($path.'/'.$user);
                   8302:         }
1.78      foxr     8303:     }
                   8304: }
1.222     foxr     8305: 
                   8306: 
                   8307: #
                   8308: #  Return the full path of a user password file, whether it exists or not.
                   8309: # Parameters:
                   8310: #   domain     - Domain in which the password file lives.
                   8311: #   user       - name of the user.
                   8312: # Returns:
                   8313: #    Full passwd path:
                   8314: #
                   8315: sub password_path {
                   8316:     my ($domain, $user) = @_;
1.264     albertel 8317:     return &propath($domain, $user).'/passwd';
1.222     foxr     8318: }
                   8319: 
                   8320: #   Password Filename
                   8321: #   Returns the path to a passwd file given domain and user... only if
                   8322: #  it exists.
                   8323: # Parameters:
                   8324: #   domain    - Domain in which to search.
                   8325: #   user      - username.
                   8326: # Returns:
                   8327: #   - If the password file exists returns its path.
                   8328: #   - If the password file does not exist, returns undefined.
                   8329: #
                   8330: sub password_filename {
                   8331:     my ($domain, $user) = @_;
                   8332: 
                   8333:     Debug ("PasswordFilename called: dom = $domain user = $user");
                   8334: 
                   8335:     my $path  = &password_path($domain, $user);
                   8336:     Debug("PasswordFilename got path: $path");
                   8337:     if(-e $path) {
                   8338: 	return $path;
                   8339:     } else {
                   8340: 	return undef;
                   8341:     }
                   8342: }
                   8343: 
                   8344: #
                   8345: #   Rewrite the contents of the user's passwd file.
                   8346: #  Parameters:
                   8347: #    domain    - domain of the user.
                   8348: #    name      - User's name.
                   8349: #    contents  - New contents of the file.
1.533     raeburn  8350: #    saveold   - (optional). If true save old file in a passwd.bak file.
1.222     foxr     8351: # Returns:
                   8352: #   0    - Failed.
                   8353: #   1    - Success.
                   8354: #
                   8355: sub rewrite_password_file {
1.533     raeburn  8356:     my ($domain, $user, $contents, $saveold) = @_;
1.222     foxr     8357: 
                   8358:     my $file = &password_filename($domain, $user);
                   8359:     if (defined $file) {
1.533     raeburn  8360:         if ($saveold) {
                   8361:             my $bakfile = $file.'.bak';
                   8362:             if (CopyFile($file,$bakfile)) {
                   8363:                 chmod(0400,$bakfile);
                   8364:                 &logthis("Old password saved in passwd.bak for internally authenticated user: $user:$domain");
                   8365:             } else {
                   8366:                 &logthis("Failed to save old password in passwd.bak for internally authenticated user: $user:$domain");
                   8367:             }
                   8368:         }
1.222     foxr     8369: 	my $pf = IO::File->new(">$file");
                   8370: 	if($pf) {
                   8371: 	    print $pf "$contents\n";
                   8372: 	    return 1;
                   8373: 	} else {
                   8374: 	    return 0;
                   8375: 	}
                   8376:     } else {
                   8377: 	return 0;
                   8378:     }
                   8379: 
                   8380: }
                   8381: 
1.78      foxr     8382: #
1.222     foxr     8383: #   get_auth_type - Determines the authorization type of a user in a domain.
1.78      foxr     8384: 
                   8385: #     Returns the authorization type or nouser if there is no such user.
                   8386: #
1.436     raeburn  8387: sub get_auth_type {
1.192     foxr     8388:     my ($domain, $user)  = @_;
1.78      foxr     8389: 
1.222     foxr     8390:     Debug("get_auth_type( $domain, $user ) \n");
1.78      foxr     8391:     my $proname    = &propath($domain, $user); 
                   8392:     my $passwdfile = "$proname/passwd";
                   8393:     if( -e $passwdfile ) {
                   8394: 	my $pf = IO::File->new($passwdfile);
                   8395: 	my $realpassword = <$pf>;
                   8396: 	chomp($realpassword);
1.79      foxr     8397: 	Debug("Password info = $realpassword\n");
1.78      foxr     8398: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79      foxr     8399: 	Debug("Authtype = $authtype, content = $contentpwd\n");
1.259     raeburn  8400: 	return "$authtype:$contentpwd";     
1.224     foxr     8401:     } else {
1.79      foxr     8402: 	Debug("Returning nouser");
1.78      foxr     8403: 	return "nouser";
                   8404:     }
1.1       albertel 8405: }
                   8406: 
1.220     foxr     8407: #
                   8408: #  Validate a user given their domain, name and password.  This utility
                   8409: #  function is used by both  AuthenticateHandler and ChangePasswordHandler
                   8410: #  to validate the login credentials of a user.
                   8411: # Parameters:
                   8412: #    $domain    - The domain being logged into (this is required due to
                   8413: #                 the capability for multihomed systems.
                   8414: #    $user      - The name of the user being validated.
                   8415: #    $password  - The user's propoposed password.
                   8416: #
                   8417: # Returns:
                   8418: #     1        - The domain,user,pasword triplet corresponds to a valid
                   8419: #                user.
                   8420: #     0        - The domain,user,password triplet is not a valid user.
                   8421: #
                   8422: sub validate_user {
1.396     raeburn  8423:     my ($domain, $user, $password, $checkdefauth) = @_;
1.220     foxr     8424: 
                   8425:     # Why negative ~pi you may well ask?  Well this function is about
                   8426:     # authentication, and therefore very important to get right.
                   8427:     # I've initialized the flag that determines whether or not I've 
                   8428:     # validated correctly to a value it's not supposed to get.
                   8429:     # At the end of this function. I'll ensure that it's not still that
                   8430:     # value so we don't just wind up returning some accidental value
                   8431:     # as a result of executing an unforseen code path that
1.249     foxr     8432:     # did not set $validated.  At the end of valid execution paths,
                   8433:     # validated shoule be 1 for success or 0 for failuer.
1.220     foxr     8434: 
                   8435:     my $validated = -3.14159;
                   8436: 
                   8437:     #  How we authenticate is determined by the type of authentication
                   8438:     #  the user has been assigned.  If the authentication type is
                   8439:     #  "nouser", the user does not exist so we will return 0.
                   8440: 
1.222     foxr     8441:     my $contents = &get_auth_type($domain, $user);
1.220     foxr     8442:     my ($howpwd, $contentpwd) = split(/:/, $contents);
                   8443: 
                   8444:     my $null = pack("C",0);	# Used by kerberos auth types.
                   8445: 
1.395     raeburn  8446:     if ($howpwd eq 'nouser') {
1.396     raeburn  8447:         if ($checkdefauth) {
                   8448:             my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   8449:             if ($domdefaults{'auth_def'} eq 'localauth') {
                   8450:                 $howpwd = $domdefaults{'auth_def'};
                   8451:                 $contentpwd = $domdefaults{'auth_arg_def'};
                   8452:             } elsif ((($domdefaults{'auth_def'} eq 'krb4') || 
                   8453:                       ($domdefaults{'auth_def'} eq 'krb5')) &&
                   8454:                      ($domdefaults{'auth_arg_def'} ne '')) {
1.574     raeburn  8455:                 #
                   8456:                 # Don't attempt authentication for username and password supplied
                   8457:                 # for user without an account if uername contains @ to avoid
1.575   ! raeburn  8458:                 # call to &Authen::Krb5::parse_name() which will result in con_lost
1.574     raeburn  8459:                 #
                   8460:                 unless ($user =~ /\@/) {
                   8461:                     $howpwd = $domdefaults{'auth_def'};
                   8462:                     $contentpwd = $domdefaults{'auth_arg_def'};
                   8463:                 }
1.396     raeburn  8464:             }
1.395     raeburn  8465:         }
1.533     raeburn  8466:     }
1.220     foxr     8467:     if ($howpwd ne 'nouser') {
                   8468: 	if($howpwd eq "internal") { # Encrypted is in local password file.
1.518     raeburn  8469:             if (length($contentpwd) == 13) {
                   8470:                 $validated = (crypt($password,$contentpwd) eq $contentpwd);
                   8471:                 if ($validated) {
1.533     raeburn  8472:                     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   8473:                     if ($domdefaults{'intauth_switch'}) {
                   8474:                         my $ncpass = &hash_passwd($domain,$password);
                   8475:                         my $saveold;
                   8476:                         if ($domdefaults{'intauth_switch'} == 2) {
                   8477:                             $saveold = 1;
                   8478:                         }
                   8479:                         if (&rewrite_password_file($domain,$user,"$howpwd:$ncpass",$saveold)) {
                   8480:                             &update_passwd_history($user,$domain,$howpwd,'conversion');
                   8481:                             &logthis("Validated password hashed with bcrypt for $user:$domain");
                   8482:                         }
1.518     raeburn  8483:                     }
                   8484:                 }
                   8485:             } else {
1.533     raeburn  8486:                 $validated = &check_internal_passwd($password,$contentpwd,$domain,$user);
1.518     raeburn  8487:             }
1.220     foxr     8488: 	}
                   8489: 	elsif ($howpwd eq "unix") { # User is a normal unix user.
                   8490: 	    $contentpwd = (getpwnam($user))[1];
                   8491: 	    if($contentpwd) {
                   8492: 		if($contentpwd eq 'x') { # Shadow password file...
                   8493: 		    my $pwauth_path = "/usr/local/sbin/pwauth";
                   8494: 		    open PWAUTH,  "|$pwauth_path" or
                   8495: 			die "Cannot invoke authentication";
                   8496: 		    print PWAUTH "$user\n$password\n";
                   8497: 		    close PWAUTH;
                   8498: 		    $validated = ! $?;
                   8499: 
                   8500: 		} else { 	         # Passwords in /etc/passwd. 
                   8501: 		    $validated = (crypt($password,
                   8502: 					$contentpwd) eq $contentpwd);
                   8503: 		}
                   8504: 	    } else {
                   8505: 		$validated = 0;
                   8506: 	    }
1.439     raeburn  8507: 	} elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
                   8508:             my $checkwithkrb5 = 0;
                   8509:             if ($dist =~/^fedora(\d+)$/) {
                   8510:                 if ($1 > 11) {
                   8511:                     $checkwithkrb5 = 1;
                   8512:                 }
                   8513:             } elsif ($dist =~ /^suse([\d.]+)$/) {
                   8514:                 if ($1 > 11.1) {
                   8515:                     $checkwithkrb5 = 1; 
                   8516:                 }
                   8517:             }
                   8518:             if ($checkwithkrb5) {
                   8519:                 $validated = &krb5_authen($password,$null,$user,$contentpwd);
                   8520:             } else {
                   8521:                 $validated = &krb4_authen($password,$null,$user,$contentpwd);
                   8522:             }
1.224     foxr     8523: 	} elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
1.439     raeburn  8524:             $validated = &krb5_authen($password,$null,$user,$contentpwd);
1.224     foxr     8525: 	} elsif ($howpwd eq "localauth") { 
1.220     foxr     8526: 	    #  Authenticate via installation specific authentcation method:
                   8527: 	    $validated = &localauth::localauth($user, 
                   8528: 					       $password, 
1.353     albertel 8529: 					       $contentpwd,
                   8530: 					       $domain);
1.358     albertel 8531: 	    if ($validated < 0) {
1.357     albertel 8532: 		&logthis("localauth for $contentpwd $user:$domain returned a $validated");
                   8533: 		$validated = 0;
                   8534: 	    }
1.224     foxr     8535: 	} else {			# Unrecognized auth is also bad.
1.220     foxr     8536: 	    $validated = 0;
                   8537: 	}
                   8538:     } else {
                   8539: 	$validated = 0;
                   8540:     }
                   8541:     #
                   8542:     #  $validated has the correct stat of the authentication:
                   8543:     #
                   8544: 
                   8545:     unless ($validated != -3.14159) {
1.249     foxr     8546: 	#  I >really really< want to know if this happens.
                   8547: 	#  since it indicates that user authentication is badly
                   8548: 	#  broken in some code path.
                   8549:         #
                   8550: 	die "ValidateUser - failed to set the value of validated $domain, $user $password";
1.220     foxr     8551:     }
                   8552:     return $validated;
                   8553: }
                   8554: 
1.518     raeburn  8555: sub check_internal_passwd {
1.533     raeburn  8556:     my ($plainpass,$stored,$domain,$user) = @_;
1.518     raeburn  8557:     my (undef,$method,@rest) = split(/!/,$stored);
1.533     raeburn  8558:     if ($method eq 'bcrypt') {
1.518     raeburn  8559:         my $result = &hash_passwd($domain,$plainpass,@rest);
                   8560:         if ($result ne $stored) {
                   8561:             return 0;
                   8562:         }
1.533     raeburn  8563:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   8564:         if ($domdefaults{'intauth_check'}) {
                   8565:             # Upgrade to a larger number of rounds if necessary
                   8566:             my $defaultcost = $domdefaults{'intauth_cost'};
                   8567:             if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
                   8568:                 $defaultcost = 10;
                   8569:             }
                   8570:             if (int($rest[0])<int($defaultcost)) {
                   8571:                 if ($domdefaults{'intauth_check'} == 1) { 
                   8572:                     my $ncpass = &hash_passwd($domain,$plainpass);
                   8573:                     if (&rewrite_password_file($domain,$user,"internal:$ncpass")) {
                   8574:                         &update_passwd_history($user,$domain,'internal','update cost');
                   8575:                         &logthis("Validated password hashed with bcrypt for $user:$domain");
                   8576:                     }
                   8577:                     return 1;
                   8578:                 } elsif ($domdefaults{'intauth_check'} == 2) {
                   8579:                     return 0;
                   8580:                 }
                   8581:             }
                   8582:         } else {
                   8583:             return 1;
1.518     raeburn  8584:         }
                   8585:     }
                   8586:     return 0;
                   8587: }
                   8588: 
                   8589: sub get_last_authchg {
                   8590:     my ($domain,$user) = @_;
                   8591:     my $lastmod;
                   8592:     my $logname = &propath($domain,$user).'/passwd.log';
                   8593:     if (-e "$logname") {
                   8594:         $lastmod = (stat("$logname"))[9];
                   8595:     }
                   8596:     return $lastmod;
                   8597: }
                   8598: 
1.439     raeburn  8599: sub krb4_authen {
                   8600:     my ($password,$null,$user,$contentpwd) = @_;
                   8601:     my $validated = 0;
                   8602:     if (!($password =~ /$null/) ) {  # Null password not allowed.
                   8603:         eval {
                   8604:             require Authen::Krb4;
                   8605:         };
                   8606:         if (!$@) {
                   8607:             my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
                   8608:                                                        "",
                   8609:                                                        $contentpwd,,
                   8610:                                                        'krbtgt',
                   8611:                                                        $contentpwd,
                   8612:                                                        1,
                   8613:                                                        $password);
                   8614:             if(!$k4error) {
                   8615:                 $validated = 1;
                   8616:             } else {
                   8617:                 $validated = 0;
                   8618:                 &logthis('krb4: '.$user.', '.$contentpwd.', '.
                   8619:                           &Authen::Krb4::get_err_txt($Authen::Krb4::error));
                   8620:             }
                   8621:         } else {
                   8622:             $validated = krb5_authen($password,$null,$user,$contentpwd);
                   8623:         }
                   8624:     }
                   8625:     return $validated;
                   8626: }
                   8627: 
                   8628: sub krb5_authen {
                   8629:     my ($password,$null,$user,$contentpwd) = @_;
                   8630:     my $validated = 0;
                   8631:     if(!($password =~ /$null/)) { # Null password not allowed.
                   8632:         my $krbclient = &Authen::Krb5::parse_name($user.'@'
                   8633:                                                   .$contentpwd);
                   8634:         my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
                   8635:         my $krbserver  = &Authen::Krb5::parse_name($krbservice);
                   8636:         my $credentials= &Authen::Krb5::cc_default();
                   8637:         $credentials->initialize(&Authen::Krb5::parse_name($user.'@'
                   8638:                                                             .$contentpwd));
                   8639:         my $krbreturn;
                   8640:         if (exists(&Authen::Krb5::get_init_creds_password)) {
                   8641:             $krbreturn =
                   8642:                 &Authen::Krb5::get_init_creds_password($krbclient,$password,
                   8643:                                                           $krbservice);
                   8644:             $validated = (ref($krbreturn) eq 'Authen::Krb5::Creds');
                   8645:         } else {
                   8646:             $krbreturn  =
                   8647:                 &Authen::Krb5::get_in_tkt_with_password($krbclient,$krbserver,
                   8648:                                                          $password,$credentials);
                   8649:             $validated = ($krbreturn == 1);
                   8650:         }
                   8651:         if (!$validated) {
                   8652:             &logthis('krb5: '.$user.', '.$contentpwd.', '.
                   8653:                      &Authen::Krb5::error());
                   8654:         }
                   8655:     }
                   8656:     return $validated;
                   8657: }
1.220     foxr     8658: 
1.84      albertel 8659: sub addline {
                   8660:     my ($fname,$hostid,$ip,$newline)=@_;
                   8661:     my $contents;
                   8662:     my $found=0;
1.355     albertel 8663:     my $expr='^'.quotemeta($hostid).':'.quotemeta($ip).':';
1.134     albertel 8664:     my $sh;
1.84      albertel 8665:     if ($sh=IO::File->new("$fname.subscription")) {
                   8666: 	while (my $subline=<$sh>) {
                   8667: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
                   8668: 	}
                   8669: 	$sh->close();
                   8670:     }
                   8671:     $sh=IO::File->new(">$fname.subscription");
                   8672:     if ($contents) { print $sh $contents; }
                   8673:     if ($newline) { print $sh $newline; }
                   8674:     $sh->close();
                   8675:     return $found;
1.86      www      8676: }
                   8677: 
1.234     foxr     8678: sub get_chat {
1.324     raeburn  8679:     my ($cdom,$cname,$udom,$uname,$group)=@_;
1.310     albertel 8680: 
1.87      www      8681:     my @entries=();
1.324     raeburn  8682:     my $namespace = 'nohist_chatroom';
                   8683:     my $namespace_inroom = 'nohist_inchatroom';
1.335     albertel 8684:     if ($group ne '') {
1.324     raeburn  8685:         $namespace .= '_'.$group;
                   8686:         $namespace_inroom .= '_'.$group;
                   8687:     }
                   8688:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 8689: 				 &GDBM_READER());
                   8690:     if ($hashref) {
                   8691: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.311     albertel 8692: 	&untie_user_hash($hashref);
1.123     www      8693:     }
1.124     www      8694:     my @participants=();
1.134     albertel 8695:     my $cutoff=time-60;
1.324     raeburn  8696:     $hashref = &tie_user_hash($cdom, $cname, $namespace_inroom,
1.310     albertel 8697: 			      &GDBM_WRCREAT());
                   8698:     if ($hashref) {
                   8699:         $hashref->{$uname.':'.$udom}=time;
                   8700:         foreach my $user (sort(keys(%$hashref))) {
                   8701: 	    if ($hashref->{$user}>$cutoff) {
                   8702: 		push(@participants, 'active_participant:'.$user);
1.123     www      8703:             }
                   8704:         }
1.311     albertel 8705:         &untie_user_hash($hashref);
1.86      www      8706:     }
1.124     www      8707:     return (@participants,@entries);
1.86      www      8708: }
                   8709: 
1.234     foxr     8710: sub chat_add {
1.324     raeburn  8711:     my ($cdom,$cname,$newchat,$group)=@_;
1.88      albertel 8712:     my @entries=();
1.142     www      8713:     my $time=time;
1.324     raeburn  8714:     my $namespace = 'nohist_chatroom';
                   8715:     my $logfile = 'chatroom.log';
1.335     albertel 8716:     if ($group ne '') {
1.324     raeburn  8717:         $namespace .= '_'.$group;
                   8718:         $logfile = 'chatroom_'.$group.'.log';
                   8719:     }
                   8720:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 8721: 				 &GDBM_WRCREAT());
                   8722:     if ($hashref) {
                   8723: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.88      albertel 8724: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
                   8725: 	my ($thentime,$idnum)=split(/\_/,$lastid);
                   8726: 	my $newid=$time.'_000000';
                   8727: 	if ($thentime==$time) {
                   8728: 	    $idnum=~s/^0+//;
                   8729: 	    $idnum++;
                   8730: 	    $idnum=substr('000000'.$idnum,-6,6);
                   8731: 	    $newid=$time.'_'.$idnum;
                   8732: 	}
1.310     albertel 8733: 	$hashref->{$newid}=$newchat;
1.88      albertel 8734: 	my $expired=$time-3600;
1.310     albertel 8735: 	foreach my $comment (keys(%$hashref)) {
                   8736: 	    my ($thistime) = ($comment=~/(\d+)\_/);
1.88      albertel 8737: 	    if ($thistime<$expired) {
1.310     albertel 8738: 		delete $hashref->{$comment};
1.88      albertel 8739: 	    }
                   8740: 	}
1.310     albertel 8741: 	{
                   8742: 	    my $proname=&propath($cdom,$cname);
1.324     raeburn  8743: 	    if (open(CHATLOG,">>$proname/$logfile")) { 
1.310     albertel 8744: 		print CHATLOG ("$time:".&unescape($newchat)."\n");
                   8745: 	    }
                   8746: 	    close(CHATLOG);
1.142     www      8747: 	}
1.311     albertel 8748: 	&untie_user_hash($hashref);
1.86      www      8749:     }
1.84      albertel 8750: }
                   8751: 
                   8752: sub unsub {
                   8753:     my ($fname,$clientip)=@_;
                   8754:     my $result;
1.188     foxr     8755:     my $unsubs = 0;		# Number of successful unsubscribes:
                   8756: 
                   8757: 
                   8758:     # An old way subscriptions were handled was to have a 
                   8759:     # subscription marker file:
                   8760: 
                   8761:     Debug("Attempting unlink of $fname.$clientname");
1.161     foxr     8762:     if (unlink("$fname.$clientname")) {
1.188     foxr     8763: 	$unsubs++;		# Successful unsub via marker file.
                   8764:     } 
                   8765: 
                   8766:     # The more modern way to do it is to have a subscription list
                   8767:     # file:
                   8768: 
1.84      albertel 8769:     if (-e "$fname.subscription") {
1.161     foxr     8770: 	my $found=&addline($fname,$clientname,$clientip,'');
1.188     foxr     8771: 	if ($found) { 
                   8772: 	    $unsubs++;
                   8773: 	}
                   8774:     } 
                   8775: 
                   8776:     #  If either or both of these mechanisms succeeded in unsubscribing a 
                   8777:     #  resource we can return ok:
                   8778: 
                   8779:     if($unsubs) {
                   8780: 	$result = "ok\n";
1.84      albertel 8781:     } else {
1.188     foxr     8782: 	$result = "not_subscribed\n";
1.84      albertel 8783:     }
1.188     foxr     8784: 
1.84      albertel 8785:     return $result;
                   8786: }
                   8787: 
1.101     www      8788: sub currentversion {
                   8789:     my $fname=shift;
                   8790:     my $version=-1;
                   8791:     my $ulsdir='';
                   8792:     if ($fname=~/^(.+)\/[^\/]+$/) {
                   8793:        $ulsdir=$1;
                   8794:     }
1.114     albertel 8795:     my ($fnamere1,$fnamere2);
                   8796:     # remove version if already specified
1.101     www      8797:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114     albertel 8798:     # get the bits that go before and after the version number
                   8799:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
                   8800: 	$fnamere1=$1;
                   8801: 	$fnamere2='.'.$2;
                   8802:     }
1.101     www      8803:     if (-e $fname) { $version=1; }
                   8804:     if (-e $ulsdir) {
1.134     albertel 8805: 	if(-d $ulsdir) {
                   8806: 	    if (opendir(LSDIR,$ulsdir)) {
                   8807: 		my $ulsfn;
                   8808: 		while ($ulsfn=readdir(LSDIR)) {
1.101     www      8809: # see if this is a regular file (ignore links produced earlier)
1.134     albertel 8810: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
                   8811: 		    unless (-l $thisfile) {
1.160     www      8812: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134     albertel 8813: 			    if ($1>$version) { $version=$1; }
                   8814: 			}
                   8815: 		    }
                   8816: 		}
                   8817: 		closedir(LSDIR);
                   8818: 		$version++;
                   8819: 	    }
                   8820: 	}
                   8821:     }
                   8822:     return $version;
1.101     www      8823: }
                   8824: 
                   8825: sub thisversion {
                   8826:     my $fname=shift;
                   8827:     my $version=-1;
                   8828:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
                   8829: 	$version=$1;
                   8830:     }
                   8831:     return $version;
                   8832: }
                   8833: 
1.84      albertel 8834: sub subscribe {
                   8835:     my ($userinput,$clientip)=@_;
                   8836:     my $result;
1.293     albertel 8837:     my ($cmd,$fname)=split(/:/,$userinput,2);
1.84      albertel 8838:     my $ownership=&ishome($fname);
                   8839:     if ($ownership eq 'owner') {
1.101     www      8840: # explitly asking for the current version?
                   8841:         unless (-e $fname) {
                   8842:             my $currentversion=&currentversion($fname);
                   8843: 	    if (&thisversion($fname)==$currentversion) {
                   8844:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
                   8845: 		    my $root=$1;
                   8846:                     my $extension=$2;
                   8847:                     symlink($root.'.'.$extension,
                   8848:                             $root.'.'.$currentversion.'.'.$extension);
1.102     www      8849:                     unless ($extension=~/\.meta$/) {
                   8850:                        symlink($root.'.'.$extension.'.meta',
                   8851:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
                   8852: 		    }
1.101     www      8853:                 }
                   8854:             }
                   8855:         }
1.84      albertel 8856: 	if (-e $fname) {
                   8857: 	    if (-d $fname) {
                   8858: 		$result="directory\n";
                   8859: 	    } else {
1.161     foxr     8860: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134     albertel 8861: 		my $now=time;
1.161     foxr     8862: 		my $found=&addline($fname,$clientname,$clientip,
                   8863: 				   "$clientname:$clientip:$now\n");
1.84      albertel 8864: 		if ($found) { $result="$fname\n"; }
                   8865: 		# if they were subscribed to only meta data, delete that
                   8866:                 # subscription, when you subscribe to a file you also get
                   8867:                 # the metadata
                   8868: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
                   8869: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
1.476     raeburn  8870:                 my $protocol = $Apache::lonnet::protocol{$perlvar{'lonHostID'}};
                   8871:                 $protocol = 'http' if ($protocol ne 'https');
                   8872: 		$fname=$protocol.'://'.&Apache::lonnet::hostname($perlvar{'lonHostID'})."/".$fname;
1.84      albertel 8873: 		$result="$fname\n";
                   8874: 	    }
                   8875: 	} else {
                   8876: 	    $result="not_found\n";
                   8877: 	}
                   8878:     } else {
                   8879: 	$result="rejected\n";
                   8880:     }
                   8881:     return $result;
                   8882: }
1.287     foxr     8883: #  Change the passwd of a unix user.  The caller must have
                   8884: #  first verified that the user is a loncapa user.
                   8885: #
                   8886: # Parameters:
                   8887: #    user      - Unix user name to change.
                   8888: #    pass      - New password for the user.
                   8889: # Returns:
                   8890: #    ok    - if success
                   8891: #    other - Some meaningfule error message string.
                   8892: # NOTE:
                   8893: #    invokes a setuid script to change the passwd.
                   8894: sub change_unix_password {
                   8895:     my ($user, $pass) = @_;
                   8896: 
                   8897:     &Debug("change_unix_password");
                   8898:     my $execdir=$perlvar{'lonDaemons'};
                   8899:     &Debug("Opening lcpasswd pipeline");
                   8900:     my $pf = IO::File->new("|$execdir/lcpasswd > "
                   8901: 			   ."$perlvar{'lonDaemons'}"
                   8902: 			   ."/logs/lcpasswd.log");
                   8903:     print $pf "$user\n$pass\n$pass\n";
                   8904:     close $pf;
                   8905:     my $err = $?;
                   8906:     return ($err < @passwderrors) ? $passwderrors[$err] : 
                   8907: 	"pwchange_falure - unknown error";
                   8908: 
                   8909:     
                   8910: }
                   8911: 
1.91      albertel 8912: 
                   8913: sub make_passwd_file {
1.518     raeburn  8914:     my ($uname,$udom,$umode,$npass,$passfilename,$action)=@_;
1.390     raeburn  8915:     my $result="ok";
1.91      albertel 8916:     if ($umode eq 'krb4' or $umode eq 'krb5') {
                   8917: 	{
                   8918: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8919: 	    if ($pf) {
                   8920: 		print $pf "$umode:$npass\n";
1.518     raeburn  8921:                 &update_passwd_history($uname,$udom,$umode,$action);
1.261     foxr     8922: 	    } else {
                   8923: 		$result = "pass_file_failed_error";
                   8924: 	    }
1.91      albertel 8925: 	}
                   8926:     } elsif ($umode eq 'internal') {
1.518     raeburn  8927:         my $ncpass = &hash_passwd($udom,$npass);
1.91      albertel 8928: 	{
                   8929: 	    &Debug("Creating internal auth");
                   8930: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8931: 	    if($pf) {
1.518     raeburn  8932: 		print $pf "internal:$ncpass\n";
                   8933:                 &update_passwd_history($uname,$udom,$umode,$action); 
1.261     foxr     8934: 	    } else {
                   8935: 		$result = "pass_file_failed_error";
                   8936: 	    }
1.91      albertel 8937: 	}
                   8938:     } elsif ($umode eq 'localauth') {
                   8939: 	{
                   8940: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8941: 	    if($pf) {
                   8942: 		print $pf "localauth:$npass\n";
1.524     raeburn  8943:                 &update_passwd_history($uname,$udom,$umode,$action);
1.261     foxr     8944: 	    } else {
                   8945: 		$result = "pass_file_failed_error";
                   8946: 	    }
1.91      albertel 8947: 	}
                   8948:     } elsif ($umode eq 'unix') {
1.502     raeburn  8949: 	&logthis(">>>Attempt to create unix account blocked -- unix auth not available for new users.");
                   8950: 	$result="no_new_unix_accounts";
1.91      albertel 8951:     } elsif ($umode eq 'none') {
                   8952: 	{
1.223     foxr     8953: 	    my $pf = IO::File->new("> $passfilename");
1.261     foxr     8954: 	    if($pf) {
                   8955: 		print $pf "none:\n";
                   8956: 	    } else {
                   8957: 		$result = "pass_file_failed_error";
                   8958: 	    }
1.91      albertel 8959: 	}
1.543     raeburn  8960:     } elsif ($umode eq 'lti') {
                   8961:         my $pf = IO::File->new(">$passfilename");
                   8962:         if($pf) {
                   8963:             print $pf "lti:\n";
                   8964:             &update_passwd_history($uname,$udom,$umode,$action);
                   8965:         } else {
                   8966:             $result = "pass_file_failed_error";
                   8967:         }
1.91      albertel 8968:     } else {
1.390     raeburn  8969: 	$result="auth_mode_error";
1.91      albertel 8970:     }
                   8971:     return $result;
1.121     albertel 8972: }
                   8973: 
1.265     albertel 8974: sub convert_photo {
                   8975:     my ($start,$dest)=@_;
                   8976:     system("convert $start $dest");
                   8977: }
                   8978: 
1.121     albertel 8979: sub sethost {
                   8980:     my ($remotereq) = @_;
                   8981:     my (undef,$hostid)=split(/:/,$remotereq);
1.322     albertel 8982:     # ignore sethost if we are already correct
                   8983:     if ($hostid eq $currenthostid) {
                   8984: 	return 'ok';
                   8985:     }
                   8986: 
1.121     albertel 8987:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
1.368     albertel 8988:     if (&Apache::lonnet::get_host_ip($perlvar{'lonHostID'}) 
                   8989: 	eq &Apache::lonnet::get_host_ip($hostid)) {
1.200     matthew  8990: 	$currenthostid  =$hostid;
1.369     albertel 8991: 	$currentdomainid=&Apache::lonnet::host_domain($hostid);
1.556     raeburn  8992:         &set_client_info();
1.443     www      8993: #	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
1.121     albertel 8994:     } else {
                   8995: 	&logthis("Requested host id $hostid not an alias of ".
                   8996: 		 $perlvar{'lonHostID'}." refusing connection");
                   8997: 	return 'unable_to_set';
                   8998:     }
                   8999:     return 'ok';
                   9000: }
                   9001: 
                   9002: sub version {
                   9003:     my ($userinput)=@_;
                   9004:     $remoteVERSION=(split(/:/,$userinput))[1];
                   9005:     return "version:$VERSION";
1.127     albertel 9006: }
1.178     foxr     9007: 
1.447     raeburn  9008: sub get_usersession_config {
                   9009:     my ($dom,$name) = @_;
                   9010:     my ($usersessionconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   9011:     if (defined($cached)) {
                   9012:         return $usersessionconf;
                   9013:     } else {
                   9014:         my %domconfig = &Apache::lonnet::get_dom('configuration',['usersessions'],$dom);
1.525     raeburn  9015:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'usersessions'},3600);
                   9016:         return $domconfig{'usersessions'};
1.447     raeburn  9017:     }
                   9018:     return;
                   9019: }
1.200     matthew  9020: 
1.534     raeburn  9021: sub get_usersearch_config {
                   9022:     my ($dom,$name) = @_;
                   9023:     my ($usersearchconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   9024:     if (defined($cached)) {
                   9025:         return $usersearchconf;
                   9026:     } else {
                   9027:         my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$dom);
                   9028:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'directorysrch'},600);
                   9029:         return $domconfig{'directorysrch'};
                   9030:     }
                   9031:     return;
                   9032: }
                   9033: 
1.525     raeburn  9034: sub get_prohibited {
                   9035:     my ($dom) = @_;
                   9036:     my $name = 'trust';
                   9037:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   9038:     unless (defined($cached)) {
                   9039:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$dom);
                   9040:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'trust'},3600);
                   9041:         $trustconfig = $domconfig{'trust'};
                   9042:     }
                   9043:     my %prohibited;
                   9044:     if (ref($trustconfig)) {
                   9045:         foreach my $prefix (keys(%{$trustconfig})) {
                   9046:             if (ref($trustconfig->{$prefix}) eq 'HASH') {
                   9047:                 my $reject;
                   9048:                 if (ref($trustconfig->{$prefix}->{'exc'}) eq 'ARRAY') {
                   9049:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'exc'}})) {
                   9050:                         $reject = 1;
                   9051:                     }
                   9052:                 }
                   9053:                 if (ref($trustconfig->{$prefix}->{'inc'}) eq 'ARRAY') {
                   9054:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'inc'}})) {
                   9055:                         $reject = 0;
                   9056:                     } else {
                   9057:                         $reject = 1;
                   9058:                     }
                   9059:                 }
                   9060:                 if ($reject) {
                   9061:                     $prohibited{$prefix} = 1;
                   9062:                 }
                   9063:             }
                   9064:         }
                   9065:     }
                   9066:     return %prohibited;
                   9067: }
1.450     raeburn  9068: 
1.556     raeburn  9069: sub get_remote_hostable {
                   9070:     my ($dom) = @_;
                   9071:     my $result;
                   9072:     if ($clientintdom) {
                   9073:         $result = 1;
                   9074:         my $remsessconf = &get_usersession_config($dom,'remotesession');
                   9075:         if (ref($remsessconf) eq 'HASH') {
                   9076:             if (ref($remsessconf->{'remote'}) eq 'HASH') {
                   9077:                 if (ref($remsessconf->{'remote'}->{'excludedomain'}) eq 'ARRAY') {
                   9078:                     if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'excludedomain'}})) {
                   9079:                         $result = 0;
                   9080:                     }
                   9081:                 }
                   9082:                 if (ref($remsessconf->{'remote'}->{'includedomain'}) eq 'ARRAY') {
                   9083:                     if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'includedomain'}})) {
                   9084:                         $result = 1;
                   9085:                     } else {
                   9086:                         $result = 0;
                   9087:                     }
                   9088:                 }
                   9089:             }
                   9090:         }
                   9091:     }
                   9092:     return $result;
                   9093: }
                   9094: 
1.471     raeburn  9095: sub distro_and_arch {
                   9096:     return $dist.':'.$arch;
                   9097: }
                   9098: 
1.61      harris41 9099: # ----------------------------------- POD (plain old documentation, CPAN style)
                   9100: 
                   9101: =head1 NAME
                   9102: 
                   9103: lond - "LON Daemon" Server (port "LOND" 5663)
                   9104: 
                   9105: =head1 SYNOPSIS
                   9106: 
1.74      harris41 9107: Usage: B<lond>
                   9108: 
                   9109: Should only be run as user=www.  This is a command-line script which
                   9110: is invoked by B<loncron>.  There is no expectation that a typical user
                   9111: will manually start B<lond> from the command-line.  (In other words,
                   9112: DO NOT START B<lond> YOURSELF.)
1.61      harris41 9113: 
                   9114: =head1 DESCRIPTION
                   9115: 
1.74      harris41 9116: There are two characteristics associated with the running of B<lond>,
                   9117: PROCESS MANAGEMENT (starting, stopping, handling child processes)
                   9118: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
                   9119: subscriptions, etc).  These are described in two large
                   9120: sections below.
                   9121: 
                   9122: B<PROCESS MANAGEMENT>
                   9123: 
1.61      harris41 9124: Preforker - server who forks first. Runs as a daemon. HUPs.
                   9125: Uses IDEA encryption
                   9126: 
1.74      harris41 9127: B<lond> forks off children processes that correspond to the other servers
                   9128: in the network.  Management of these processes can be done at the
                   9129: parent process level or the child process level.
                   9130: 
                   9131: B<logs/lond.log> is the location of log messages.
                   9132: 
                   9133: The process management is now explained in terms of linux shell commands,
                   9134: subroutines internal to this code, and signal assignments:
                   9135: 
                   9136: =over 4
                   9137: 
                   9138: =item *
                   9139: 
                   9140: PID is stored in B<logs/lond.pid>
                   9141: 
                   9142: This is the process id number of the parent B<lond> process.
                   9143: 
                   9144: =item *
                   9145: 
                   9146: SIGTERM and SIGINT
                   9147: 
                   9148: Parent signal assignment:
                   9149:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   9150: 
                   9151: Child signal assignment:
                   9152:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
                   9153: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
                   9154:  to restart a new child.)
                   9155: 
                   9156: Command-line invocations:
                   9157:  B<kill> B<-s> SIGTERM I<PID>
                   9158:  B<kill> B<-s> SIGINT I<PID>
                   9159: 
                   9160: Subroutine B<HUNTSMAN>:
                   9161:  This is only invoked for the B<lond> parent I<PID>.
                   9162: This kills all the children, and then the parent.
                   9163: The B<lonc.pid> file is cleared.
                   9164: 
                   9165: =item *
                   9166: 
                   9167: SIGHUP
                   9168: 
                   9169: Current bug:
                   9170:  This signal can only be processed the first time
                   9171: on the parent process.  Subsequent SIGHUP signals
                   9172: have no effect.
                   9173: 
                   9174: Parent signal assignment:
                   9175:  $SIG{HUP}  = \&HUPSMAN;
                   9176: 
                   9177: Child signal assignment:
                   9178:  none (nothing happens)
                   9179: 
                   9180: Command-line invocations:
                   9181:  B<kill> B<-s> SIGHUP I<PID>
                   9182: 
                   9183: Subroutine B<HUPSMAN>:
                   9184:  This is only invoked for the B<lond> parent I<PID>,
                   9185: This kills all the children, and then the parent.
                   9186: The B<lond.pid> file is cleared.
                   9187: 
                   9188: =item *
                   9189: 
                   9190: SIGUSR1
                   9191: 
                   9192: Parent signal assignment:
                   9193:  $SIG{USR1} = \&USRMAN;
                   9194: 
                   9195: Child signal assignment:
                   9196:  $SIG{USR1}= \&logstatus;
                   9197: 
                   9198: Command-line invocations:
                   9199:  B<kill> B<-s> SIGUSR1 I<PID>
                   9200: 
                   9201: Subroutine B<USRMAN>:
                   9202:  When invoked for the B<lond> parent I<PID>,
                   9203: SIGUSR1 is sent to all the children, and the status of
                   9204: each connection is logged.
1.144     foxr     9205: 
                   9206: =item *
                   9207: 
                   9208: SIGUSR2
                   9209: 
                   9210: Parent Signal assignment:
                   9211:     $SIG{USR2} = \&UpdateHosts
                   9212: 
                   9213: Child signal assignment:
                   9214:     NONE
                   9215: 
1.74      harris41 9216: 
                   9217: =item *
                   9218: 
                   9219: SIGCHLD
                   9220: 
                   9221: Parent signal assignment:
                   9222:  $SIG{CHLD} = \&REAPER;
                   9223: 
                   9224: Child signal assignment:
                   9225:  none
                   9226: 
                   9227: Command-line invocations:
                   9228:  B<kill> B<-s> SIGCHLD I<PID>
                   9229: 
                   9230: Subroutine B<REAPER>:
                   9231:  This is only invoked for the B<lond> parent I<PID>.
                   9232: Information pertaining to the child is removed.
                   9233: The socket port is cleaned up.
                   9234: 
                   9235: =back
                   9236: 
                   9237: B<SERVER-SIDE ACTIVITIES>
                   9238: 
                   9239: Server-side information can be accepted in an encrypted or non-encrypted
                   9240: method.
                   9241: 
                   9242: =over 4
                   9243: 
                   9244: =item ping
                   9245: 
                   9246: Query a client in the hosts.tab table; "Are you there?"
                   9247: 
                   9248: =item pong
                   9249: 
                   9250: Respond to a ping query.
                   9251: 
                   9252: =item ekey
                   9253: 
                   9254: Read in encrypted key, make cipher.  Respond with a buildkey.
                   9255: 
                   9256: =item load
                   9257: 
                   9258: Respond with CPU load based on a computation upon /proc/loadavg.
                   9259: 
                   9260: =item currentauth
                   9261: 
                   9262: Reply with current authentication information (only over an
                   9263: encrypted channel).
                   9264: 
                   9265: =item auth
                   9266: 
                   9267: Only over an encrypted channel, reply as to whether a user's
                   9268: authentication information can be validated.
                   9269: 
                   9270: =item passwd
                   9271: 
                   9272: Allow for a password to be set.
                   9273: 
                   9274: =item makeuser
                   9275: 
                   9276: Make a user.
                   9277: 
1.517     raeburn  9278: =item changeuserauth
1.74      harris41 9279: 
                   9280: Allow for authentication mechanism and password to be changed.
                   9281: 
                   9282: =item home
1.61      harris41 9283: 
1.74      harris41 9284: Respond to a question "are you the home for a given user?"
                   9285: 
                   9286: =item update
                   9287: 
                   9288: Update contents of a subscribed resource.
                   9289: 
                   9290: =item unsubscribe
                   9291: 
                   9292: The server is unsubscribing from a resource.
                   9293: 
                   9294: =item subscribe
                   9295: 
                   9296: The server is subscribing to a resource.
                   9297: 
                   9298: =item log
                   9299: 
                   9300: Place in B<logs/lond.log>
                   9301: 
                   9302: =item put
                   9303: 
                   9304: stores hash in namespace
                   9305: 
1.496     raeburn  9306: =item rolesput
1.74      harris41 9307: 
                   9308: put a role into a user's environment
                   9309: 
                   9310: =item get
                   9311: 
                   9312: returns hash with keys from array
                   9313: reference filled in from namespace
                   9314: 
                   9315: =item eget
                   9316: 
                   9317: returns hash with keys from array
                   9318: reference filled in from namesp (encrypts the return communication)
                   9319: 
                   9320: =item rolesget
                   9321: 
                   9322: get a role from a user's environment
                   9323: 
                   9324: =item del
                   9325: 
                   9326: deletes keys out of array from namespace
                   9327: 
                   9328: =item keys
                   9329: 
                   9330: returns namespace keys
                   9331: 
                   9332: =item dump
                   9333: 
                   9334: dumps the complete (or key matching regexp) namespace into a hash
                   9335: 
                   9336: =item store
                   9337: 
                   9338: stores hash permanently
                   9339: for this url; hashref needs to be given and should be a \%hashname; the
                   9340: remaining args aren't required and if they aren't passed or are '' they will
                   9341: be derived from the ENV
                   9342: 
                   9343: =item restore
                   9344: 
                   9345: returns a hash for a given url
                   9346: 
                   9347: =item querysend
                   9348: 
                   9349: Tells client about the lonsql process that has been launched in response
                   9350: to a sent query.
                   9351: 
                   9352: =item queryreply
                   9353: 
                   9354: Accept information from lonsql and make appropriate storage in temporary
                   9355: file space.
                   9356: 
                   9357: =item idput
                   9358: 
                   9359: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
                   9360: for each student, defined perhaps by the institutional Registrar.)
                   9361: 
                   9362: =item idget
                   9363: 
                   9364: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
                   9365: for each student, defined perhaps by the institutional Registrar.)
                   9366: 
1.517     raeburn  9367: =item iddel
                   9368: 
                   9369: Deletes one or more ids in a domain's id database.
                   9370: 
1.74      harris41 9371: =item tmpput
                   9372: 
                   9373: Accept and store information in temporary space.
                   9374: 
                   9375: =item tmpget
                   9376: 
                   9377: Send along temporarily stored information.
                   9378: 
                   9379: =item ls
                   9380: 
                   9381: List part of a user's directory.
                   9382: 
1.135     foxr     9383: =item pushtable
                   9384: 
                   9385: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
                   9386: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
                   9387: must be restored manually in case of a problem with the new table file.
                   9388: pushtable requires that the request be encrypted and validated via
                   9389: ValidateManager.  The form of the command is:
                   9390: enc:pushtable tablename <tablecontents> \n
                   9391: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
                   9392: cleartext newline.
                   9393: 
1.74      harris41 9394: =item Hanging up (exit or init)
                   9395: 
                   9396: What to do when a client tells the server that they (the client)
                   9397: are leaving the network.
                   9398: 
                   9399: =item unknown command
                   9400: 
                   9401: If B<lond> is sent an unknown command (not in the list above),
                   9402: it replys to the client "unknown_cmd".
1.135     foxr     9403: 
1.74      harris41 9404: 
                   9405: =item UNKNOWN CLIENT
                   9406: 
                   9407: If the anti-spoofing algorithm cannot verify the client,
                   9408: the client is rejected (with a "refused" message sent
                   9409: to the client, and the connection is closed.
                   9410: 
                   9411: =back
1.61      harris41 9412: 
                   9413: =head1 PREREQUISITES
                   9414: 
                   9415: IO::Socket
                   9416: IO::File
                   9417: Apache::File
                   9418: POSIX
                   9419: Crypt::IDEA
                   9420: GDBM_File
                   9421: Authen::Krb4
1.91      albertel 9422: Authen::Krb5
1.61      harris41 9423: 
                   9424: =head1 COREQUISITES
                   9425: 
1.490     droeschl 9426: none
                   9427: 
1.61      harris41 9428: =head1 OSNAMES
                   9429: 
                   9430: linux
                   9431: 
                   9432: =head1 SCRIPT CATEGORIES
                   9433: 
                   9434: Server/Process
                   9435: 
                   9436: =cut
1.409     foxr     9437: 
                   9438: 
                   9439: =pod
                   9440: 
                   9441: =head1 LOG MESSAGES
                   9442: 
                   9443: The messages below can be emitted in the lond log.  This log is located
                   9444: in ~httpd/perl/logs/lond.log  Many log messages have HTML encapsulation
                   9445: to provide coloring if examined from inside a web page. Some do not.
                   9446: Where color is used, the colors are; Red for sometihhng to get excited
                   9447: about and to follow up on. Yellow for something to keep an eye on to
                   9448: be sure it does not get worse, Green,and Blue for informational items.
                   9449: 
                   9450: In the discussions below, sometimes reference is made to ~httpd
                   9451: when describing file locations.  There isn't really an httpd 
                   9452: user, however there is an httpd directory that gets installed in the
                   9453: place that user home directories go.  On linux, this is usually
                   9454: (always?) /home/httpd.
                   9455: 
                   9456: 
                   9457: Some messages are colorless.  These are usually (not always)
                   9458: Green/Blue color level messages.
                   9459: 
                   9460: =over 2
                   9461: 
                   9462: =item (Red)  LocalConnection rejecting non local: <ip> ne 127.0.0.1
                   9463: 
                   9464: A local connection negotiation was attempted by
                   9465: a host whose IP address was not 127.0.0.1.
                   9466: The socket is closed and the child will exit.
                   9467: lond has three ways to establish an encyrption
                   9468: key with a client:
                   9469: 
                   9470: =over 2
                   9471: 
                   9472: =item local 
                   9473: 
                   9474: The key is written and read from a file.
                   9475: This is only valid for connections from localhost.
                   9476: 
                   9477: =item insecure 
                   9478: 
                   9479: The key is generated by the server and
                   9480: transmitted to the client.
                   9481: 
                   9482: =item  ssl (secure)
                   9483: 
                   9484: An ssl connection is negotiated with the client,
                   9485: the key is generated by the server and sent to the 
                   9486: client across this ssl connection before the
                   9487: ssl connectionis terminated and clear text
                   9488: transmission resumes.
                   9489: 
                   9490: =back
                   9491: 
                   9492: =item (Red) LocalConnection: caller is insane! init = <init> and type = <type>
                   9493: 
                   9494: The client is local but has not sent an initialization
                   9495: string that is the literal "init:local"  The connection
                   9496: is closed and the child exits.
                   9497: 
                   9498: =item Red CRITICAL Can't get key file <error>        
                   9499: 
                   9500: SSL key negotiation is being attempted but the call to
1.549     raeburn  9501: lonssl::KeyFile failed.  This usually means that the
1.409     foxr     9502: configuration file is not correctly defining or protecting
                   9503: the directories/files lonCertificateDirectory or
                   9504: lonnetPrivateKey
                   9505: <error> is a string that describes the reason that
                   9506: the key file could not be located.
                   9507: 
                   9508: =item (Red) CRITICAL  Can't get certificates <error>  
                   9509: 
                   9510: SSL key negotiation failed because we were not able to retrives our certificate
                   9511: or the CA's certificate in the call to lonssl::CertificateFile
                   9512: <error> is the textual reason this failed.  Usual reasons:
                   9513: 
                   9514: =over 2
1.490     droeschl 9515: 
1.409     foxr     9516: =item Apache config file for loncapa  incorrect:
1.490     droeschl 9517: 
1.409     foxr     9518: one of the variables 
                   9519: lonCertificateDirectory, lonnetCertificateAuthority, or lonnetCertificate
                   9520: undefined or incorrect
                   9521: 
                   9522: =item Permission error:
                   9523: 
                   9524: The directory pointed to by lonCertificateDirectory is not readable by lond
                   9525: 
                   9526: =item Permission error:
                   9527: 
                   9528: Files in the directory pointed to by lonCertificateDirectory are not readable by lond.
                   9529: 
                   9530: =item Installation error:                         
                   9531: 
                   9532: Either the certificate authority file or the certificate have not
                   9533: been installed in lonCertificateDirectory.
                   9534: 
                   9535: =item (Red) CRITICAL SSL Socket promotion failed:  <err> 
                   9536: 
                   9537: The promotion of the connection from plaintext to SSL failed
                   9538: <err> is the reason for the failure.  There are two
                   9539: system calls involved in the promotion (one of which failed), 
                   9540: a dup to produce
                   9541: a second fd on the raw socket over which the encrypted data
                   9542: will flow and IO::SOcket::SSL->new_from_fd which creates
                   9543: the SSL connection on the duped fd.
                   9544: 
                   9545: =item (Blue)   WARNING client did not respond to challenge 
                   9546: 
                   9547: This occurs on an insecure (non SSL) connection negotiation request.
                   9548: lond generates some number from the time, the PID and sends it to
                   9549: the client.  The client must respond by echoing this information back.
                   9550: If the client does not do so, that's a violation of the challenge
                   9551: protocols and the connection will be failed.
                   9552: 
                   9553: =item (Red) No manager table. Nobody can manage!!    
                   9554: 
                   9555: lond has the concept of privileged hosts that
                   9556: can perform remote management function such
                   9557: as update the hosts.tab.   The manager hosts
                   9558: are described in the 
                   9559: ~httpd/lonTabs/managers.tab file.
                   9560: this message is logged if this file is missing.
                   9561: 
                   9562: 
                   9563: =item (Green) Registering manager <dnsname> as <cluster_name> with <ipaddress>
                   9564: 
                   9565: Reports the successful parse and registration
                   9566: of a specific manager. 
                   9567: 
                   9568: =item Green existing host <clustername:dnsname>  
                   9569: 
                   9570: The manager host is already defined in the hosts.tab
                   9571: the information in that table, rather than the info in the
                   9572: manager table will be used to determine the manager's ip.
                   9573: 
                   9574: =item (Red) Unable to craete <filename>                 
                   9575: 
                   9576: lond has been asked to create new versions of an administrative
                   9577: file (by a manager).  When this is done, the new file is created
                   9578: in a temp file and then renamed into place so that there are always
                   9579: usable administrative files, even if the update fails.  This failure
                   9580: message means that the temp file could not be created.
                   9581: The update is abandoned, and the old file is available for use.
                   9582: 
                   9583: =item (Green) CopyFile from <oldname> to <newname> failed
                   9584: 
                   9585: In an update of administrative files, the copy of the existing file to a
                   9586: backup file failed.  The installation of the new file may still succeed,
                   9587: but there will not be a back up file to rever to (this should probably
                   9588: be yellow).
                   9589: 
                   9590: =item (Green) Pushfile: backed up <oldname> to <newname>
                   9591: 
                   9592: See above, the backup of the old administrative file succeeded.
                   9593: 
                   9594: =item (Red)  Pushfile: Unable to install <filename> <reason>
                   9595: 
                   9596: The new administrative file could not be installed.  In this case,
                   9597: the old administrative file is still in use.
                   9598: 
                   9599: =item (Green) Installed new < filename>.                      
                   9600: 
                   9601: The new administrative file was successfullly installed.                                               
                   9602: 
                   9603: =item (Red) Reinitializing lond pid=<pid>                    
                   9604: 
                   9605: The lonc child process <pid> will be sent a USR2 
                   9606: signal.
                   9607: 
                   9608: =item (Red) Reinitializing self                                    
                   9609: 
                   9610: We've been asked to re-read our administrative files,and
                   9611: are doing so.
                   9612: 
                   9613: =item (Yellow) error:Invalid process identifier <ident>  
                   9614: 
                   9615: A reinit command was received, but the target part of the 
                   9616: command was not valid.  It must be either
                   9617: 'lond' or 'lonc' but was <ident>
                   9618: 
                   9619: =item (Green) isValideditCommand checking: Command = <command> Key = <key> newline = <newline>
                   9620: 
                   9621: Checking to see if lond has been handed a valid edit
                   9622: command.  It is possible the edit command is not valid
                   9623: in that case there are no log messages to indicate that.
                   9624: 
                   9625: =item Result of password change for  <username> pwchange_success
                   9626: 
                   9627: The password for <username> was
                   9628: successfully changed.
                   9629: 
                   9630: =item Unable to open <user> passwd to change password
                   9631: 
                   9632: Could not rewrite the 
                   9633: internal password file for a user
                   9634: 
                   9635: =item Result of password change for <user> : <result>
1.490     droeschl 9636: 
1.409     foxr     9637: A unix password change for <user> was attempted 
                   9638: and the pipe returned <result>  
                   9639: 
                   9640: =item LWP GET: <message> for <fname> (<remoteurl>)
                   9641: 
                   9642: The lightweight process fetch for a resource failed
                   9643: with <message> the local filename that should
                   9644: have existed/been created was  <fname> the
                   9645: corresponding URI: <remoteurl>  This is emitted in several
                   9646: places.
                   9647: 
                   9648: =item Unable to move <transname> to <destname>     
                   9649: 
                   9650: From fetch_user_file_handler - the user file was replicated but could not
                   9651: be mv'd to its final location.
                   9652: 
                   9653: =item Looking for <domain> <username>              
                   9654: 
                   9655: From user_has_session_handler - This should be a Debug call instead
                   9656: it indicates lond is about to check whether the specified user has a 
                   9657: session active on the specified domain on the local host.
                   9658: 
                   9659: =item Client <ip> (<name>) hanging up: <input>     
                   9660: 
                   9661: lond has been asked to exit by its client.  The <ip> and <name> identify the
                   9662: client systemand <input> is the full exit command sent to the server.
                   9663: 
                   9664: =item Red CRITICAL: ABNORMAL EXIT. child <pid> for server <hostname> died through a crass with this error->[<message>].
1.490     droeschl 9665: 
1.409     foxr     9666: A lond child terminated.  NOte that this termination can also occur when the
                   9667: child receives the QUIT or DIE signals.  <pid> is the process id of the child,
                   9668: <hostname> the host lond is working for, and <message> the reason the child died
                   9669: to the best of our ability to get it (I would guess that any numeric value
                   9670: represents and errno value).  This is immediately followed by
                   9671: 
                   9672: =item  Famous last words: Catching exception - <log> 
                   9673: 
                   9674: Where log is some recent information about the state of the child.
                   9675: 
                   9676: =item Red CRITICAL: TIME OUT <pid>                     
                   9677: 
                   9678: Some timeout occured for server <pid>.  THis is normally a timeout on an LWP
                   9679: doing an HTTP::GET.
                   9680: 
                   9681: =item child <pid> died                              
                   9682: 
                   9683: The reaper caught a SIGCHILD for the lond child process <pid>
                   9684: This should be modified to also display the IP of the dying child
                   9685: $children{$pid}
                   9686: 
                   9687: =item Unknown child 0 died                           
                   9688: A child died but the wait for it returned a pid of zero which really should not
                   9689: ever happen. 
                   9690: 
                   9691: =item Child <which> - <pid> looks like we missed it's death 
                   9692: 
                   9693: When a sigchild is received, the reaper process checks all children to see if they are
                   9694: alive.  If children are dying quite quickly, the lack of signal queuing can mean
                   9695: that a signal hearalds the death of more than one child.  If so this message indicates
                   9696: which other one died. <which> is the ip of a dead child
                   9697: 
                   9698: =item Free socket: <shutdownretval>                
                   9699: 
                   9700: The HUNTSMAN sub was called due to a SIGINT in a child process.  The socket is being shutdown.
                   9701: for whatever reason, <shutdownretval> is printed but in fact shutdown() is not documented
                   9702: to return anything. This is followed by: 
                   9703: 
                   9704: =item Red CRITICAL: Shutting down                       
                   9705: 
                   9706: Just prior to exit.
                   9707: 
                   9708: =item Free socket: <shutdownretval>                 
                   9709: 
                   9710: The HUPSMAN sub was called due to a SIGHUP.  all children get killsed, and lond execs itself.
                   9711: This is followed by:
                   9712: 
                   9713: =item (Red) CRITICAL: Restarting                         
                   9714: 
                   9715: lond is about to exec itself to restart.
                   9716: 
                   9717: =item (Blue) Updating connections                        
                   9718: 
                   9719: (In response to a USR2).  All the children (except the one for localhost)
                   9720: are about to be killed, the hosts tab reread, and Apache reloaded via apachereload.
                   9721: 
                   9722: =item (Blue) UpdateHosts killing child <pid> for ip <ip>   
                   9723: 
                   9724: Due to USR2 as above.
                   9725: 
                   9726: =item (Green) keeping child for ip <ip> (pid = <pid>)    
                   9727: 
                   9728: In response to USR2 as above, the child indicated is not being restarted because
                   9729: it's assumed that we'll always need a child for the localhost.
                   9730: 
                   9731: 
                   9732: =item Going to check on the children                
                   9733: 
                   9734: Parent is about to check on the health of the child processes.
                   9735: Note that this is in response to a USR1 sent to the parent lond.
                   9736: there may be one or more of the next two messages:
                   9737: 
                   9738: =item <pid> is dead                                 
                   9739: 
                   9740: A child that we have in our child hash as alive has evidently died.
                   9741: 
                   9742: =item  Child <pid> did not respond                   
                   9743: 
                   9744: In the health check the child <pid> did not update/produce a pid_.txt
                   9745: file when sent it's USR1 signal.  That process is killed with a 9 signal, as it's
                   9746: assumed to be hung in some un-fixable way.
                   9747: 
                   9748: =item Finished checking children                   
1.490     droeschl 9749: 
1.409     foxr     9750: Master processs's USR1 processing is cojmplete.
                   9751: 
                   9752: =item (Red) CRITICAL: ------- Starting ------            
                   9753: 
                   9754: (There are more '-'s on either side).  Lond has forked itself off to 
                   9755: form a new session and is about to start actual initialization.
                   9756: 
                   9757: =item (Green) Attempting to start child (<client>)       
                   9758: 
                   9759: Started a new child process for <client>.  Client is IO::Socket object
                   9760: connected to the child.  This was as a result of a TCP/IP connection from a client.
                   9761: 
                   9762: =item Unable to determine who caller was, getpeername returned nothing
1.490     droeschl 9763: 
1.409     foxr     9764: In child process initialization.  either getpeername returned undef or
                   9765: a zero sized object was returned.  Processing continues, but in my opinion,
                   9766: this should be cause for the child to exit.
                   9767: 
                   9768: =item Unable to determine clientip                  
                   9769: 
                   9770: In child process initialization.  The peer address from getpeername was not defined.
                   9771: The client address is stored as "Unavailable" and processing continues.
                   9772: 
                   9773: =item (Yellow) INFO: Connection <ip> <name> connection type = <type>
1.490     droeschl 9774: 
1.409     foxr     9775: In child initialization.  A good connectionw as received from <ip>.
                   9776: 
                   9777: =over 2
                   9778: 
                   9779: =item <name> 
                   9780: 
                   9781: is the name of the client from hosts.tab.
                   9782: 
                   9783: =item <type> 
                   9784: 
                   9785: Is the connection type which is either 
                   9786: 
                   9787: =over 2
                   9788: 
                   9789: =item manager 
                   9790: 
                   9791: The connection is from a manager node, not in hosts.tab
                   9792: 
                   9793: =item client  
                   9794: 
                   9795: the connection is from a non-manager in the hosts.tab
                   9796: 
                   9797: =item both
                   9798: 
                   9799: The connection is from a manager in the hosts.tab.
                   9800: 
                   9801: =back
                   9802: 
                   9803: =back
                   9804: 
                   9805: =item (Blue) Certificates not installed -- trying insecure auth
                   9806: 
                   9807: One of the certificate file, key file or
                   9808: certificate authority file could not be found for a client attempting
                   9809: SSL connection intiation.  COnnection will be attemptied in in-secure mode.
                   9810: (this would be a system with an up to date lond that has not gotten a 
                   9811: certificate from us).
                   9812: 
                   9813: =item (Green)  Successful local authentication            
                   9814: 
                   9815: A local connection successfully negotiated the encryption key. 
                   9816: In this case the IDEA key is in a file (that is hopefully well protected).
                   9817: 
                   9818: =item (Green) Successful ssl authentication with <client>  
                   9819: 
                   9820: The client (<client> is the peer's name in hosts.tab), has successfully
                   9821: negotiated an SSL connection with this child process.
                   9822: 
                   9823: =item (Green) Successful insecure authentication with <client>
1.490     droeschl 9824: 
1.409     foxr     9825: 
                   9826: The client has successfully negotiated an  insecure connection withthe child process.
                   9827: 
                   9828: =item (Yellow) Attempted insecure connection disallowed    
                   9829: 
                   9830: The client attempted and failed to successfully negotiate a successful insecure
                   9831: connection.  This can happen either because the variable londAllowInsecure is false
                   9832: or undefined, or becuse the child did not successfully echo back the challenge
                   9833: string.
                   9834: 
                   9835: 
                   9836: =back
                   9837: 
1.441     raeburn  9838: =back
                   9839: 
1.409     foxr     9840: 
                   9841: =cut

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