Annotation of loncom/lond, revision 1.580

1.1       albertel    1: #!/usr/bin/perl
                      2: # The LearningOnline Network
                      3: # lond "LON Daemon" Server (port "LOND" 5663)
1.60      www         4: #
1.580   ! raeburn     5: # $Id: lond,v 1.579 2023/06/07 14:21:52 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.580   ! raeburn    68: my $VERSION='$Revision: 1.579 $'; #' 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},
1.577     raeburn   309:                signlti => {remote => 1},
1.525     raeburn   310:                store => {remote => 1, enroll => 1, reqcrs => 1,},
                    311:                studentphoto => {remote => 1, enroll => 1},
                    312:                sub => {content => 1,},
1.552     raeburn   313:                tmpdel => {institutiononly => 1},
                    314:                tmpget => {institutiononly => 1},
                    315:                tmpput => {remote => 1, othcoau => 1},
1.525     raeburn   316:                tokenauthuserfile => {anywhere => 1},
1.575     raeburn   317:                unamemaprules => {remote => 1,},
1.525     raeburn   318:                unsub => {content => 1,},
                    319:                update => {shared => 1},
1.564     raeburn   320:                updatebalcookie => {institutiononly => 1},
1.525     raeburn   321:                updateclickers => {remote => 1},
                    322:                userhassession => {anywhere => 1},
                    323:                userload => {anywhere => 1},
                    324:                version => {anywhere => 1}, #not used
                    325:             );
                    326: 
                    327: #
1.207     foxr      328: #   Statistics that are maintained and dislayed in the status line.
                    329: #
1.212     foxr      330: my $Transactions = 0;		# Number of attempted transactions.
                    331: my $Failures     = 0;		# Number of transcations failed.
1.207     foxr      332: 
                    333: #   ResetStatistics: 
                    334: #      Resets the statistics counters:
                    335: #
                    336: sub ResetStatistics {
                    337:     $Transactions = 0;
                    338:     $Failures     = 0;
                    339: }
                    340: 
1.200     matthew   341: #------------------------------------------------------------------------
                    342: #
                    343: #   LocalConnection
                    344: #     Completes the formation of a locally authenticated connection.
                    345: #     This function will ensure that the 'remote' client is really the
                    346: #     local host.  If not, the connection is closed, and the function fails.
                    347: #     If so, initcmd is parsed for the name of a file containing the
                    348: #     IDEA session key.  The fie is opened, read, deleted and the session
                    349: #     key returned to the caller.
                    350: #
                    351: # Parameters:
                    352: #   $Socket      - Socket open on client.
                    353: #   $initcmd     - The full text of the init command.
                    354: #
                    355: # Returns:
                    356: #     IDEA session key on success.
                    357: #     undef on failure.
                    358: #
                    359: sub LocalConnection {
                    360:     my ($Socket, $initcmd) = @_;
1.373     albertel  361:     Debug("Attempting local connection: $initcmd client: $clientip");
1.277     albertel  362:     if($clientip ne "127.0.0.1") {
1.200     matthew   363: 	&logthis('<font color="red"> LocalConnection rejecting non local: '
1.373     albertel  364: 		 ."$clientip ne 127.0.0.1 </font>");
1.200     matthew   365: 	close $Socket;
                    366: 	return undef;
1.224     foxr      367:     }  else {
1.200     matthew   368: 	chomp($initcmd);	# Get rid of \n in filename.
                    369: 	my ($init, $type, $name) = split(/:/, $initcmd);
                    370: 	Debug(" Init command: $init $type $name ");
                    371: 
                    372: 	# Require that $init = init, and $type = local:  Otherwise
                    373: 	# the caller is insane:
                    374: 
                    375: 	if(($init ne "init") && ($type ne "local")) {
                    376: 	    &logthis('<font color = "red"> LocalConnection: caller is insane! '
                    377: 		     ."init = $init, and type = $type </font>");
                    378: 	    close($Socket);;
                    379: 	    return undef;
                    380: 		
                    381: 	}
                    382: 	#  Now get the key filename:
                    383: 
                    384: 	my $IDEAKey = lonlocal::ReadKeyFile($name);
                    385: 	return $IDEAKey;
                    386:     }
                    387: }
                    388: #------------------------------------------------------------------------------
                    389: #
                    390: #  SSLConnection
                    391: #   Completes the formation of an ssh authenticated connection. The
                    392: #   socket is promoted to an ssl socket.  If this promotion and the associated
                    393: #   certificate exchange are successful, the IDEA key is generated and sent
                    394: #   to the remote peer via the SSL tunnel. The IDEA key is also returned to
                    395: #   the caller after the SSL tunnel is torn down.
                    396: #
                    397: # Parameters:
                    398: #   Name              Type             Purpose
                    399: #   $Socket          IO::Socket::INET  Plaintext socket.
                    400: #
                    401: # Returns:
                    402: #    IDEA key on success.
                    403: #    undef on failure.
                    404: #
                    405: sub SSLConnection {
                    406:     my $Socket   = shift;
                    407: 
                    408:     Debug("SSLConnection: ");
                    409:     my $KeyFile         = lonssl::KeyFile();
                    410:     if(!$KeyFile) {
                    411: 	my $err = lonssl::LastError();
                    412: 	&logthis("<font color=\"red\"> CRITICAL"
                    413: 		 ."Can't get key file $err </font>");
                    414: 	return undef;
                    415:     }
                    416:     my ($CACertificate,
                    417: 	$Certificate) = lonssl::CertificateFile();
                    418: 
                    419: 
                    420:     # If any of the key, certificate or certificate authority 
                    421:     # certificate filenames are not defined, this can't work.
                    422: 
                    423:     if((!$Certificate) || (!$CACertificate)) {
                    424: 	my $err = lonssl::LastError();
                    425: 	&logthis("<font color=\"red\"> CRITICAL"
                    426: 		 ."Can't get certificates: $err </font>");
                    427: 
                    428: 	return undef;
                    429:     }
                    430:     Debug("Key: $KeyFile CA: $CACertificate Cert: $Certificate");
                    431: 
                    432:     # Indicate to our peer that we can procede with
                    433:     # a transition to ssl authentication:
                    434: 
                    435:     print $Socket "ok:ssl\n";
                    436: 
                    437:     Debug("Approving promotion -> ssl");
                    438:     #  And do so:
                    439: 
1.545     raeburn   440:     my $CRLFile;
                    441:     unless ($crlchecked{$clientname}) {
                    442:         $CRLFile = lonssl::CRLFile();
                    443:         $crlchecked{$clientname} = 1;
                    444:     }
                    445: 
1.200     matthew   446:     my $SSLSocket = lonssl::PromoteServerSocket($Socket,
                    447: 						$CACertificate,
                    448: 						$Certificate,
1.544     raeburn   449: 						$KeyFile,
1.545     raeburn   450: 						$clientname,
1.546     raeburn   451:                                                 $CRLFile,
                    452:                                                 $clientversion);
1.200     matthew   453:     if(! ($SSLSocket) ) {	# SSL socket promotion failed.
                    454: 	my $err = lonssl::LastError();
                    455: 	&logthis("<font color=\"red\"> CRITICAL "
                    456: 		 ."SSL Socket promotion failed: $err </font>");
                    457: 	return undef;
                    458:     }
                    459:     Debug("SSL Promotion successful");
                    460: 
                    461:     # 
                    462:     #  The only thing we'll use the socket for is to send the IDEA key
                    463:     #  to the peer:
                    464: 
                    465:     my $Key = lonlocal::CreateCipherKey();
                    466:     print $SSLSocket "$Key\n";
                    467: 
                    468:     lonssl::Close($SSLSocket); 
                    469: 
                    470:     Debug("Key exchange complete: $Key");
                    471: 
                    472:     return $Key;
                    473: }
                    474: #
                    475: #     InsecureConnection: 
                    476: #        If insecure connections are allowd,
                    477: #        exchange a challenge with the client to 'validate' the
                    478: #        client (not really, but that's the protocol):
                    479: #        We produce a challenge string that's sent to the client.
                    480: #        The client must then echo the challenge verbatim to us.
                    481: #
                    482: #  Parameter:
                    483: #      Socket      - Socket open on the client.
                    484: #  Returns:
                    485: #      1           - success.
                    486: #      0           - failure (e.g.mismatch or insecure not allowed).
                    487: #
                    488: sub InsecureConnection {
                    489:     my $Socket  =  shift;
                    490: 
                    491:     #   Don't even start if insecure connections are not allowed.
1.532     raeburn   492:     #   return 0 if Insecure connections not allowed.
                    493:     #
                    494:     if (ref($secureconf{'connfrom'}) eq 'HASH') {
                    495:         if ($clientsamedom) {
                    496:             if ($secureconf{'connfrom'}{'dom'} eq 'req') {
                    497:                 return 0;
                    498:             } 
                    499:         } elsif ($clientsameinst) {
                    500:             if ($secureconf{'connfrom'}{'intdom'} eq 'req') {
                    501:                 return 0;
                    502:             }
                    503:         } else {
                    504:             if ($secureconf{'connfrom'}{'other'} eq 'req') {
                    505:                 return 0;
                    506:             }
                    507:         }
                    508:     } elsif (!$perlvar{londAllowInsecure}) {
1.200     matthew   509: 	return 0;
                    510:     }
                    511: 
                    512:     #   Fabricate a challenge string and send it..
                    513: 
                    514:     my $challenge = "$$".time;	# pid + time.
                    515:     print $Socket "$challenge\n";
                    516:     &status("Waiting for challenge reply");
                    517: 
                    518:     my $answer = <$Socket>;
                    519:     $answer    =~s/\W//g;
                    520:     if($challenge eq $answer) {
                    521: 	return 1;
1.224     foxr      522:     } else {
1.200     matthew   523: 	logthis("<font color='blue'>WARNING client did not respond to challenge</font>");
                    524: 	&status("No challenge reqply");
                    525: 	return 0;
                    526:     }
                    527:     
                    528: 
                    529: }
1.251     foxr      530: #
                    531: #   Safely execute a command (as long as it's not a shel command and doesn
                    532: #   not require/rely on shell escapes.   The function operates by doing a
                    533: #   a pipe based fork and capturing stdout and stderr  from the pipe.
                    534: #
                    535: # Formal Parameters:
                    536: #     $line                    - A line of text to be executed as a command.
                    537: # Returns:
                    538: #     The output from that command.  If the output is multiline the caller
                    539: #     must know how to split up the output.
                    540: #
                    541: #
                    542: sub execute_command {
                    543:     my ($line)    = @_;
                    544:     my @words     = split(/\s/, $line);	# Bust the command up into words.
                    545:     my $output    = "";
                    546: 
                    547:     my $pid = open(CHILD, "-|");
                    548:     
                    549:     if($pid) {			# Parent process
                    550: 	Debug("In parent process for execute_command");
                    551: 	my @data = <CHILD>;	# Read the child's outupt...
                    552: 	close CHILD;
                    553: 	foreach my $output_line (@data) {
                    554: 	    Debug("Adding $output_line");
                    555: 	    $output .= $output_line; # Presumably has a \n on it.
                    556: 	}
                    557: 
                    558:     } else {			# Child process
                    559: 	close (STDERR);
                    560: 	open  (STDERR, ">&STDOUT");# Combine stderr, and stdout...
                    561: 	exec(@words);		# won't return.
                    562:     }
                    563:     return $output;
                    564: }
                    565: 
1.200     matthew   566: 
1.140     foxr      567: #   GetCertificate: Given a transaction that requires a certificate,
                    568: #   this function will extract the certificate from the transaction
                    569: #   request.  Note that at this point, the only concept of a certificate
                    570: #   is the hostname to which we are connected.
                    571: #
                    572: #   Parameter:
                    573: #      request   - The request sent by our client (this parameterization may
                    574: #                  need to change when we really use a certificate granting
                    575: #                  authority.
                    576: #
                    577: sub GetCertificate {
                    578:     my $request = shift;
                    579: 
                    580:     return $clientip;
                    581: }
1.161     foxr      582: 
1.178     foxr      583: #
                    584: #   Return true if client is a manager.
                    585: #
                    586: sub isManager {
                    587:     return (($ConnectionType eq "manager") || ($ConnectionType eq "both"));
                    588: }
                    589: #
                    590: #   Return tru if client can do client functions
                    591: #
                    592: sub isClient {
                    593:     return (($ConnectionType eq "client") || ($ConnectionType eq "both"));
                    594: }
1.161     foxr      595: 
                    596: 
1.156     foxr      597: #
                    598: #   ReadManagerTable: Reads in the current manager table. For now this is
                    599: #                     done on each manager authentication because:
                    600: #                     - These authentications are not frequent
                    601: #                     - This allows dynamic changes to the manager table
                    602: #                       without the need to signal to the lond.
                    603: #
                    604: sub ReadManagerTable {
                    605: 
1.412     foxr      606:     &Debug("Reading manager table");
1.156     foxr      607:     #   Clean out the old table first..
                    608: 
1.166     foxr      609:    foreach my $key (keys %managers) {
                    610:       delete $managers{$key};
                    611:    }
                    612: 
                    613:    my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
                    614:    if (!open (MANAGERS, $tablename)) {
1.473     raeburn   615:        my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
                    616:        if (&Apache::lonnet::is_LC_dns($hostname)) {
1.472     raeburn   617:            &logthis('<font color="red">No manager table.  Nobody can manage!!</font>');
                    618:        }
                    619:        return;
1.166     foxr      620:    }
                    621:    while(my $host = <MANAGERS>) {
                    622:       chomp($host);
                    623:       if ($host =~ "^#") {                  # Comment line.
                    624:          next;
                    625:       }
1.368     albertel  626:       if (!defined &Apache::lonnet::get_host_ip($host)) { # This is a non cluster member
1.161     foxr      627: 	    #  The entry is of the form:
                    628: 	    #    cluname:hostname
                    629: 	    #  cluname - A 'cluster hostname' is needed in order to negotiate
                    630: 	    #            the host key.
                    631: 	    #  hostname- The dns name of the host.
                    632: 	    #
1.166     foxr      633:           my($cluname, $dnsname) = split(/:/, $host);
                    634:           
                    635:           my $ip = gethostbyname($dnsname);
                    636:           if(defined($ip)) {                 # bad names don't deserve entry.
                    637:             my $hostip = inet_ntoa($ip);
                    638:             $managers{$hostip} = $cluname;
                    639:             logthis('<font color="green"> registering manager '.
                    640:                     "$dnsname as $cluname with $hostip </font>\n");
                    641:          }
                    642:       } else {
                    643:          logthis('<font color="green"> existing host'." $host</font>\n");
1.472     raeburn   644:          $managers{&Apache::lonnet::get_host_ip($host)} = $host;  # Use info from cluster tab if cluster memeber
1.166     foxr      645:       }
                    646:    }
1.156     foxr      647: }
1.140     foxr      648: 
                    649: #
                    650: #  ValidManager: Determines if a given certificate represents a valid manager.
                    651: #                in this primitive implementation, the 'certificate' is
                    652: #                just the connecting loncapa client name.  This is checked
                    653: #                against a valid client list in the configuration.
                    654: #
                    655: #                  
                    656: sub ValidManager {
                    657:     my $certificate = shift; 
                    658: 
1.163     foxr      659:     return isManager;
1.140     foxr      660: }
                    661: #
1.143     foxr      662: #  CopyFile:  Called as part of the process of installing a 
                    663: #             new configuration file.  This function copies an existing
                    664: #             file to a backup file.
                    665: # Parameters:
                    666: #     oldfile  - Name of the file to backup.
                    667: #     newfile  - Name of the backup file.
                    668: # Return:
                    669: #     0   - Failure (errno has failure reason).
                    670: #     1   - Success.
                    671: #
                    672: sub CopyFile {
1.192     foxr      673: 
                    674:     my ($oldfile, $newfile) = @_;
1.143     foxr      675: 
1.281     matthew   676:     if (! copy($oldfile,$newfile)) {
                    677:         return 0;
1.143     foxr      678:     }
1.281     matthew   679:     chmod(0660, $newfile);
                    680:     return 1;
1.143     foxr      681: }
1.157     foxr      682: #
                    683: #  Host files are passed out with externally visible host IPs.
                    684: #  If, for example, we are behind a fire-wall or NAT host, our 
                    685: #  internally visible IP may be different than the externally
                    686: #  visible IP.  Therefore, we always adjust the contents of the
                    687: #  host file so that the entry for ME is the IP that we believe
                    688: #  we have.  At present, this is defined as the entry that
                    689: #  DNS has for us.  If by some chance we are not able to get a
                    690: #  DNS translation for us, then we assume that the host.tab file
                    691: #  is correct.  
                    692: #    BUGBUGBUG - in the future, we really should see if we can
                    693: #       easily query the interface(s) instead.
                    694: # Parameter(s):
                    695: #     contents    - The contents of the host.tab to check.
                    696: # Returns:
                    697: #     newcontents - The adjusted contents.
                    698: #
                    699: #
                    700: sub AdjustHostContents {
                    701:     my $contents  = shift;
                    702:     my $adjusted;
                    703:     my $me        = $perlvar{'lonHostID'};
                    704: 
1.354     albertel  705:     foreach my $line (split(/\n/,$contents)) {
1.472     raeburn   706: 	if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/) ||
                    707:              ($line =~ /^\s*\^/))) {
1.157     foxr      708: 	    chomp($line);
                    709: 	    my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
                    710: 	    if ($id eq $me) {
1.354     albertel  711: 		my $ip = gethostbyname($name);
                    712: 		my $ipnew = inet_ntoa($ip);
                    713: 		$ip = $ipnew;
1.157     foxr      714: 		#  Reconstruct the host line and append to adjusted:
                    715: 		
1.354     albertel  716: 		my $newline = "$id:$domain:$role:$name:$ip";
                    717: 		if($maxcon ne "") { # Not all hosts have loncnew tuning params
                    718: 		    $newline .= ":$maxcon:$idleto:$mincon";
                    719: 		}
                    720: 		$adjusted .= $newline."\n";
1.157     foxr      721: 		
1.354     albertel  722: 	    } else {		# Not me, pass unmodified.
                    723: 		$adjusted .= $line."\n";
                    724: 	    }
1.157     foxr      725: 	} else {                  # Blank or comment never re-written.
                    726: 	    $adjusted .= $line."\n";	# Pass blanks and comments as is.
                    727: 	}
1.354     albertel  728:     }
                    729:     return $adjusted;
1.157     foxr      730: }
1.143     foxr      731: #
                    732: #   InstallFile: Called to install an administrative file:
1.412     foxr      733: #       - The file is created int a temp directory called <name>.tmp
                    734: #       - lcinstall file is called to install the file.
                    735: #         since the web app has no direct write access to the table directory
1.143     foxr      736: #
                    737: #  Parameters:
                    738: #       Name of the file
                    739: #       File Contents.
                    740: #  Return:
                    741: #      nonzero - success.
                    742: #      0       - failure and $! has an errno.
1.412     foxr      743: # Assumptions:
                    744: #    File installtion is a relatively infrequent
1.143     foxr      745: #
                    746: sub InstallFile {
1.192     foxr      747: 
                    748:     my ($Filename, $Contents) = @_;
1.412     foxr      749: #     my $TempFile = $Filename.".tmp";
                    750:     my $exedir = $perlvar{'lonDaemons'};
                    751:     my $tmpdir = $exedir.'/tmp/';
                    752:     my $TempFile = $tmpdir."TempTableFile.tmp";
1.143     foxr      753: 
                    754:     #  Open the file for write:
                    755: 
                    756:     my $fh = IO::File->new("> $TempFile"); # Write to temp.
                    757:     if(!(defined $fh)) {
                    758: 	&logthis('<font color="red"> Unable to create '.$TempFile."</font>");
                    759: 	return 0;
                    760:     }
                    761:     #  write the contents of the file:
                    762: 
                    763:     print $fh ($Contents); 
                    764:     $fh->close;			# In case we ever have a filesystem w. locking
                    765: 
1.412     foxr      766:     chmod(0664, $TempFile);	# Everyone can write it.
                    767: 
                    768:     # Use lcinstall file to put the file in the table directory...
                    769: 
                    770:     &Debug("Opening pipe to $exedir/lcinstallfile $TempFile $Filename");
                    771:     my $pf = IO::File->new("| $exedir/lcinstallfile   $TempFile $Filename > $exedir/logs/lcinstallfile.log");
                    772:     close $pf;
                    773:     my $err = $?;
                    774:     &Debug("Status is $err");
                    775:     if ($err != 0) {
                    776: 	my $msg = $err;
                    777: 	if ($err < @installerrors) {
                    778: 	    $msg = $installerrors[$err];
                    779: 	}
                    780: 	&logthis("Install failed for table file $Filename : $msg");
                    781: 	return 0;
                    782:     }
                    783: 
                    784:     # Remove the temp file:
1.143     foxr      785: 
1.412     foxr      786:     unlink($TempFile);
1.143     foxr      787: 
                    788:     return 1;
                    789: }
1.200     matthew   790: 
                    791: 
1.169     foxr      792: #
                    793: #   ConfigFileFromSelector: converts a configuration file selector
1.411     foxr      794: #                 into a configuration file pathname.
1.472     raeburn   795: #                 Supports the following file selectors: 
                    796: #                 hosts, domain, dns_hosts, dns_domain  
1.411     foxr      797: #
1.169     foxr      798: #
                    799: #  Parameters:
                    800: #      selector  - Configuration file selector.
                    801: #  Returns:
                    802: #      Full path to the file or undef if the selector is invalid.
                    803: #
                    804: sub ConfigFileFromSelector {
                    805:     my $selector   = shift;
                    806:     my $tablefile;
                    807: 
1.549     raeburn   808:     if ($selector eq 'loncapaCAcrl') {
                    809:         my $tabledir = $perlvar{'lonCertificateDirectory'};
                    810:         if (-d $tabledir) {
                    811:             $tablefile =  $tabledir.'/'.$selector.'.pem';
                    812:         }
                    813:     } else {
                    814:         my $tabledir = $perlvar{'lonTabDir'}.'/';
                    815:         if (($selector eq "hosts") || ($selector eq "domain") || 
                    816:             ($selector eq "dns_hosts") || ($selector eq "dns_domain")) {
                    817: 	    $tablefile =  $tabledir.$selector.'.tab';
                    818:         }
1.169     foxr      819:     }
                    820:     return $tablefile;
                    821: }
1.143     foxr      822: #
1.141     foxr      823: #   PushFile:  Called to do an administrative push of a file.
                    824: #              - Ensure the file being pushed is one we support.
                    825: #              - Backup the old file to <filename.saved>
                    826: #              - Separate the contents of the new file out from the
                    827: #                rest of the request.
                    828: #              - Write the new file.
                    829: #  Parameter:
                    830: #     Request - The entire user request.  This consists of a : separated
                    831: #               string pushfile:tablename:contents.
                    832: #     NOTE:  The contents may have :'s in it as well making things a bit
                    833: #            more interesting... but not much.
                    834: #  Returns:
                    835: #     String to send to client ("ok" or "refused" if bad file).
                    836: #
                    837: sub PushFile {
1.510     raeburn   838:     my $request = shift;
1.141     foxr      839:     my ($command, $filename, $contents) = split(":", $request, 3);
1.412     foxr      840:     &Debug("PushFile");
1.141     foxr      841:     
1.549     raeburn   842:     #  At this point in time, pushes for only the following tables and
                    843:     #  CRL file are supported:
1.141     foxr      844:     #   hosts.tab  ($filename eq host).
                    845:     #   domain.tab ($filename eq domain).
1.472     raeburn   846:     #   dns_hosts.tab ($filename eq dns_host).
1.554     raeburn   847:     #   dns_domain.tab ($filename eq dns_domain).
                    848:     #   loncapaCAcrl.pem ($filename eq loncapaCAcrl).
1.141     foxr      849:     # Construct the destination filename or reject the request.
                    850:     #
                    851:     # lonManage is supposed to ensure this, however this session could be
                    852:     # part of some elaborate spoof that managed somehow to authenticate.
                    853:     #
                    854: 
1.169     foxr      855: 
                    856:     my $tablefile = ConfigFileFromSelector($filename);
                    857:     if(! (defined $tablefile)) {
1.141     foxr      858: 	return "refused";
                    859:     }
1.412     foxr      860: 
1.157     foxr      861:     #  If the file being pushed is the host file, we adjust the entry for ourself so that the
                    862:     #  IP will be our current IP as looked up in dns.  Note this is only 99% good as it's possible
                    863:     #  to conceive of conditions where we don't have a DNS entry locally.  This is possible in a 
                    864:     #  network sense but it doesn't make much sense in a LonCAPA sense so we ignore (for now)
                    865:     #  that possibilty.
                    866: 
                    867:     if($filename eq "host") {
                    868: 	$contents = AdjustHostContents($contents);
1.576     raeburn   869:     } elsif (($filename eq 'dns_hosts') || ($filename eq 'dns_domain') ||
1.549     raeburn   870:              ($filename eq 'loncapaCAcrl')) {
1.510     raeburn   871:         if ($contents eq '') {
                    872:             &logthis('<font color="red"> Pushfile: unable to install '
                    873:                     .$tablefile." - no data received from push. </font>");
                    874:             return 'error: push had no data';
                    875:         }
                    876:         if (&Apache::lonnet::get_host_ip($clientname)) {
                    877:             my $clienthost = &Apache::lonnet::hostname($clientname);
                    878:             if ($managers{$clientip} eq $clientname) {
                    879:                 my $clientprotocol = $Apache::lonnet::protocol{$clientname};
                    880:                 $clientprotocol = 'http' if ($clientprotocol ne 'https');
1.549     raeburn   881:                 my $url;
                    882:                 if ($filename eq 'loncapaCAcrl') {
                    883:                     $url = '/adm/dns/loncapaCRL';
                    884:                 } else {
                    885:                     $url = '/adm/'.$filename;
                    886:                     $url =~ s{_}{/};
                    887:                 }
1.510     raeburn   888:                 my $request=new HTTP::Request('GET',"$clientprotocol://$clienthost$url");
1.523     raeburn   889:                 my $response = LONCAPA::LWPReq::makerequest($clientname,$request,'',\%perlvar,60,0);
1.510     raeburn   890:                 if ($response->is_error()) {
                    891:                     &logthis('<font color="red"> Pushfile: unable to install '
                    892:                             .$tablefile." - error attempting to pull data. </font>");
                    893:                     return 'error: pull failed';
                    894:                 } else {
                    895:                     my $result = $response->content;
                    896:                     chomp($result);
                    897:                     unless ($result eq $contents) {
                    898:                         &logthis('<font color="red"> Pushfile: unable to install '
                    899:                                 .$tablefile." - pushed data and pulled data differ. </font>");
                    900:                         my $pushleng = length($contents);
                    901:                         my $pullleng = length($result);
                    902:                         if ($pushleng != $pullleng) {
                    903:                             return "error: $pushleng vs $pullleng bytes";
                    904:                         } else {
                    905:                             return "error: mismatch push and pull";
                    906:                         }
                    907:                     }
                    908:                 }
                    909:             }
                    910:         }
1.157     foxr      911:     }
                    912: 
1.141     foxr      913:     #  Install the new file:
                    914: 
1.412     foxr      915:     &logthis("Installing new $tablefile contents:\n$contents");
1.143     foxr      916:     if(!InstallFile($tablefile, $contents)) {
                    917: 	&logthis('<font color="red"> Pushfile: unable to install '
1.145     foxr      918: 	 .$tablefile." $! </font>");
1.143     foxr      919: 	return "error:$!";
1.224     foxr      920:     } else {
1.143     foxr      921: 	&logthis('<font color="green"> Installed new '.$tablefile
1.473     raeburn   922: 		 ." - transaction by: $clientname ($clientip)</font>");
1.472     raeburn   923:         my $adminmail = $perlvar{'lonAdmEMail'};
                    924:         my $admindom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                    925:         if ($admindom ne '') {
                    926:             my %domconfig =
                    927:                 &Apache::lonnet::get_dom('configuration',['contacts'],$admindom);
                    928:             if (ref($domconfig{'contacts'}) eq 'HASH') {
                    929:                 if ($domconfig{'contacts'}{'adminemail'} ne '') {
                    930:                     $adminmail = $domconfig{'contacts'}{'adminemail'};
                    931:                 }
                    932:             }
                    933:         }
                    934:         if ($adminmail =~ /^[^\@]+\@[^\@]+$/) {
                    935:             my $msg = new Mail::Send;
                    936:             $msg->to($adminmail);
                    937:             $msg->subject('LON-CAPA DNS update on '.$perlvar{'lonHostID'});
                    938:             $msg->add('Content-type','text/plain; charset=UTF-8');
                    939:             if (my $fh = $msg->open()) {
                    940:                 print $fh 'Update to '.$tablefile.' from Cluster Manager '.
1.473     raeburn   941:                           "$clientname ($clientip)\n";
1.472     raeburn   942:                 $fh->close;
                    943:             }
                    944:         }
1.143     foxr      945:     }
                    946: 
1.141     foxr      947:     #  Indicate success:
                    948:  
                    949:     return "ok";
                    950: 
                    951: }
1.145     foxr      952: 
                    953: #
                    954: #  Called to re-init either lonc or lond.
                    955: #
                    956: #  Parameters:
                    957: #    request   - The full request by the client.  This is of the form
                    958: #                reinit:<process>  
                    959: #                where <process> is allowed to be either of 
                    960: #                lonc or lond
                    961: #
                    962: #  Returns:
                    963: #     The string to be sent back to the client either:
                    964: #   ok         - Everything worked just fine.
                    965: #   error:why  - There was a failure and why describes the reason.
                    966: #
                    967: #
                    968: sub ReinitProcess {
                    969:     my $request = shift;
                    970: 
1.146     foxr      971: 
                    972:     # separate the request (reinit) from the process identifier and
                    973:     # validate it producing the name of the .pid file for the process.
                    974:     #
                    975:     #
                    976:     my ($junk, $process) = split(":", $request);
1.147     foxr      977:     my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
1.146     foxr      978:     if($process eq 'lonc') {
                    979: 	$processpidfile = $processpidfile."lonc.pid";
1.147     foxr      980: 	if (!open(PIDFILE, "< $processpidfile")) {
                    981: 	    return "error:Open failed for $processpidfile";
                    982: 	}
                    983: 	my $loncpid = <PIDFILE>;
                    984: 	close(PIDFILE);
                    985: 	logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
                    986: 		."</font>");
                    987: 	kill("USR2", $loncpid);
1.146     foxr      988:     } elsif ($process eq 'lond') {
1.147     foxr      989: 	logthis('<font color="red"> Reinitializing self (lond) </font>');
                    990: 	&UpdateHosts;			# Lond is us!!
1.146     foxr      991:     } else {
                    992: 	&logthis('<font color="yellow" Invalid reinit request for '.$process
                    993: 		 ."</font>");
                    994: 	return "error:Invalid process identifier $process";
                    995:     }
1.145     foxr      996:     return 'ok';
                    997: }
1.168     foxr      998: #   Validate a line in a configuration file edit script:
                    999: #   Validation includes:
                   1000: #     - Ensuring the command is valid.
                   1001: #     - Ensuring the command has sufficient parameters
                   1002: #   Parameters:
                   1003: #     scriptline - A line to validate (\n has been stripped for what it's worth).
1.167     foxr     1004: #
1.168     foxr     1005: #   Return:
                   1006: #      0     - Invalid scriptline.
                   1007: #      1     - Valid scriptline
                   1008: #  NOTE:
                   1009: #     Only the command syntax is checked, not the executability of the
                   1010: #     command.
                   1011: #
                   1012: sub isValidEditCommand {
                   1013:     my $scriptline = shift;
                   1014: 
                   1015:     #   Line elements are pipe separated:
                   1016: 
                   1017:     my ($command, $key, $newline)  = split(/\|/, $scriptline);
                   1018:     &logthis('<font color="green"> isValideditCommand checking: '.
                   1019: 	     "Command = '$command', Key = '$key', Newline = '$newline' </font>\n");
                   1020:     
                   1021:     if ($command eq "delete") {
                   1022: 	#
                   1023: 	#   key with no newline.
                   1024: 	#
                   1025: 	if( ($key eq "") || ($newline ne "")) {
                   1026: 	    return 0;		# Must have key but no newline.
                   1027: 	} else {
                   1028: 	    return 1;		# Valid syntax.
                   1029: 	}
1.169     foxr     1030:     } elsif ($command eq "replace") {
1.168     foxr     1031: 	#
                   1032: 	#   key and newline:
                   1033: 	#
                   1034: 	if (($key eq "") || ($newline eq "")) {
                   1035: 	    return 0;
                   1036: 	} else {
                   1037: 	    return 1;
                   1038: 	}
1.169     foxr     1039:     } elsif ($command eq "append") {
                   1040: 	if (($key ne "") && ($newline eq "")) {
                   1041: 	    return 1;
                   1042: 	} else {
                   1043: 	    return 0;
                   1044: 	}
1.168     foxr     1045:     } else {
                   1046: 	return 0;		# Invalid command.
                   1047:     }
                   1048:     return 0;			# Should not get here!!!
                   1049: }
1.169     foxr     1050: #
                   1051: #   ApplyEdit - Applies an edit command to a line in a configuration 
                   1052: #               file.  It is the caller's responsiblity to validate the
                   1053: #               edit line.
                   1054: #   Parameters:
                   1055: #      $directive - A single edit directive to apply.  
                   1056: #                   Edit directives are of the form:
                   1057: #                  append|newline      - Appends a new line to the file.
                   1058: #                  replace|key|newline - Replaces the line with key value 'key'
                   1059: #                  delete|key          - Deletes the line with key value 'key'.
                   1060: #      $editor   - A config file editor object that contains the
                   1061: #                  file being edited.
                   1062: #
                   1063: sub ApplyEdit {
1.192     foxr     1064: 
                   1065:     my ($directive, $editor) = @_;
1.169     foxr     1066: 
                   1067:     # Break the directive down into its command and its parameters
                   1068:     # (at most two at this point.  The meaning of the parameters, if in fact
                   1069:     #  they exist depends on the command).
                   1070: 
                   1071:     my ($command, $p1, $p2) = split(/\|/, $directive);
                   1072: 
                   1073:     if($command eq "append") {
                   1074: 	$editor->Append($p1);	          # p1 - key p2 null.
                   1075:     } elsif ($command eq "replace") {
                   1076: 	$editor->ReplaceLine($p1, $p2);   # p1 - key p2 = newline.
                   1077:     } elsif ($command eq "delete") {
                   1078: 	$editor->DeleteLine($p1);         # p1 - key p2 null.
                   1079:     } else {			          # Should not get here!!!
                   1080: 	die "Invalid command given to ApplyEdit $command"
                   1081:     }
                   1082: }
                   1083: #
                   1084: # AdjustOurHost:
                   1085: #           Adjusts a host file stored in a configuration file editor object
                   1086: #           for the true IP address of this host. This is necessary for hosts
                   1087: #           that live behind a firewall.
                   1088: #           Those hosts have a publicly distributed IP of the firewall, but
                   1089: #           internally must use their actual IP.  We assume that a given
                   1090: #           host only has a single IP interface for now.
                   1091: # Formal Parameters:
                   1092: #     editor   - The configuration file editor to adjust.  This
                   1093: #                editor is assumed to contain a hosts.tab file.
                   1094: # Strategy:
                   1095: #    - Figure out our hostname.
                   1096: #    - Lookup the entry for this host.
                   1097: #    - Modify the line to contain our IP
                   1098: #    - Do a replace for this host.
                   1099: sub AdjustOurHost {
                   1100:     my $editor        = shift;
                   1101: 
                   1102:     # figure out who I am.
                   1103: 
                   1104:     my $myHostName    = $perlvar{'lonHostID'}; # LonCAPA hostname.
                   1105: 
                   1106:     #  Get my host file entry.
                   1107: 
                   1108:     my $ConfigLine    = $editor->Find($myHostName);
                   1109:     if(! (defined $ConfigLine)) {
                   1110: 	die "AdjustOurHost - no entry for me in hosts file $myHostName";
                   1111:     }
                   1112:     # figure out my IP:
                   1113:     #   Use the config line to get my hostname.
                   1114:     #   Use gethostbyname to translate that into an IP address.
                   1115:     #
1.338     albertel 1116:     my ($id,$domain,$role,$name,$maxcon,$idleto,$mincon) = split(/:/,$ConfigLine);
1.169     foxr     1117:     #
                   1118:     #  Reassemble the config line from the elements in the list.
                   1119:     #  Note that if the loncnew items were not present before, they will
                   1120:     #  be now even if they would be empty
                   1121:     #
                   1122:     my $newConfigLine = $id;
1.338     albertel 1123:     foreach my $item ($domain, $role, $name, $maxcon, $idleto, $mincon) {
1.169     foxr     1124: 	$newConfigLine .= ":".$item;
                   1125:     }
                   1126:     #  Replace the line:
                   1127: 
                   1128:     $editor->ReplaceLine($id, $newConfigLine);
                   1129:     
                   1130: }
                   1131: #
                   1132: #   ReplaceConfigFile:
                   1133: #              Replaces a configuration file with the contents of a
                   1134: #              configuration file editor object.
                   1135: #              This is done by:
                   1136: #              - Copying the target file to <filename>.old
                   1137: #              - Writing the new file to <filename>.tmp
                   1138: #              - Moving <filename.tmp>  -> <filename>
                   1139: #              This laborious process ensures that the system is never without
                   1140: #              a configuration file that's at least valid (even if the contents
                   1141: #              may be dated).
                   1142: #   Parameters:
                   1143: #        filename   - Name of the file to modify... this is a full path.
                   1144: #        editor     - Editor containing the file.
                   1145: #
                   1146: sub ReplaceConfigFile {
1.192     foxr     1147:     
                   1148:     my ($filename, $editor) = @_;
1.168     foxr     1149: 
1.169     foxr     1150:     CopyFile ($filename, $filename.".old");
                   1151: 
                   1152:     my $contents  = $editor->Get(); # Get the contents of the file.
                   1153: 
                   1154:     InstallFile($filename, $contents);
                   1155: }
1.168     foxr     1156: #   
                   1157: #
                   1158: #   Called to edit a configuration table  file
1.167     foxr     1159: #   Parameters:
                   1160: #      request           - The entire command/request sent by lonc or lonManage
                   1161: #   Return:
                   1162: #      The reply to send to the client.
1.168     foxr     1163: #
1.167     foxr     1164: sub EditFile {
                   1165:     my $request = shift;
                   1166: 
                   1167:     #  Split the command into it's pieces:  edit:filetype:script
                   1168: 
1.339     albertel 1169:     my ($cmd, $filetype, $script) = split(/:/, $request,3);	# : in script
1.167     foxr     1170: 
                   1171:     #  Check the pre-coditions for success:
                   1172: 
1.339     albertel 1173:     if($cmd != "edit") {	# Something is amiss afoot alack.
1.167     foxr     1174: 	return "error:edit request detected, but request != 'edit'\n";
                   1175:     }
                   1176:     if( ($filetype ne "hosts")  &&
                   1177: 	($filetype ne "domain")) {
                   1178: 	return "error:edit requested with invalid file specifier: $filetype \n";
                   1179:     }
                   1180: 
                   1181:     #   Split the edit script and check it's validity.
1.168     foxr     1182: 
                   1183:     my @scriptlines = split(/\n/, $script);  # one line per element.
                   1184:     my $linecount   = scalar(@scriptlines);
                   1185:     for(my $i = 0; $i < $linecount; $i++) {
                   1186: 	chomp($scriptlines[$i]);
                   1187: 	if(!isValidEditCommand($scriptlines[$i])) {
                   1188: 	    return "error:edit with bad script line: '$scriptlines[$i]' \n";
                   1189: 	}
                   1190:     }
1.145     foxr     1191: 
1.167     foxr     1192:     #   Execute the edit operation.
1.169     foxr     1193:     #   - Create a config file editor for the appropriate file and 
                   1194:     #   - execute each command in the script:
                   1195:     #
                   1196:     my $configfile = ConfigFileFromSelector($filetype);
                   1197:     if (!(defined $configfile)) {
                   1198: 	return "refused\n";
                   1199:     }
                   1200:     my $editor = ConfigFileEdit->new($configfile);
1.167     foxr     1201: 
1.169     foxr     1202:     for (my $i = 0; $i < $linecount; $i++) {
                   1203: 	ApplyEdit($scriptlines[$i], $editor);
                   1204:     }
                   1205:     # If the file is the host file, ensure that our host is
                   1206:     # adjusted to have our ip:
                   1207:     #
                   1208:     if($filetype eq "host") {
                   1209: 	AdjustOurHost($editor);
                   1210:     }
                   1211:     #  Finally replace the current file with our file.
                   1212:     #
                   1213:     ReplaceConfigFile($configfile, $editor);
1.167     foxr     1214: 
                   1215:     return "ok\n";
                   1216: }
1.207     foxr     1217: 
1.255     foxr     1218: #   read_profile
                   1219: #
                   1220: #   Returns a set of specific entries from a user's profile file.
                   1221: #   this is a utility function that is used by both get_profile_entry and
                   1222: #   get_profile_entry_encrypted.
                   1223: #
                   1224: # Parameters:
                   1225: #    udom       - Domain in which the user exists.
                   1226: #    uname      - User's account name (loncapa account)
                   1227: #    namespace  - The profile namespace to open.
                   1228: #    what       - A set of & separated queries.
                   1229: # Returns:
                   1230: #    If all ok: - The string that needs to be shipped back to the user.
                   1231: #    If failure - A string that starts with error: followed by the failure
                   1232: #                 reason.. note that this probabyl gets shipped back to the
                   1233: #                 user as well.
                   1234: #
                   1235: sub read_profile {
                   1236:     my ($udom, $uname, $namespace, $what) = @_;
                   1237:     
                   1238:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   1239: 				 &GDBM_READER());
                   1240:     if ($hashref) {
                   1241:         my @queries=split(/\&/,$what);
1.440     raeburn  1242:         if ($namespace eq 'roles') {
                   1243:             @queries = map { &unescape($_); } @queries; 
                   1244:         }
1.255     foxr     1245:         my $qresult='';
                   1246: 	
                   1247: 	for (my $i=0;$i<=$#queries;$i++) {
                   1248: 	    $qresult.="$hashref->{$queries[$i]}&";    # Presumably failure gives empty string.
                   1249: 	}
                   1250: 	$qresult=~s/\&$//;              # Remove trailing & from last lookup.
1.311     albertel 1251: 	if (&untie_user_hash($hashref)) {
1.255     foxr     1252: 	    return $qresult;
                   1253: 	} else {
                   1254: 	    return "error: ".($!+0)." untie (GDBM) Failed";
                   1255: 	}
                   1256:     } else {
                   1257: 	if ($!+0 == 2) {
                   1258: 	    return "error:No such file or GDBM reported bad block error";
                   1259: 	} else {
                   1260: 	    return "error: ".($!+0)." tie (GDBM) Failed";
                   1261: 	}
                   1262:     }
                   1263: 
                   1264: }
1.214     foxr     1265: #--------------------- Request Handlers --------------------------------------------
                   1266: #
1.215     foxr     1267: #   By convention each request handler registers itself prior to the sub 
                   1268: #   declaration:
1.214     foxr     1269: #
                   1270: 
1.216     foxr     1271: #++
                   1272: #
1.214     foxr     1273: #  Handles ping requests.
                   1274: #  Parameters:
                   1275: #      $cmd    - the actual keyword that invoked us.
                   1276: #      $tail   - the tail of the request that invoked us.
                   1277: #      $replyfd- File descriptor connected to the client
                   1278: #  Implicit Inputs:
                   1279: #      $currenthostid - Global variable that carries the name of the host we are
                   1280: #                       known as.
                   1281: #  Returns:
                   1282: #      1       - Ok to continue processing.
                   1283: #      0       - Program should exit.
                   1284: #  Side effects:
                   1285: #      Reply information is sent to the client.
                   1286: sub ping_handler {
                   1287:     my ($cmd, $tail, $client) = @_;
                   1288:     Debug("$cmd $tail $client .. $currenthostid:");
                   1289:    
1.387     albertel 1290:     Reply( $client,\$currenthostid,"$cmd:$tail");
1.214     foxr     1291:    
                   1292:     return 1;
                   1293: }
                   1294: &register_handler("ping", \&ping_handler, 0, 1, 1);       # Ping unencoded, client or manager.
                   1295: 
1.216     foxr     1296: #++
1.215     foxr     1297: #
                   1298: # Handles pong requests.  Pong replies with our current host id, and
                   1299: #                         the results of a ping sent to us via our lonc.
                   1300: #
                   1301: # Parameters:
                   1302: #      $cmd    - the actual keyword that invoked us.
                   1303: #      $tail   - the tail of the request that invoked us.
                   1304: #      $replyfd- File descriptor connected to the client
                   1305: #  Implicit Inputs:
                   1306: #      $currenthostid - Global variable that carries the name of the host we are
                   1307: #                       connected to.
                   1308: #  Returns:
                   1309: #      1       - Ok to continue processing.
                   1310: #      0       - Program should exit.
                   1311: #  Side effects:
                   1312: #      Reply information is sent to the client.
                   1313: sub pong_handler {
                   1314:     my ($cmd, $tail, $replyfd) = @_;
                   1315: 
1.365     albertel 1316:     my $reply=&Apache::lonnet::reply("ping",$clientname);
1.215     foxr     1317:     &Reply( $replyfd, "$currenthostid:$reply\n", "$cmd:$tail"); 
                   1318:     return 1;
                   1319: }
                   1320: &register_handler("pong", \&pong_handler, 0, 1, 1);       # Pong unencoded, client or manager
                   1321: 
1.216     foxr     1322: #++
                   1323: #      Called to establish an encrypted session key with the remote client.
                   1324: #      Note that with secure lond, in most cases this function is never
                   1325: #      invoked.  Instead, the secure session key is established either
                   1326: #      via a local file that's locked down tight and only lives for a short
                   1327: #      time, or via an ssl tunnel...and is generated from a bunch-o-random
                   1328: #      bits from /dev/urandom, rather than the predictable pattern used by
                   1329: #      by this sub.  This sub is only used in the old-style insecure
                   1330: #      key negotiation.
                   1331: # Parameters:
                   1332: #      $cmd    - the actual keyword that invoked us.
                   1333: #      $tail   - the tail of the request that invoked us.
                   1334: #      $replyfd- File descriptor connected to the client
                   1335: #  Implicit Inputs:
                   1336: #      $currenthostid - Global variable that carries the name of the host
                   1337: #                       known as.
1.448     raeburn  1338: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.216     foxr     1339: #  Returns:
                   1340: #      1       - Ok to continue processing.
                   1341: #      0       - Program should exit.
                   1342: #  Implicit Outputs:
                   1343: #      Reply information is sent to the client.
                   1344: #      $cipher is set with a reference to a new IDEA encryption object.
                   1345: #
                   1346: sub establish_key_handler {
                   1347:     my ($cmd, $tail, $replyfd) = @_;
                   1348: 
                   1349:     my $buildkey=time.$$.int(rand 100000);
                   1350:     $buildkey=~tr/1-6/A-F/;
                   1351:     $buildkey=int(rand 100000).$buildkey.int(rand 100000);
                   1352:     my $key=$currenthostid.$clientname;
                   1353:     $key=~tr/a-z/A-Z/;
                   1354:     $key=~tr/G-P/0-9/;
                   1355:     $key=~tr/Q-Z/0-9/;
                   1356:     $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
                   1357:     $key=substr($key,0,32);
                   1358:     my $cipherkey=pack("H32",$key);
                   1359:     $cipher=new IDEA $cipherkey;
1.387     albertel 1360:     &Reply($replyfd, \$buildkey, "$cmd:$tail"); 
1.216     foxr     1361:    
                   1362:     return 1;
                   1363: 
                   1364: }
                   1365: &register_handler("ekey", \&establish_key_handler, 0, 1,1);
                   1366: 
1.217     foxr     1367: #     Handler for the load command.  Returns the current system load average
                   1368: #     to the requestor.
                   1369: #
                   1370: # Parameters:
                   1371: #      $cmd    - the actual keyword that invoked us.
                   1372: #      $tail   - the tail of the request that invoked us.
                   1373: #      $replyfd- File descriptor connected to the client
                   1374: #  Implicit Inputs:
                   1375: #      $currenthostid - Global variable that carries the name of the host
                   1376: #                       known as.
1.448     raeburn  1377: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.217     foxr     1378: #  Returns:
                   1379: #      1       - Ok to continue processing.
                   1380: #      0       - Program should exit.
                   1381: #  Side effects:
                   1382: #      Reply information is sent to the client.
                   1383: sub load_handler {
                   1384:     my ($cmd, $tail, $replyfd) = @_;
                   1385: 
1.463     foxr     1386: 
                   1387: 
1.217     foxr     1388:    # Get the load average from /proc/loadavg and calculate it as a percentage of
                   1389:    # the allowed load limit as set by the perl global variable lonLoadLim
                   1390: 
                   1391:     my $loadavg;
                   1392:     my $loadfile=IO::File->new('/proc/loadavg');
                   1393:    
                   1394:     $loadavg=<$loadfile>;
                   1395:     $loadavg =~ s/\s.*//g;                      # Extract the first field only.
                   1396:    
                   1397:     my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
                   1398: 
1.387     albertel 1399:     &Reply( $replyfd, \$loadpercent, "$cmd:$tail");
1.217     foxr     1400:    
                   1401:     return 1;
                   1402: }
1.263     albertel 1403: &register_handler("load", \&load_handler, 0, 1, 0);
1.217     foxr     1404: 
                   1405: #
                   1406: #   Process the userload request.  This sub returns to the client the current
                   1407: #  user load average.  It can be invoked either by clients or managers.
                   1408: #
                   1409: # Parameters:
                   1410: #      $cmd    - the actual keyword that invoked us.
                   1411: #      $tail   - the tail of the request that invoked us.
                   1412: #      $replyfd- File descriptor connected to the client
                   1413: #  Implicit Inputs:
                   1414: #      $currenthostid - Global variable that carries the name of the host
                   1415: #                       known as.
1.448     raeburn  1416: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.217     foxr     1417: #  Returns:
                   1418: #      1       - Ok to continue processing.
                   1419: #      0       - Program should exit
                   1420: # Implicit inputs:
                   1421: #     whatever the userload() function requires.
                   1422: #  Implicit outputs:
                   1423: #     the reply is written to the client.
                   1424: #
                   1425: sub user_load_handler {
                   1426:     my ($cmd, $tail, $replyfd) = @_;
                   1427: 
1.365     albertel 1428:     my $userloadpercent=&Apache::lonnet::userload();
1.387     albertel 1429:     &Reply($replyfd, \$userloadpercent, "$cmd:$tail");
1.217     foxr     1430:     
                   1431:     return 1;
                   1432: }
1.263     albertel 1433: &register_handler("userload", \&user_load_handler, 0, 1, 0);
1.217     foxr     1434: 
1.218     foxr     1435: #   Process a request for the authorization type of a user:
                   1436: #   (userauth).
                   1437: #
                   1438: # Parameters:
                   1439: #      $cmd    - the actual keyword that invoked us.
                   1440: #      $tail   - the tail of the request that invoked us.
                   1441: #      $replyfd- File descriptor connected to the client
                   1442: #  Returns:
                   1443: #      1       - Ok to continue processing.
                   1444: #      0       - Program should exit
                   1445: # Implicit outputs:
                   1446: #    The user authorization type is written to the client.
                   1447: #
                   1448: sub user_authorization_type {
                   1449:     my ($cmd, $tail, $replyfd) = @_;
                   1450:    
                   1451:     my $userinput = "$cmd:$tail";
                   1452:    
                   1453:     #  Pull the domain and username out of the command tail.
1.222     foxr     1454:     # and call get_auth_type to determine the authentication type.
1.218     foxr     1455:    
                   1456:     my ($udom,$uname)=split(/:/,$tail);
1.222     foxr     1457:     my $result = &get_auth_type($udom, $uname);
1.218     foxr     1458:     if($result eq "nouser") {
                   1459: 	&Failure( $replyfd, "unknown_user\n", $userinput);
                   1460:     } else {
                   1461: 	#
1.222     foxr     1462: 	# We only want to pass the second field from get_auth_type
1.218     foxr     1463: 	# for ^krb.. otherwise we'll be handing out the encrypted
                   1464: 	# password for internals e.g.
                   1465: 	#
                   1466: 	my ($type,$otherinfo) = split(/:/,$result);
                   1467: 	if($type =~ /^krb/) {
                   1468: 	    $type = $result;
1.269     raeburn  1469: 	} else {
                   1470:             $type .= ':';
                   1471:         }
1.387     albertel 1472: 	&Reply( $replyfd, \$type, $userinput);
1.218     foxr     1473:     }
                   1474:   
                   1475:     return 1;
                   1476: }
                   1477: &register_handler("currentauth", \&user_authorization_type, 1, 1, 0);
                   1478: 
                   1479: #   Process a request by a manager to push a hosts or domain table 
                   1480: #   to us.  We pick apart the command and pass it on to the subs
                   1481: #   that already exist to do this.
                   1482: #
                   1483: # Parameters:
                   1484: #      $cmd    - the actual keyword that invoked us.
                   1485: #      $tail   - the tail of the request that invoked us.
                   1486: #      $client - File descriptor connected to the client
                   1487: #  Returns:
                   1488: #      1       - Ok to continue processing.
                   1489: #      0       - Program should exit
                   1490: # Implicit Output:
                   1491: #    a reply is written to the client.
                   1492: sub push_file_handler {
                   1493:     my ($cmd, $tail, $client) = @_;
1.412     foxr     1494:     &Debug("In push file handler");
1.218     foxr     1495:     my $userinput = "$cmd:$tail";
                   1496: 
                   1497:     # At this time we only know that the IP of our partner is a valid manager
                   1498:     # the code below is a hook to do further authentication (e.g. to resolve
                   1499:     # spoofing).
                   1500: 
                   1501:     my $cert = &GetCertificate($userinput);
1.412     foxr     1502:     if(&ValidManager($cert)) {
                   1503: 	&Debug("Valid manager: $client");
1.218     foxr     1504: 
                   1505: 	# Now presumably we have the bona fides of both the peer host and the
                   1506: 	# process making the request.
                   1507:       
                   1508: 	my $reply = &PushFile($userinput);
1.387     albertel 1509: 	&Reply($client, \$reply, $userinput);
1.218     foxr     1510: 
                   1511:     } else {
1.412     foxr     1512: 	&logthis("push_file_handler $client is not valid");
1.218     foxr     1513: 	&Failure( $client, "refused\n", $userinput);
                   1514:     } 
1.219     foxr     1515:     return 1;
1.218     foxr     1516: }
                   1517: &register_handler("pushfile", \&push_file_handler, 1, 0, 1);
                   1518: 
1.399     raeburn  1519: # The du_handler routine should be considered obsolete and is retained
                   1520: # for communication with legacy servers.  Please see the du2_handler.
1.243     banghart 1521: #
1.399     raeburn  1522: #   du  - list the disk usage of a directory recursively. 
1.243     banghart 1523: #    
                   1524: #   note: stolen code from the ls file handler
                   1525: #   under construction by Rick Banghart 
                   1526: #    .
                   1527: # Parameters:
                   1528: #    $cmd        - The command that dispatched us (du).
                   1529: #    $ududir     - The directory path to list... I'm not sure what this
                   1530: #                  is relative as things like ls:. return e.g.
                   1531: #                  no_such_dir.
                   1532: #    $client     - Socket open on the client.
                   1533: # Returns:
                   1534: #     1 - indicating that the daemon should not disconnect.
                   1535: # Side Effects:
                   1536: #   The reply is written to  $client.
                   1537: #
                   1538: sub du_handler {
                   1539:     my ($cmd, $ududir, $client) = @_;
1.339     albertel 1540:     ($ududir) = split(/:/,$ududir); # Make 'telnet' testing easier.
1.251     foxr     1541:     my $userinput = "$cmd:$ududir";
                   1542: 
1.245     albertel 1543:     if ($ududir=~/\.\./ || $ududir!~m|^/home/httpd/|) {
                   1544: 	&Failure($client,"refused\n","$cmd:$ududir");
                   1545: 	return 1;
                   1546:     }
1.249     foxr     1547:     #  Since $ududir could have some nasties in it,
                   1548:     #  we will require that ududir is a valid
                   1549:     #  directory.  Just in case someone tries to
                   1550:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
                   1551:     #  etc.
                   1552:     #
                   1553:     if (-d $ududir) {
1.292     albertel 1554: 	my $total_size=0;
                   1555: 	my $code=sub { 
                   1556: 	    if ($_=~/\.\d+\./) { return;} 
                   1557: 	    if ($_=~/\.meta$/) { return;}
1.362     albertel 1558: 	    if (-d $_)         { return;}
1.292     albertel 1559: 	    $total_size+=(stat($_))[7];
                   1560: 	};
1.295     raeburn  1561: 	chdir($ududir);
1.292     albertel 1562: 	find($code,$ududir);
                   1563: 	$total_size=int($total_size/1024);
1.387     albertel 1564: 	&Reply($client,\$total_size,"$cmd:$ududir");
1.249     foxr     1565:     } else {
1.251     foxr     1566: 	&Failure($client, "bad_directory:$ududir\n","$cmd:$ududir"); 
1.249     foxr     1567:     }
1.243     banghart 1568:     return 1;
                   1569: }
                   1570: &register_handler("du", \&du_handler, 0, 1, 0);
1.218     foxr     1571: 
1.399     raeburn  1572: # Please also see the du_handler, which is obsoleted by du2. 
                   1573: # du2_handler differs from du_handler in that required path to directory
                   1574: # provided by &propath() is prepended in the handler instead of on the 
                   1575: # client side.
1.239     foxr     1576: #
1.399     raeburn  1577: #   du2  - list the disk usage of a directory recursively.
                   1578: #
                   1579: # Parameters:
                   1580: #    $cmd        - The command that dispatched us (du).
                   1581: #    $tail       - The tail of the request that invoked us.
                   1582: #                  $tail is a : separated list of the following:
                   1583: #                   - $ududir - directory path to list (before prepending)
                   1584: #                   - $getpropath = 1 if &propath() should prepend
                   1585: #                   - $uname - username to use for &propath or user dir
                   1586: #                   - $udom - domain to use for &propath or user dir
                   1587: #                   All are escaped.
                   1588: #    $client     - Socket open on the client.
                   1589: # Returns:
                   1590: #     1 - indicating that the daemon should not disconnect.
                   1591: # Side Effects:
                   1592: #   The reply is written to $client.
                   1593: #
                   1594: 
                   1595: sub du2_handler {
                   1596:     my ($cmd, $tail, $client) = @_;
                   1597:     my ($ududir,$getpropath,$uname,$udom) = map { &unescape($_) } (split(/:/, $tail));
                   1598:     my $userinput = "$cmd:$tail";
                   1599:     if (($ududir=~/\.\./) || (($ududir!~m|^/home/httpd/|) && (!$getpropath))) {
                   1600:         &Failure($client,"refused\n","$cmd:$tail");
                   1601:         return 1;
                   1602:     }
                   1603:     if ($getpropath) {
                   1604:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
                   1605:             $ududir = &propath($udom,$uname).'/'.$ududir;
                   1606:         } else {
                   1607:             &Failure($client,"refused\n","$cmd:$tail");
                   1608:             return 1;
                   1609:         }
                   1610:     }
                   1611:     #  Since $ududir could have some nasties in it,
                   1612:     #  we will require that ududir is a valid
                   1613:     #  directory.  Just in case someone tries to
                   1614:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
                   1615:     #  etc.
                   1616:     #
                   1617:     if (-d $ududir) {
                   1618:         my $total_size=0;
                   1619:         my $code=sub {
                   1620:             if ($_=~/\.\d+\./) { return;}
                   1621:             if ($_=~/\.meta$/) { return;}
                   1622:             if (-d $_)         { return;}
                   1623:             $total_size+=(stat($_))[7];
                   1624:         };
                   1625:         chdir($ududir);
                   1626:         find($code,$ududir);
                   1627:         $total_size=int($total_size/1024);
                   1628:         &Reply($client,\$total_size,"$cmd:$ududir");
                   1629:     } else {
                   1630:         &Failure($client, "bad_directory:$ududir\n","$cmd:$tail");
                   1631:     }
                   1632:     return 1;
                   1633: }
                   1634: &register_handler("du2", \&du2_handler, 0, 1, 0);
                   1635: 
                   1636: #
                   1637: # The ls_handler routine should be considered obsolete and is retained
                   1638: # for communication with legacy servers.  Please see the ls3_handler.
1.280     matthew  1639: #
1.239     foxr     1640: #   ls  - list the contents of a directory.  For each file in the
                   1641: #    selected directory the filename followed by the full output of
                   1642: #    the stat function is returned.  The returned info for each
                   1643: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1644: #
                   1645: #    If the requested path contains /../ or is:
                   1646: #
                   1647: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1648: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1649: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1650: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
                   1651: #    or is:
                   1652: #
1.538     raeburn  1653: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1654: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1655: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1656: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
1.529     raeburn  1657: #
                   1658: #    the response will be "refused".
                   1659: #
1.239     foxr     1660: # Parameters:
                   1661: #    $cmd        - The command that dispatched us (ls).
                   1662: #    $ulsdir     - The directory path to list... I'm not sure what this
                   1663: #                  is relative as things like ls:. return e.g.
                   1664: #                  no_such_dir.
                   1665: #    $client     - Socket open on the client.
                   1666: # Returns:
                   1667: #     1 - indicating that the daemon should not disconnect.
                   1668: # Side Effects:
                   1669: #   The reply is written to  $client.
                   1670: #
                   1671: sub ls_handler {
1.280     matthew  1672:     # obsoleted by ls2_handler
1.239     foxr     1673:     my ($cmd, $ulsdir, $client) = @_;
                   1674: 
                   1675:     my $userinput = "$cmd:$ulsdir";
                   1676: 
                   1677:     my $obs;
                   1678:     my $rights;
                   1679:     my $ulsout='';
                   1680:     my $ulsfn;
1.529     raeburn  1681:     if ($ulsdir =~m{/\.\./}) {
                   1682:         &Failure($client,"refused\n",$userinput);
                   1683:         return 1;
                   1684:     }
1.239     foxr     1685:     if (-e $ulsdir) {
                   1686: 	if(-d $ulsdir) {
1.539     raeburn  1687:             unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1688:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
1.529     raeburn  1689:                 &Failure($client,"refused\n",$userinput);
                   1690:                 return 1;
                   1691:             }
1.239     foxr     1692: 	    if (opendir(LSDIR,$ulsdir)) {
                   1693: 		while ($ulsfn=readdir(LSDIR)) {
1.291     albertel 1694: 		    undef($obs);
                   1695: 		    undef($rights); 
1.239     foxr     1696: 		    my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1697: 		    #We do some obsolete checking here
                   1698: 		    if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   1699: 			open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1700: 			my @obsolete=<FILE>;
                   1701: 			foreach my $obsolete (@obsolete) {
1.301     www      1702: 			    if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
1.239     foxr     1703: 			    if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
                   1704: 			}
                   1705: 		    }
                   1706: 		    $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
                   1707: 		    if($obs eq '1') { $ulsout.="&1"; }
                   1708: 		    else { $ulsout.="&0"; }
                   1709: 		    if($rights eq '1') { $ulsout.="&1:"; }
                   1710: 		    else { $ulsout.="&0:"; }
                   1711: 		}
                   1712: 		closedir(LSDIR);
                   1713: 	    }
                   1714: 	} else {
1.539     raeburn  1715:             unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1716:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
1.529     raeburn  1717:                 &Failure($client,"refused\n",$userinput);
                   1718:                 return 1;
                   1719:             }
1.239     foxr     1720: 	    my @ulsstats=stat($ulsdir);
                   1721: 	    $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1722: 	}
                   1723:     } else {
                   1724: 	$ulsout='no_such_dir';
                   1725:     }
                   1726:     if ($ulsout eq '') { $ulsout='empty'; }
1.387     albertel 1727:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1.239     foxr     1728:     
                   1729:     return 1;
                   1730: 
                   1731: }
                   1732: &register_handler("ls", \&ls_handler, 0, 1, 0);
                   1733: 
1.399     raeburn  1734: # The ls2_handler routine should be considered obsolete and is retained
                   1735: # for communication with legacy servers.  Please see the ls3_handler.
                   1736: # Please also see the ls_handler, which was itself obsoleted by ls2.
1.280     matthew  1737: # ls2_handler differs from ls_handler in that it escapes its return 
                   1738: # values before concatenating them together with ':'s.
                   1739: #
                   1740: #   ls2  - list the contents of a directory.  For each file in the
                   1741: #    selected directory the filename followed by the full output of
                   1742: #    the stat function is returned.  The returned info for each
                   1743: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1744: #
                   1745: #    If the requested path contains /../ or is:
                   1746: #
                   1747: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1748: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1749: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1750: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
                   1751: #    or is:
                   1752: #
1.538     raeburn  1753: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1754: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1755: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1756: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
1.529     raeburn  1757: #
                   1758: #    the response will be "refused".
                   1759: #
1.280     matthew  1760: # Parameters:
                   1761: #    $cmd        - The command that dispatched us (ls).
                   1762: #    $ulsdir     - The directory path to list... I'm not sure what this
                   1763: #                  is relative as things like ls:. return e.g.
                   1764: #                  no_such_dir.
                   1765: #    $client     - Socket open on the client.
                   1766: # Returns:
                   1767: #     1 - indicating that the daemon should not disconnect.
                   1768: # Side Effects:
                   1769: #   The reply is written to  $client.
                   1770: #
                   1771: sub ls2_handler {
                   1772:     my ($cmd, $ulsdir, $client) = @_;
                   1773: 
                   1774:     my $userinput = "$cmd:$ulsdir";
                   1775: 
                   1776:     my $obs;
                   1777:     my $rights;
                   1778:     my $ulsout='';
                   1779:     my $ulsfn;
1.529     raeburn  1780:     if ($ulsdir =~m{/\.\./}) {
                   1781:         &Failure($client,"refused\n",$userinput);
                   1782:         return 1;
                   1783:     }
1.280     matthew  1784:     if (-e $ulsdir) {
                   1785:         if(-d $ulsdir) {
1.539     raeburn  1786:             unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1787:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
1.529     raeburn  1788:                 &Failure($client,"refused\n","$userinput");
                   1789:                 return 1;
                   1790:             }
1.280     matthew  1791:             if (opendir(LSDIR,$ulsdir)) {
                   1792:                 while ($ulsfn=readdir(LSDIR)) {
1.291     albertel 1793:                     undef($obs);
                   1794: 		    undef($rights); 
1.280     matthew  1795:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1796:                     #We do some obsolete checking here
                   1797:                     if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   1798:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1799:                         my @obsolete=<FILE>;
                   1800:                         foreach my $obsolete (@obsolete) {
1.301     www      1801:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
1.280     matthew  1802:                             if($obsolete =~ m|(<copyright>)(default)|) {
                   1803:                                 $rights = 1;
                   1804:                             }
                   1805:                         }
                   1806:                     }
                   1807:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
                   1808:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1809:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1810:                     $ulsout.= &escape($tmp).':';
                   1811:                 }
                   1812:                 closedir(LSDIR);
                   1813:             }
                   1814:         } else {
1.539     raeburn  1815:             unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1816:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
1.529     raeburn  1817:                 &Failure($client,"refused\n",$userinput);
                   1818:                 return 1;
                   1819:             }
1.280     matthew  1820:             my @ulsstats=stat($ulsdir);
                   1821:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1822:         }
                   1823:     } else {
                   1824:         $ulsout='no_such_dir';
                   1825:    }
                   1826:    if ($ulsout eq '') { $ulsout='empty'; }
1.387     albertel 1827:    &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1.280     matthew  1828:    return 1;
                   1829: }
                   1830: &register_handler("ls2", \&ls2_handler, 0, 1, 0);
1.399     raeburn  1831: #
                   1832: #   ls3  - list the contents of a directory.  For each file in the
                   1833: #    selected directory the filename followed by the full output of
                   1834: #    the stat function is returned.  The returned info for each
                   1835: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1836: #
                   1837: #    If the requested path (after prepending) contains /../ or is:
                   1838: #
                   1839: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1840: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1841: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1842: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
1.539     raeburn  1843: #        (d) /home/httpd/html/priv/<domain> and client is the homeserver
1.529     raeburn  1844: #
1.530     raeburn  1845: #    or is:
1.529     raeburn  1846: #
1.538     raeburn  1847: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1848: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1849: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1850: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
                   1851: #        (d) /home/httpd/html/priv/<domain>/<username>/ and client is the homeserver
1.529     raeburn  1852: #
                   1853: #    the response will be "refused".
                   1854: #
1.399     raeburn  1855: # Parameters:
                   1856: #    $cmd        - The command that dispatched us (ls).
                   1857: #    $tail       - The tail of the request that invoked us.
                   1858: #                  $tail is a : separated list of the following:
                   1859: #                   - $ulsdir - directory path to list (before prepending)
                   1860: #                   - $getpropath = 1 if &propath() should prepend
                   1861: #                   - $getuserdir = 1 if path to user dir in lonUsers should
                   1862: #                                     prepend
                   1863: #                   - $alternate_root - path to prepend
                   1864: #                   - $uname - username to use for &propath or user dir
                   1865: #                   - $udom - domain to use for &propath or user dir
                   1866: #            All of these except $getpropath and &getuserdir are escaped.    
                   1867: #                  no_such_dir.
                   1868: #    $client     - Socket open on the client.
                   1869: # Returns:
                   1870: #     1 - indicating that the daemon should not disconnect.
                   1871: # Side Effects:
                   1872: #   The reply is written to $client.
                   1873: #
                   1874: 
                   1875: sub ls3_handler {
                   1876:     my ($cmd, $tail, $client) = @_;
                   1877:     my $userinput = "$cmd:$tail";
                   1878:     my ($ulsdir,$getpropath,$getuserdir,$alternate_root,$uname,$udom) =
                   1879:         split(/:/,$tail);
                   1880:     if (defined($ulsdir)) {
                   1881:         $ulsdir = &unescape($ulsdir);
                   1882:     }
                   1883:     if (defined($alternate_root)) {
                   1884:         $alternate_root = &unescape($alternate_root);
                   1885:     }
                   1886:     if (defined($uname)) {
                   1887:         $uname = &unescape($uname);
                   1888:     }
                   1889:     if (defined($udom)) {
                   1890:         $udom = &unescape($udom);
                   1891:     }
                   1892: 
                   1893:     my $dir_root = $perlvar{'lonDocRoot'};
1.529     raeburn  1894:     if (($getpropath) || ($getuserdir)) {
1.399     raeburn  1895:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
                   1896:             $dir_root = &propath($udom,$uname);
                   1897:             $dir_root =~ s/\/$//;
                   1898:         } else {
1.529     raeburn  1899:             &Failure($client,"refused\n",$userinput);
1.399     raeburn  1900:             return 1;
                   1901:         }
1.400     raeburn  1902:     } elsif ($alternate_root ne '') {
1.399     raeburn  1903:         $dir_root = $alternate_root;
                   1904:     }
1.408     raeburn  1905:     if (($dir_root ne '') && ($dir_root ne '/')) {
1.400     raeburn  1906:         if ($ulsdir =~ /^\//) {
                   1907:             $ulsdir = $dir_root.$ulsdir;
                   1908:         } else {
                   1909:             $ulsdir = $dir_root.'/'.$ulsdir;
                   1910:         }
1.399     raeburn  1911:     }
1.529     raeburn  1912:     if ($ulsdir =~m{/\.\./}) {
                   1913:         &Failure($client,"refused\n",$userinput);
                   1914:         return 1;
                   1915:     }
                   1916:     my $islocal;
                   1917:     my @machine_ids = &Apache::lonnet::current_machine_ids();
                   1918:     if (grep(/^\Q$clientname\E$/,@machine_ids)) {
                   1919:         $islocal = 1;
                   1920:     }
1.399     raeburn  1921:     my $obs;
                   1922:     my $rights;
                   1923:     my $ulsout='';
                   1924:     my $ulsfn;
1.547     raeburn  1925: 
                   1926:     my ($crscheck,$toplevel,$currdom,$currnum,$skip);
                   1927:     unless ($islocal) {
                   1928:         my ($major,$minor) = split(/\./,$clientversion);
                   1929:         if (($major < 2) || ($major == 2 && $minor < 12)) {
                   1930:             $crscheck = 1;
                   1931:         }
                   1932:     }
1.399     raeburn  1933:     if (-e $ulsdir) {
                   1934:         if(-d $ulsdir) {
1.529     raeburn  1935:             unless (($getpropath) || ($getuserdir) ||
1.539     raeburn  1936:                     ($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1937:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles}) ||
                   1938:                     (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain}) && ($islocal))) {
1.529     raeburn  1939:                 &Failure($client,"refused\n",$userinput);
                   1940:                 return 1;
                   1941:             }
1.547     raeburn  1942:             if (($crscheck) &&
                   1943:                 ($ulsdir =~ m{^/home/httpd/html/res/($LONCAPA::match_domain)(/?$|/$LONCAPA::match_courseid)})) {
                   1944:                 ($currdom,my $posscnum) = ($1,$2);
                   1945:                 if (($posscnum eq '') || ($posscnum eq '/')) {
                   1946:                     $toplevel = 1;
                   1947:                 } else {
                   1948:                     $posscnum =~ s{^/+}{};
                   1949:                     if (&LONCAPA::Lond::is_course($currdom,$posscnum)) {
                   1950:                         $skip = 1;
                   1951:                     }
                   1952:                 }
                   1953:             }
                   1954:             if ((!$skip) && (opendir(LSDIR,$ulsdir))) {
1.399     raeburn  1955:                 while ($ulsfn=readdir(LSDIR)) {
1.547     raeburn  1956:                     if (($crscheck) && ($toplevel) && ($currdom ne '') &&
                   1957:                         ($ulsfn =~ /^$LONCAPA::match_courseid$/) && (-d "$ulsdir/$ulsfn")) {
                   1958:                         if (&LONCAPA::Lond::is_course($currdom,$ulsfn)) {
                   1959:                             next;
                   1960:                         }
                   1961:                     }
1.399     raeburn  1962:                     undef($obs);
                   1963:                     undef($rights);
                   1964:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1965:                     #We do some obsolete checking here
                   1966:                     if(-e $ulsdir.'/'.$ulsfn.".meta") {
                   1967:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1968:                         my @obsolete=<FILE>;
                   1969:                         foreach my $obsolete (@obsolete) {
                   1970:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; }
                   1971:                             if($obsolete =~ m|(<copyright>)(default)|) {
                   1972:                                 $rights = 1;
                   1973:                             }
                   1974:                         }
                   1975:                     }
                   1976:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
                   1977:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1978:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1979:                     $ulsout.= &escape($tmp).':';
                   1980:                 }
                   1981:                 closedir(LSDIR);
                   1982:             }
                   1983:         } else {
1.529     raeburn  1984:             unless (($getpropath) || ($getuserdir) ||
1.539     raeburn  1985:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1986:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/}) ||
                   1987:                     (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain/$LONCAPA::match_name/}) && ($islocal))) {
1.529     raeburn  1988:                 &Failure($client,"refused\n",$userinput);
                   1989:                 return 1;
                   1990:             }
1.399     raeburn  1991:             my @ulsstats=stat($ulsdir);
                   1992:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1993:         }
                   1994:     } else {
                   1995:         $ulsout='no_such_dir';
1.400     raeburn  1996:     }
                   1997:     if ($ulsout eq '') { $ulsout='empty'; }
                   1998:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
                   1999:     return 1;
1.399     raeburn  2000: }
                   2001: &register_handler("ls3", \&ls3_handler, 0, 1, 0);
1.280     matthew  2002: 
1.477     raeburn  2003: sub read_lonnet_global {
                   2004:     my ($cmd,$tail,$client) = @_;
                   2005:     my $userinput = "$cmd:$tail";
                   2006:     my $requested = &Apache::lonnet::thaw_unescape($tail);
                   2007:     my $result;
1.480     raeburn  2008:     my %packagevars = (
                   2009:                         spareid => \%Apache::lonnet::spareid,
                   2010:                         perlvar => \%Apache::lonnet::perlvar,
                   2011:                       );
                   2012:     my %limit_to = (
                   2013:                     perlvar => {
1.531     raeburn  2014:                                  lonOtherAuthen  => 1,
                   2015:                                  lonBalancer     => 1,
                   2016:                                  lonVersion      => 1,
                   2017:                                  lonAdmEMail     => 1,
                   2018:                                  lonSupportEMail => 1,  
                   2019:                                  lonSysEMail     => 1,
                   2020:                                  lonHostID       => 1,
                   2021:                                  lonRole         => 1,
                   2022:                                  lonDefDomain    => 1,
                   2023:                                  lonLoadLim      => 1,
                   2024:                                  lonUserLoadLim  => 1,
1.480     raeburn  2025:                                }
                   2026:                   );
1.477     raeburn  2027:     if (ref($requested) eq 'HASH') {
                   2028:         foreach my $what (keys(%{$requested})) {
                   2029:             my $response;
1.480     raeburn  2030:             my $items = {};
                   2031:             if (exists($packagevars{$what})) {
                   2032:                 if (ref($limit_to{$what}) eq 'HASH') {
                   2033:                     foreach my $varname (keys(%{$packagevars{$what}})) {
                   2034:                         if ($limit_to{$what}{$varname}) {
                   2035:                             $items->{$varname} = $packagevars{$what}{$varname};
                   2036:                         }
                   2037:                     }
                   2038:                 } else {
                   2039:                     $items = $packagevars{$what};
1.477     raeburn  2040:                 }
1.480     raeburn  2041:                 if ($what eq 'perlvar') {
                   2042:                     if (!exists($packagevars{$what}{'lonBalancer'})) {
1.570     raeburn  2043:                         if ($dist =~ /^(centos|rhes|fedora|scientific|oracle|rocky|alma)/) {
1.480     raeburn  2044:                             my $othervarref=LONCAPA::Configuration::read_conf('httpd.conf');
                   2045:                             if (ref($othervarref) eq 'HASH') {
                   2046:                                 $items->{'lonBalancer'} = $othervarref->{'lonBalancer'};
                   2047:                             }
                   2048:                         }
                   2049:                     }
1.477     raeburn  2050:                 }
1.480     raeburn  2051:                 $response = &Apache::lonnet::freeze_escape($items);
1.477     raeburn  2052:             }
1.478     raeburn  2053:             $result .= &escape($what).'='.$response.'&';
1.477     raeburn  2054:         }
                   2055:     }
                   2056:     $result =~ s/\&$//;
                   2057:     &Reply($client,\$result,$userinput);
                   2058:     return 1;
                   2059: }
                   2060: &register_handler("readlonnetglobal", \&read_lonnet_global, 0, 1, 0);
                   2061: 
1.479     raeburn  2062: sub server_devalidatecache_handler {
                   2063:     my ($cmd,$tail,$client) = @_;
                   2064:     my $userinput = "$cmd:$tail";
1.503     raeburn  2065:     my $items = &unescape($tail);
                   2066:     my @cached = split(/\&/,$items);
                   2067:     foreach my $key (@cached) {
                   2068:         if ($key =~ /:/) {
                   2069:             my ($name,$id) = map { &unescape($_); } split(/:/,$key);
                   2070:             &Apache::lonnet::devalidate_cache_new($name,$id);
                   2071:         }
                   2072:     }
1.479     raeburn  2073:     my $result = 'ok';
                   2074:     &Reply($client,\$result,$userinput);
                   2075:     return 1;
                   2076: }
1.481     raeburn  2077: &register_handler("devalidatecache", \&server_devalidatecache_handler, 0, 1, 0);
1.479     raeburn  2078: 
1.410     raeburn  2079: sub server_timezone_handler {
                   2080:     my ($cmd,$tail,$client) = @_;
                   2081:     my $userinput = "$cmd:$tail";
                   2082:     my $timezone;
                   2083:     my $clockfile = '/etc/sysconfig/clock'; # Fedora/CentOS/SuSE
                   2084:     my $tzfile = '/etc/timezone'; # Debian/Ubuntu
                   2085:     if (-e $clockfile) {
                   2086:         if (open(my $fh,"<$clockfile")) {
                   2087:             while (<$fh>) {
                   2088:                 next if (/^[\#\s]/);
                   2089:                 if (/^(?:TIME)?ZONE\s*=\s*['"]?\s*([\w\/]+)/) {
                   2090:                     $timezone = $1;
                   2091:                     last;
                   2092:                 }
                   2093:             }
                   2094:             close($fh);
                   2095:         }
                   2096:     } elsif (-e $tzfile) {
                   2097:         if (open(my $fh,"<$tzfile")) {
                   2098:             $timezone = <$fh>;
                   2099:             close($fh);
                   2100:             chomp($timezone);
                   2101:             if ($timezone =~ m{^Etc/(\w+)$}) {
                   2102:                 $timezone = $1;
                   2103:             }
                   2104:         }
                   2105:     }
                   2106:     &Reply($client,\$timezone,$userinput); # This supports debug logging.
                   2107:     return 1;
                   2108: }
                   2109: &register_handler("servertimezone", \&server_timezone_handler, 0, 1, 0);
                   2110: 
1.413     raeburn  2111: sub server_loncaparev_handler {
                   2112:     my ($cmd,$tail,$client) = @_;
                   2113:     my $userinput = "$cmd:$tail";
                   2114:     &Reply($client,\$perlvar{'lonVersion'},$userinput);
                   2115:     return 1;
                   2116: }
                   2117: &register_handler("serverloncaparev", \&server_loncaparev_handler, 0, 1, 0);
                   2118: 
1.448     raeburn  2119: sub server_homeID_handler {
                   2120:     my ($cmd,$tail,$client) = @_;
                   2121:     my $userinput = "$cmd:$tail";
                   2122:     &Reply($client,\$perlvar{'lonHostID'},$userinput);
                   2123:     return 1;
                   2124: }
                   2125: &register_handler("serverhomeID", \&server_homeID_handler, 0, 1, 0);
                   2126: 
1.471     raeburn  2127: sub server_distarch_handler {
                   2128:     my ($cmd,$tail,$client) = @_;
                   2129:     my $userinput = "$cmd:$tail";
                   2130:     my $reply = &distro_and_arch();
                   2131:     &Reply($client,\$reply,$userinput);
                   2132:     return 1;
                   2133: }
                   2134: &register_handler("serverdistarch", \&server_distarch_handler, 0, 1, 0);
                   2135: 
1.523     raeburn  2136: sub server_certs_handler {
                   2137:     my ($cmd,$tail,$client) = @_;
                   2138:     my $userinput = "$cmd:$tail";
1.548     raeburn  2139:     my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
                   2140:     my $result = &LONCAPA::Lond::server_certs(\%perlvar,$perlvar{'lonHostID'},$hostname);
1.523     raeburn  2141:     &Reply($client,\$result,$userinput);
                   2142:     return;
                   2143: }
                   2144: &register_handler("servercerts", \&server_certs_handler, 0, 1, 0);
                   2145: 
1.218     foxr     2146: #   Process a reinit request.  Reinit requests that either
                   2147: #   lonc or lond be reinitialized so that an updated 
                   2148: #   host.tab or domain.tab can be processed.
                   2149: #
                   2150: # Parameters:
                   2151: #      $cmd    - the actual keyword that invoked us.
                   2152: #      $tail   - the tail of the request that invoked us.
                   2153: #      $client - File descriptor connected to the client
                   2154: #  Returns:
                   2155: #      1       - Ok to continue processing.
                   2156: #      0       - Program should exit
                   2157: #  Implicit output:
                   2158: #     a reply is sent to the client.
                   2159: #
                   2160: sub reinit_process_handler {
                   2161:     my ($cmd, $tail, $client) = @_;
                   2162:    
                   2163:     my $userinput = "$cmd:$tail";
                   2164:    
                   2165:     my $cert = &GetCertificate($userinput);
                   2166:     if(&ValidManager($cert)) {
                   2167: 	chomp($userinput);
                   2168: 	my $reply = &ReinitProcess($userinput);
1.387     albertel 2169: 	&Reply( $client,  \$reply, $userinput);
1.218     foxr     2170:     } else {
                   2171: 	&Failure( $client, "refused\n", $userinput);
                   2172:     }
                   2173:     return 1;
                   2174: }
                   2175: &register_handler("reinit", \&reinit_process_handler, 1, 0, 1);
                   2176: 
                   2177: #  Process the editing script for a table edit operation.
                   2178: #  the editing operation must be encrypted and requested by
                   2179: #  a manager host.
                   2180: #
                   2181: # Parameters:
                   2182: #      $cmd    - the actual keyword that invoked us.
                   2183: #      $tail   - the tail of the request that invoked us.
                   2184: #      $client - File descriptor connected to the client
                   2185: #  Returns:
                   2186: #      1       - Ok to continue processing.
                   2187: #      0       - Program should exit
                   2188: #  Implicit output:
                   2189: #     a reply is sent to the client.
                   2190: #
                   2191: sub edit_table_handler {
                   2192:     my ($command, $tail, $client) = @_;
                   2193:    
                   2194:     my $userinput = "$command:$tail";
                   2195: 
                   2196:     my $cert = &GetCertificate($userinput);
                   2197:     if(&ValidManager($cert)) {
                   2198: 	my($filetype, $script) = split(/:/, $tail);
                   2199: 	if (($filetype eq "hosts") || 
                   2200: 	    ($filetype eq "domain")) {
                   2201: 	    if($script ne "") {
                   2202: 		&Reply($client,              # BUGBUG - EditFile
                   2203: 		      &EditFile($userinput), #   could fail.
                   2204: 		      $userinput);
                   2205: 	    } else {
                   2206: 		&Failure($client,"refused\n",$userinput);
                   2207: 	    }
                   2208: 	} else {
                   2209: 	    &Failure($client,"refused\n",$userinput);
                   2210: 	}
                   2211:     } else {
                   2212: 	&Failure($client,"refused\n",$userinput);
                   2213:     }
                   2214:     return 1;
                   2215: }
1.263     albertel 2216: &register_handler("edit", \&edit_table_handler, 1, 0, 1);
1.218     foxr     2217: 
1.220     foxr     2218: #
                   2219: #   Authenticate a user against the LonCAPA authentication
                   2220: #   database.  Note that there are several authentication
                   2221: #   possibilities:
                   2222: #   - unix     - The user can be authenticated against the unix
                   2223: #                password file.
                   2224: #   - internal - The user can be authenticated against a purely 
                   2225: #                internal per user password file.
                   2226: #   - kerberos - The user can be authenticated against either a kerb4 or kerb5
                   2227: #                ticket granting authority.
                   2228: #   - user     - The person tailoring LonCAPA can supply a user authentication
                   2229: #                mechanism that is per system.
                   2230: #
                   2231: # Parameters:
                   2232: #    $cmd      - The command that got us here.
                   2233: #    $tail     - Tail of the command (remaining parameters).
                   2234: #    $client   - File descriptor connected to client.
                   2235: # Returns
                   2236: #     0        - Requested to exit, caller should shut down.
                   2237: #     1        - Continue processing.
                   2238: # Implicit inputs:
                   2239: #    The authentication systems describe above have their own forms of implicit
                   2240: #    input into the authentication process that are described above.
                   2241: #
                   2242: sub authenticate_handler {
                   2243:     my ($cmd, $tail, $client) = @_;
                   2244: 
                   2245:     
                   2246:     #  Regenerate the full input line 
                   2247:     
                   2248:     my $userinput  = $cmd.":".$tail;
                   2249:     
                   2250:     #  udom    - User's domain.
                   2251:     #  uname   - Username.
                   2252:     #  upass   - User's password.
1.396     raeburn  2253:     #  checkdefauth - Pass to validate_user() to try authentication
                   2254:     #                 with default auth type(s) if no user account.
1.447     raeburn  2255:     #  clientcancheckhost - Passed by clients with functionality in lonauth.pm
                   2256:     #                       to check if session can be hosted.
1.220     foxr     2257:     
1.447     raeburn  2258:     my ($udom, $uname, $upass, $checkdefauth, $clientcancheckhost)=split(/:/,$tail);
1.399     raeburn  2259:     &Debug(" Authenticate domain = $udom, user = $uname, password = $upass,  checkdefauth = $checkdefauth");
1.220     foxr     2260:     chomp($upass);
                   2261:     $upass=&unescape($upass);
                   2262: 
1.396     raeburn  2263:     my $pwdcorrect = &validate_user($udom,$uname,$upass,$checkdefauth);
1.220     foxr     2264:     if($pwdcorrect) {
1.447     raeburn  2265:         my $canhost = 1;
                   2266:         unless ($clientcancheckhost) {
1.448     raeburn  2267:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   2268:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.452     raeburn  2269:             my @intdoms;
                   2270:             my $internet_names = &Apache::lonnet::get_internet_names($clientname);
                   2271:             if (ref($internet_names) eq 'ARRAY') {
                   2272:                 @intdoms = @{$internet_names};
                   2273:             }
1.448     raeburn  2274:             unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
1.447     raeburn  2275:                 my ($remote,$hosted);
                   2276:                 my $remotesession = &get_usersession_config($udom,'remotesession');
                   2277:                 if (ref($remotesession) eq 'HASH') {
1.525     raeburn  2278:                     $remote = $remotesession->{'remote'};
1.447     raeburn  2279:                 }
1.448     raeburn  2280:                 my $hostedsession = &get_usersession_config($clienthomedom,'hostedsession');
1.447     raeburn  2281:                 if (ref($hostedsession) eq 'HASH') {
                   2282:                     $hosted = $hostedsession->{'hosted'};
                   2283:                 }
1.448     raeburn  2284:                 $canhost = &Apache::lonnet::can_host_session($udom,$clientname,
1.492     droeschl 2285:                                                              $clientversion,
1.447     raeburn  2286:                                                              $remote,$hosted);
                   2287:             }
                   2288:         }
                   2289:         if ($canhost) {               
                   2290:             &Reply( $client, "authorized\n", $userinput);
                   2291:         } else {
                   2292:             &Reply( $client, "not_allowed_to_host\n", $userinput);
                   2293:         }
1.220     foxr     2294: 	#
                   2295: 	#  Bad credentials: Failed to authorize
                   2296: 	#
                   2297:     } else {
                   2298: 	&Failure( $client, "non_authorized\n", $userinput);
                   2299:     }
                   2300: 
                   2301:     return 1;
                   2302: }
1.263     albertel 2303: &register_handler("auth", \&authenticate_handler, 1, 1, 0);
1.214     foxr     2304: 
1.222     foxr     2305: #
                   2306: #   Change a user's password.  Note that this function is complicated by
                   2307: #   the fact that a user may be authenticated in more than one way:
                   2308: #   At present, we are not able to change the password for all types of
                   2309: #   authentication methods.  Only for:
                   2310: #      unix    - unix password or shadow passoword style authentication.
                   2311: #      local   - Locally written authentication mechanism.
                   2312: #   For now, kerb4 and kerb5 password changes are not supported and result
                   2313: #   in an error.
                   2314: # FUTURE WORK:
                   2315: #    Support kerberos passwd changes?
                   2316: # Parameters:
                   2317: #    $cmd      - The command that got us here.
                   2318: #    $tail     - Tail of the command (remaining parameters).
                   2319: #    $client   - File descriptor connected to client.
                   2320: # Returns
                   2321: #     0        - Requested to exit, caller should shut down.
                   2322: #     1        - Continue processing.
                   2323: # Implicit inputs:
                   2324: #    The authentication systems describe above have their own forms of implicit
                   2325: #    input into the authentication process that are described above.
                   2326: sub change_password_handler {
                   2327:     my ($cmd, $tail, $client) = @_;
                   2328: 
                   2329:     my $userinput = $cmd.":".$tail;           # Reconstruct client's string.
                   2330: 
                   2331:     #
                   2332:     #  udom  - user's domain.
                   2333:     #  uname - Username.
                   2334:     #  upass - Current password.
                   2335:     #  npass - New password.
1.346     raeburn  2336:     #  context - Context in which this was called 
                   2337:     #            (preferences or reset_by_email).
1.428     raeburn  2338:     #  lonhost - HostID of server where request originated 
1.222     foxr     2339:    
1.428     raeburn  2340:     my ($udom,$uname,$upass,$npass,$context,$lonhost)=split(/:/,$tail);
1.222     foxr     2341: 
                   2342:     $upass=&unescape($upass);
                   2343:     $npass=&unescape($npass);
                   2344:     &Debug("Trying to change password for $uname");
                   2345: 
                   2346:     # First require that the user can be authenticated with their
1.346     raeburn  2347:     # old password unless context was 'reset_by_email':
                   2348:     
1.428     raeburn  2349:     my ($validated,$failure);
1.346     raeburn  2350:     if ($context eq 'reset_by_email') {
1.428     raeburn  2351:         if ($lonhost eq '') {
                   2352:             $failure = 'invalid_client';
                   2353:         } else {
                   2354:             $validated = 1;
                   2355:         }
1.346     raeburn  2356:     } else {
                   2357:         $validated = &validate_user($udom, $uname, $upass);
                   2358:     }
1.222     foxr     2359:     if($validated) {
                   2360: 	my $realpasswd  = &get_auth_type($udom, $uname); # Defined since authd.
                   2361: 	my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
1.558     raeburn  2362:         my $notunique;
1.222     foxr     2363: 	if ($howpwd eq 'internal') {
                   2364: 	    &Debug("internal auth");
1.518     raeburn  2365:             my $ncpass = &hash_passwd($udom,$npass);
1.558     raeburn  2366:             my (undef,$method,@rest) = split(/!/,$contentpwd);
                   2367:             if ($method eq 'bcrypt') {
                   2368:                 my %passwdconf = &Apache::lonnet::get_passwdconf($udom);
                   2369:                 if (($passwdconf{'numsaved'}) && ($passwdconf{'numsaved'} =~ /^\d+$/)) {
                   2370:                     my @oldpasswds;
                   2371:                     my $userpath = &propath($udom,$uname);
                   2372:                     my $fullpath = $userpath.'/oldpasswds';
                   2373:                     if (-d $userpath) {
                   2374:                         my @oldfiles;
                   2375:                         if (-e $fullpath) {
                   2376:                             if (opendir(my $dir,$fullpath)) {
                   2377:                                 (@oldfiles) = grep(/^\d+$/,readdir($dir));
                   2378:                                 closedir($dir);
                   2379:                             }
                   2380:                             if (@oldfiles) {
                   2381:                                 @oldfiles = sort { $b <=> $a } (@oldfiles);
                   2382:                                 my $numremoved = 0;
                   2383:                                 for (my $i=0; $i<@oldfiles; $i++) {
                   2384:                                     if ($i>=$passwdconf{'numsaved'}) {
                   2385:                                         if (-f "$fullpath/$oldfiles[$i]") {
                   2386:                                             if (unlink("$fullpath/$oldfiles[$i]")) {
                   2387:                                                 $numremoved ++;
                   2388:                                             }
                   2389:                                         }
                   2390:                                     } elsif (open(my $fh,'<',"$fullpath/$oldfiles[$i]")) {
                   2391:                                         while (my $line = <$fh>) {
                   2392:                                             push(@oldpasswds,$line);
                   2393:                                         }
                   2394:                                         close($fh);
                   2395:                                     }
                   2396:                                 }
                   2397:                                 if ($numremoved) {
                   2398:                                     &logthis("unlinked $numremoved old password files for $uname:$udom");
                   2399:                                 }
                   2400:                             }
                   2401:                         }
                   2402:                         push(@oldpasswds,$contentpwd);
                   2403:                         foreach my $item (@oldpasswds) {
                   2404:                             my (undef,$method,@rest) = split(/!/,$item);
                   2405:                             if ($method eq 'bcrypt') {
                   2406:                                 my $result = &hash_passwd($udom,$npass,@rest);
                   2407:                                 if ($result eq $item) {
                   2408:                                     $notunique = 1;
                   2409:                                     last;
                   2410:                                 }
                   2411:                             }
                   2412:                         }
                   2413:                         unless ($notunique) {
                   2414:                             unless (-e $fullpath) {
                   2415:                                 if (&mkpath("$fullpath/")) {
                   2416:                                     chmod(0700,$fullpath);
                   2417:                                 }
                   2418:                             }
                   2419:                             if (-d $fullpath) {
                   2420:                                 my $now = time;
                   2421:                                 if (open(my $fh,'>',"$fullpath/$now")) {
                   2422:                                     print $fh $contentpwd;
                   2423:                                     close($fh);
                   2424:                                     chmod(0400,"$fullpath/$now");
                   2425:                                 }
                   2426:                             }
                   2427:                         }
                   2428:                     }
                   2429:                 }
                   2430:             }
                   2431:             if ($notunique) {
                   2432:                 my $msg="Result of password change for $uname:$udom - password matches one used before";
                   2433:                 if ($lonhost) {
                   2434:                     $msg .= " - request originated from: $lonhost";
                   2435:                 }
                   2436:                 &logthis($msg);
                   2437:                 &Reply($client, "prioruse\n", $userinput);
                   2438: 	    } elsif (&rewrite_password_file($udom, $uname, "internal:$ncpass")) {
1.428     raeburn  2439: 		my $msg="Result of password change for $uname: pwchange_success";
                   2440:                 if ($lonhost) {
                   2441:                     $msg .= " - request originated from: $lonhost";
                   2442:                 }
                   2443:                 &logthis($msg);
1.518     raeburn  2444:                 &update_passwd_history($uname,$udom,$howpwd,$context);
1.222     foxr     2445: 		&Reply($client, "ok\n", $userinput);
                   2446: 	    } else {
                   2447: 		&logthis("Unable to open $uname passwd "               
                   2448: 			 ."to change password");
                   2449: 		&Failure( $client, "non_authorized\n",$userinput);
                   2450: 	    }
1.346     raeburn  2451: 	} elsif ($howpwd eq 'unix' && $context ne 'reset_by_email') {
1.287     foxr     2452: 	    my $result = &change_unix_password($uname, $npass);
1.518     raeburn  2453:             if ($result eq 'ok') {
                   2454:                 &update_passwd_history($uname,$udom,$howpwd,$context);
1.561     raeburn  2455:             }
1.222     foxr     2456: 	    &logthis("Result of password change for $uname: ".
1.287     foxr     2457: 		     $result);
1.387     albertel 2458: 	    &Reply($client, \$result, $userinput);
1.222     foxr     2459: 	} else {
                   2460: 	    # this just means that the current password mode is not
                   2461: 	    # one we know how to change (e.g the kerberos auth modes or
                   2462: 	    # locally written auth handler).
                   2463: 	    #
                   2464: 	    &Failure( $client, "auth_mode_error\n", $userinput);
                   2465: 	}  
1.224     foxr     2466:     } else {
1.428     raeburn  2467: 	if ($failure eq '') {
                   2468: 	    $failure = 'non_authorized';
                   2469: 	}
                   2470: 	&Failure( $client, "$failure\n", $userinput);
1.222     foxr     2471:     }
                   2472: 
                   2473:     return 1;
                   2474: }
1.263     albertel 2475: &register_handler("passwd", \&change_password_handler, 1, 1, 0);
1.222     foxr     2476: 
1.518     raeburn  2477: sub hash_passwd {
                   2478:     my ($domain,$plainpass,@rest) = @_;
                   2479:     my ($salt,$cost);
                   2480:     if (@rest) {
                   2481:         $cost = $rest[0];
                   2482:         # salt is first 22 characters, base-64 encoded by bcrypt
                   2483:         my $plainsalt = substr($rest[1],0,22);
                   2484:         $salt = Crypt::Eksblowfish::Bcrypt::de_base64($plainsalt);
                   2485:     } else {
1.533     raeburn  2486:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   2487:         my $defaultcost = $domdefaults{'intauth_cost'};
1.518     raeburn  2488:         if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
                   2489:             $cost = 10;
                   2490:         } else {
                   2491:             $cost = $defaultcost;
                   2492:         }
                   2493:         # Generate random 16-octet base64 salt
                   2494:         $salt = "";
                   2495:         $salt .= pack("C", int rand(256)) for 1..16;
                   2496:     }
                   2497:     my $hash = &Crypt::Eksblowfish::Bcrypt::bcrypt_hash({
                   2498:         key_nul => 1,
                   2499:         cost    => $cost,
                   2500:         salt    => $salt,
                   2501:     }, Digest::SHA::sha512(Encode::encode('UTF-8',$plainpass)));
                   2502: 
                   2503:     my $result = join("!", "", "bcrypt", sprintf("%02d",$cost),
                   2504:                 &Crypt::Eksblowfish::Bcrypt::en_base64($salt).
                   2505:                 &Crypt::Eksblowfish::Bcrypt::en_base64($hash));
                   2506:     return $result;
                   2507: }
                   2508: 
1.225     foxr     2509: #
                   2510: #   Create a new user.  User in this case means a lon-capa user.
                   2511: #   The user must either already exist in some authentication realm
                   2512: #   like kerberos or the /etc/passwd.  If not, a user completely local to
                   2513: #   this loncapa system is created.
                   2514: #
                   2515: # Parameters:
                   2516: #    $cmd      - The command that got us here.
                   2517: #    $tail     - Tail of the command (remaining parameters).
                   2518: #    $client   - File descriptor connected to client.
                   2519: # Returns
                   2520: #     0        - Requested to exit, caller should shut down.
                   2521: #     1        - Continue processing.
                   2522: # Implicit inputs:
                   2523: #    The authentication systems describe above have their own forms of implicit
                   2524: #    input into the authentication process that are described above.
                   2525: sub add_user_handler {
                   2526: 
                   2527:     my ($cmd, $tail, $client) = @_;
                   2528: 
                   2529: 
                   2530:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   2531:     my $userinput = $cmd.":".$tail; # Reconstruct the full request line.
                   2532: 
                   2533:     &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
                   2534: 
                   2535: 
                   2536:     if($udom eq $currentdomainid) { # Reject new users for other domains...
                   2537: 	
                   2538: 	my $oldumask=umask(0077);
                   2539: 	chomp($npass);
                   2540: 	$npass=&unescape($npass);
                   2541: 	my $passfilename  = &password_path($udom, $uname);
                   2542: 	&Debug("Password file created will be:".$passfilename);
                   2543: 	if (-e $passfilename) {
                   2544: 	    &Failure( $client, "already_exists\n", $userinput);
                   2545: 	} else {
                   2546: 	    my $fperror='';
1.264     albertel 2547: 	    if (!&mkpath($passfilename)) {
                   2548: 		$fperror="error: ".($!+0)." mkdir failed while attempting "
                   2549: 		    ."makeuser";
1.225     foxr     2550: 	    }
                   2551: 	    unless ($fperror) {
1.518     raeburn  2552: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
                   2553:                                              $passfilename,'makeuser');
1.390     raeburn  2554: 		&Reply($client,\$result, $userinput);     #BUGBUG - could be fail
1.225     foxr     2555: 	    } else {
1.387     albertel 2556: 		&Failure($client, \$fperror, $userinput);
1.225     foxr     2557: 	    }
                   2558: 	}
                   2559: 	umask($oldumask);
                   2560:     }  else {
                   2561: 	&Failure($client, "not_right_domain\n",
                   2562: 		$userinput);	# Even if we are multihomed.
                   2563:     
                   2564:     }
                   2565:     return 1;
                   2566: 
                   2567: }
                   2568: &register_handler("makeuser", \&add_user_handler, 1, 1, 0);
                   2569: 
                   2570: #
                   2571: #   Change the authentication method of a user.  Note that this may
                   2572: #   also implicitly change the user's password if, for example, the user is
                   2573: #   joining an existing authentication realm.  Known authentication realms at
                   2574: #   this time are:
                   2575: #    internal   - Purely internal password file (only loncapa knows this user)
                   2576: #    local      - Institutionally written authentication module.
                   2577: #    unix       - Unix user (/etc/passwd with or without /etc/shadow).
                   2578: #    kerb4      - kerberos version 4
                   2579: #    kerb5      - kerberos version 5
                   2580: #
                   2581: # Parameters:
                   2582: #    $cmd      - The command that got us here.
                   2583: #    $tail     - Tail of the command (remaining parameters).
                   2584: #    $client   - File descriptor connected to client.
                   2585: # Returns
                   2586: #     0        - Requested to exit, caller should shut down.
                   2587: #     1        - Continue processing.
                   2588: # Implicit inputs:
                   2589: #    The authentication systems describe above have their own forms of implicit
                   2590: #    input into the authentication process that are described above.
1.287     foxr     2591: # NOTE:
                   2592: #   This is also used to change the authentication credential values (e.g. passwd).
                   2593: #   
1.225     foxr     2594: #
                   2595: sub change_authentication_handler {
                   2596: 
                   2597:     my ($cmd, $tail, $client) = @_;
                   2598:    
                   2599:     my $userinput  = "$cmd:$tail";              # Reconstruct user input.
                   2600: 
                   2601:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   2602:     &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
                   2603:     if ($udom ne $currentdomainid) {
                   2604: 	&Failure( $client, "not_right_domain\n", $client);
                   2605:     } else {
                   2606: 	
                   2607: 	chomp($npass);
                   2608: 	
                   2609: 	$npass=&unescape($npass);
1.261     foxr     2610: 	my $oldauth = &get_auth_type($udom, $uname); # Get old auth info.
1.225     foxr     2611: 	my $passfilename = &password_path($udom, $uname);
                   2612: 	if ($passfilename) {	# Not allowed to create a new user!!
1.287     foxr     2613: 	    # If just changing the unix passwd. need to arrange to run
1.502     raeburn  2614: 	    # passwd since otherwise make_passwd_file will fail as 
                   2615: 	    # creation of unix authenticated users is no longer supported
                   2616:             # except from the command line, when running make_domain_coordinator.pl
1.287     foxr     2617: 
                   2618: 	    if(($oldauth =~/^unix/) && ($umode eq "unix")) {
                   2619: 		my $result = &change_unix_password($uname, $npass);
                   2620: 		&logthis("Result of password change for $uname: ".$result);
                   2621: 		if ($result eq "ok") {
1.518     raeburn  2622:                     &update_passwd_history($uname,$udom,$umode,'changeuserauth'); 
1.390     raeburn  2623: 		    &Reply($client, \$result);
1.288     albertel 2624: 		} else {
1.387     albertel 2625: 		    &Failure($client, \$result);
1.287     foxr     2626: 		}
1.288     albertel 2627: 	    } else {
1.518     raeburn  2628: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
                   2629:                                              $passfilename,'changeuserauth');
1.287     foxr     2630: 		#
                   2631: 		#  If the current auth mode is internal, and the old auth mode was
                   2632: 		#  unix, or krb*,  and the user is an author for this domain,
                   2633: 		#  re-run manage_permissions for that role in order to be able
                   2634: 		#  to take ownership of the construction space back to www:www
                   2635: 		#
1.502     raeburn  2636: 
                   2637: 
1.387     albertel 2638: 		&Reply($client, \$result, $userinput);
1.261     foxr     2639: 	    }
                   2640: 	       
                   2641: 
1.225     foxr     2642: 	} else {	       
1.251     foxr     2643: 	    &Failure($client, "non_authorized\n", $userinput); # Fail the user now.
1.225     foxr     2644: 	}
                   2645:     }
                   2646:     return 1;
                   2647: }
                   2648: &register_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
                   2649: 
1.518     raeburn  2650: sub update_passwd_history {
                   2651:     my ($uname,$udom,$umode,$context) = @_;
                   2652:     my $proname=&propath($udom,$uname);
                   2653:     my $now = time;
                   2654:     if (open(my $fh,">>$proname/passwd.log")) {
                   2655:         print $fh "$now:$umode:$context\n";
                   2656:         close($fh);
                   2657:     }
                   2658:     return;
                   2659: }
                   2660: 
1.575     raeburn  2661: sub inst_unamemap_check {
                   2662:     my ($cmd, $tail, $client)   = @_;
                   2663:     my $userinput               = "$cmd:$tail";
                   2664:     my %rulecheck;
                   2665:     my $outcome;
                   2666:     my ($udom,$uname,@rules) = split(/:/,$tail);
                   2667:     $udom = &unescape($udom);
                   2668:     $uname = &unescape($uname);
                   2669:     @rules = map {&unescape($_);} (@rules);
                   2670:     eval {
                   2671:         local($SIG{__DIE__})='DEFAULT';
                   2672:         $outcome = &localenroll::unamemap_check($udom,$uname,\@rules,\%rulecheck);
                   2673:     };
                   2674:     if (!$@) {
                   2675:         if ($outcome eq 'ok') {
                   2676:             my $result='';
                   2677:             foreach my $key (keys(%rulecheck)) {
                   2678:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   2679:             }
                   2680:             &Reply($client,\$result,$userinput);
                   2681:         } else {
                   2682:             &Reply($client,"error\n", $userinput);
                   2683:         }
                   2684:     } else {
                   2685:         &Failure($client,"unknown_cmd\n",$userinput);
                   2686:     }
                   2687: }
                   2688: &register_handler("instunamemapcheck",\&inst_unamemap_check,0,1,0);
                   2689: 
                   2690: 
1.225     foxr     2691: #
                   2692: #   Determines if this is the home server for a user.  The home server
                   2693: #   for a user will have his/her lon-capa passwd file.  Therefore all we need
                   2694: #   to do is determine if this file exists.
                   2695: #
                   2696: # Parameters:
                   2697: #    $cmd      - The command that got us here.
                   2698: #    $tail     - Tail of the command (remaining parameters).
                   2699: #    $client   - File descriptor connected to client.
                   2700: # Returns
                   2701: #     0        - Requested to exit, caller should shut down.
                   2702: #     1        - Continue processing.
                   2703: # Implicit inputs:
                   2704: #    The authentication systems describe above have their own forms of implicit
                   2705: #    input into the authentication process that are described above.
                   2706: #
                   2707: sub is_home_handler {
                   2708:     my ($cmd, $tail, $client) = @_;
                   2709:    
                   2710:     my $userinput  = "$cmd:$tail";
                   2711:    
                   2712:     my ($udom,$uname)=split(/:/,$tail);
                   2713:     chomp($uname);
                   2714:     my $passfile = &password_filename($udom, $uname);
                   2715:     if($passfile) {
                   2716: 	&Reply( $client, "found\n", $userinput);
                   2717:     } else {
                   2718: 	&Failure($client, "not_found\n", $userinput);
                   2719:     }
                   2720:     return 1;
                   2721: }
                   2722: &register_handler("home", \&is_home_handler, 0,1,0);
                   2723: 
                   2724: #
1.434     www      2725: #   Process an update request for a resource.
                   2726: #   A resource has been modified that we hold a subscription to.
1.225     foxr     2727: #   If the resource is not local, then we must update, or at least invalidate our
                   2728: #   cached copy of the resource. 
                   2729: # Parameters:
                   2730: #    $cmd      - The command that got us here.
                   2731: #    $tail     - Tail of the command (remaining parameters).
                   2732: #    $client   - File descriptor connected to client.
                   2733: # Returns
                   2734: #     0        - Requested to exit, caller should shut down.
                   2735: #     1        - Continue processing.
                   2736: # Implicit inputs:
                   2737: #    The authentication systems describe above have their own forms of implicit
                   2738: #    input into the authentication process that are described above.
                   2739: #
                   2740: sub update_resource_handler {
                   2741: 
                   2742:     my ($cmd, $tail, $client) = @_;
                   2743:    
                   2744:     my $userinput = "$cmd:$tail";
                   2745:    
                   2746:     my $fname= $tail;		# This allows interactive testing
                   2747: 
                   2748: 
                   2749:     my $ownership=ishome($fname);
                   2750:     if ($ownership eq 'not_owner') {
                   2751: 	if (-e $fname) {
1.434     www      2752:             # Delete preview file, if exists
                   2753:             unlink("$fname.tmp");
                   2754:             # Get usage stats
1.225     foxr     2755: 	    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
                   2756: 		$atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
                   2757: 	    my $now=time;
                   2758: 	    my $since=$now-$atime;
1.434     www      2759:             # If the file has not been used within lonExpire seconds,
                   2760:             # unsubscribe from it and delete local copy
1.225     foxr     2761: 	    if ($since>$perlvar{'lonExpire'}) {
1.365     albertel 2762: 		my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
1.308     albertel 2763: 		&devalidate_meta_cache($fname);
1.225     foxr     2764: 		unlink("$fname");
1.334     albertel 2765: 		unlink("$fname.meta");
1.225     foxr     2766: 	    } else {
1.434     www      2767:             # Yes, this is in active use. Get a fresh copy. Since it might be in
                   2768:             # very active use and huge (like a movie), copy it to "in.transfer" filename first.
1.225     foxr     2769: 		my $transname="$fname.in.transfer";
1.365     albertel 2770: 		my $remoteurl=&Apache::lonnet::reply("sub:$fname","$clientname");
1.225     foxr     2771: 		my $response;
1.537     raeburn  2772: # FIXME: cannot replicate files that take more than two minutes to transfer -- needs checking now 1200s timeout used
                   2773: # for LWP request.
                   2774: 		my $request=new HTTP::Request('GET',"$remoteurl");
                   2775:                 $response=&LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,0,1);
1.225     foxr     2776: 		if ($response->is_error()) {
1.541     raeburn  2777:                     my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
                   2778:                     &devalidate_meta_cache($fname);
                   2779:                     if (-e $transname) {
                   2780:                         unlink($transname);
                   2781:                     }
                   2782:                     unlink($fname);
1.225     foxr     2783: 		    my $message=$response->status_line;
                   2784: 		    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   2785: 		} else {
                   2786: 		    if ($remoteurl!~/\.meta$/) {
1.537     raeburn  2787: 			my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2788:                         my $mresponse = &LONCAPA::LWPReq::makerequest($clientname,$mrequest,$fname.'.meta',\%perlvar,120,0,1);
                   2789: 			if ($mresponse->is_error()) {
                   2790: 			    unlink($fname.'.meta');
1.225     foxr     2791: 			}
                   2792: 		    }
1.434     www      2793:                     # we successfully transfered, copy file over to real name
1.225     foxr     2794: 		    rename($transname,$fname);
1.308     albertel 2795: 		    &devalidate_meta_cache($fname);
1.225     foxr     2796: 		}
                   2797: 	    }
                   2798: 	    &Reply( $client, "ok\n", $userinput);
                   2799: 	} else {
                   2800: 	    &Failure($client, "not_found\n", $userinput);
                   2801: 	}
                   2802:     } else {
                   2803: 	&Failure($client, "rejected\n", $userinput);
                   2804:     }
                   2805:     return 1;
                   2806: }
                   2807: &register_handler("update", \&update_resource_handler, 0 ,1, 0);
                   2808: 
1.308     albertel 2809: sub devalidate_meta_cache {
                   2810:     my ($url) = @_;
                   2811:     use Cache::Memcached;
                   2812:     my $memcache = new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.365     albertel 2813:     $url = &Apache::lonnet::declutter($url);
1.308     albertel 2814:     $url =~ s-\.meta$--;
                   2815:     my $id = &escape('meta:'.$url);
                   2816:     $memcache->delete($id);
                   2817: }
                   2818: 
1.225     foxr     2819: #
1.226     foxr     2820: #   Fetch a user file from a remote server to the user's home directory
                   2821: #   userfiles subdir.
1.225     foxr     2822: # Parameters:
                   2823: #    $cmd      - The command that got us here.
                   2824: #    $tail     - Tail of the command (remaining parameters).
                   2825: #    $client   - File descriptor connected to client.
                   2826: # Returns
                   2827: #     0        - Requested to exit, caller should shut down.
                   2828: #     1        - Continue processing.
                   2829: #
                   2830: sub fetch_user_file_handler {
                   2831: 
                   2832:     my ($cmd, $tail, $client) = @_;
                   2833: 
                   2834:     my $userinput = "$cmd:$tail";
                   2835:     my $fname           = $tail;
1.232     foxr     2836:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
1.225     foxr     2837:     my $udir=&propath($udom,$uname).'/userfiles';
                   2838:     unless (-e $udir) {
                   2839: 	mkdir($udir,0770); 
                   2840:     }
1.232     foxr     2841:     Debug("fetch user file for $fname");
1.225     foxr     2842:     if (-e $udir) {
                   2843: 	$ufile=~s/^[\.\~]+//;
1.232     foxr     2844: 
                   2845: 	# IF necessary, create the path right down to the file.
                   2846: 	# Note that any regular files in the way of this path are
                   2847: 	# wiped out to deal with some earlier folly of mine.
                   2848: 
1.267     raeburn  2849: 	if (!&mkpath($udir.'/'.$ufile)) {
1.264     albertel 2850: 	    &Failure($client, "unable_to_create\n", $userinput);	    
1.232     foxr     2851: 	}
                   2852: 
1.225     foxr     2853: 	my $destname=$udir.'/'.$ufile;
                   2854: 	my $transname=$udir.'/'.$ufile.'.in.transit';
1.476     raeburn  2855:         my $clientprotocol=$Apache::lonnet::protocol{$clientname};
                   2856:         $clientprotocol = 'http' if ($clientprotocol ne 'https');
1.486     raeburn  2857: 	my $clienthost = &Apache::lonnet::hostname($clientname);
                   2858: 	my $remoteurl=$clientprotocol.'://'.$clienthost.'/userfiles/'.$fname;
1.225     foxr     2859: 	my $response;
1.232     foxr     2860: 	Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
1.537     raeburn  2861: 	my $request=new HTTP::Request('GET',"$remoteurl");
                   2862:         my $verifycert = 1;
                   2863:         my @machine_ids = &Apache::lonnet::current_machine_ids();
                   2864:         if (grep(/^\Q$clientname\E$/,@machine_ids)) {
                   2865:             $verifycert = 0;
                   2866:         }
                   2867:         $response = &LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,$verifycert);
1.225     foxr     2868: 	if ($response->is_error()) {
                   2869: 	    unlink($transname);
                   2870: 	    my $message=$response->status_line;
                   2871: 	    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   2872: 	    &Failure($client, "failed\n", $userinput);
                   2873: 	} else {
1.232     foxr     2874: 	    Debug("Renaming $transname to $destname");
1.225     foxr     2875: 	    if (!rename($transname,$destname)) {
                   2876: 		&logthis("Unable to move $transname to $destname");
                   2877: 		unlink($transname);
                   2878: 		&Failure($client, "failed\n", $userinput);
                   2879: 	    } else {
1.495     raeburn  2880:                 if ($fname =~ /^default.+\.(page|sequence)$/) {
                   2881:                     my ($major,$minor) = split(/\./,$clientversion);
                   2882:                     if (($major < 2) || ($major == 2 && $minor < 11)) {
                   2883:                         my $now = time;
                   2884:                         &Apache::lonnet::do_cache_new('crschange',$udom.'_'.$uname,$now,600);
                   2885:                         my $key = &escape('internal.contentchange');
                   2886:                         my $what = "$key=$now";
                   2887:                         my $hashref = &tie_user_hash($udom,$uname,'environment',
                   2888:                                                      &GDBM_WRCREAT(),"P",$what);
                   2889:                         if ($hashref) {
                   2890:                             $hashref->{$key}=$now;
                   2891:                             if (!&untie_user_hash($hashref)) {
                   2892:                                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
                   2893:                                          "when updating internal.contentchange");
                   2894:                             }
                   2895:                         }
                   2896:                     }
                   2897:                 }
1.225     foxr     2898: 		&Reply($client, "ok\n", $userinput);
                   2899: 	    }
                   2900: 	}   
                   2901:     } else {
                   2902: 	&Failure($client, "not_home\n", $userinput);
                   2903:     }
                   2904:     return 1;
                   2905: }
                   2906: &register_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
                   2907: 
1.226     foxr     2908: #
                   2909: #   Remove a file from a user's home directory userfiles subdirectory.
                   2910: # Parameters:
                   2911: #    cmd   - the Lond request keyword that got us here.
                   2912: #    tail  - the part of the command past the keyword.
                   2913: #    client- File descriptor connected with the client.
                   2914: #
                   2915: # Returns:
                   2916: #    1    - Continue processing.
                   2917: sub remove_user_file_handler {
                   2918:     my ($cmd, $tail, $client) = @_;
                   2919: 
                   2920:     my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2921: 
                   2922:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2923:     if ($ufile =~m|/\.\./|) {
                   2924: 	# any files paths with /../ in them refuse 
                   2925: 	# to deal with
                   2926: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2927:     } else {
                   2928: 	my $udir = &propath($udom,$uname);
                   2929: 	if (-e $udir) {
                   2930: 	    my $file=$udir.'/userfiles/'.$ufile;
                   2931: 	    if (-e $file) {
1.253     foxr     2932: 		#
                   2933: 		#   If the file is a regular file unlink is fine...
1.520     raeburn  2934: 		#   However it's possible the client wants a dir 
                   2935: 		#   removed, in which case rmdir is more appropriate.
                   2936: 		#   Note: rmdir will only remove an empty directory.
1.253     foxr     2937: 		#
1.240     banghart 2938: 	        if (-f $file){
1.241     albertel 2939: 		    unlink($file);
1.520     raeburn  2940:                     # for html files remove the associated .bak file 
                   2941:                     # which may have been created by the editor.
                   2942:                     if ($ufile =~ m{^((docs|supplemental)/(?:\d+|default)/\d+(?:|/.+)/)[^/]+\.x?html?$}i) {
                   2943:                         my $path = $1;
                   2944:                         if (-e $file.'.bak') {
                   2945:                             unlink($file.'.bak');
                   2946:                         }
                   2947:                     }
1.241     albertel 2948: 		} elsif(-d $file) {
                   2949: 		    rmdir($file);
1.240     banghart 2950: 		}
1.226     foxr     2951: 		if (-e $file) {
1.253     foxr     2952: 		    #  File is still there after we deleted it ?!?
                   2953: 
1.226     foxr     2954: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2955: 		} else {
                   2956: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2957: 		}
                   2958: 	    } else {
                   2959: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2960: 	    }
                   2961: 	} else {
                   2962: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2963: 	}
                   2964:     }
                   2965:     return 1;
                   2966: }
                   2967: &register_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
                   2968: 
1.236     albertel 2969: #
                   2970: #   make a directory in a user's home directory userfiles subdirectory.
                   2971: # Parameters:
                   2972: #    cmd   - the Lond request keyword that got us here.
                   2973: #    tail  - the part of the command past the keyword.
                   2974: #    client- File descriptor connected with the client.
                   2975: #
                   2976: # Returns:
                   2977: #    1    - Continue processing.
                   2978: sub mkdir_user_file_handler {
                   2979:     my ($cmd, $tail, $client) = @_;
                   2980: 
                   2981:     my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2982:     $dir=&unescape($dir);
                   2983:     my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2984:     if ($ufile =~m|/\.\./|) {
                   2985: 	# any files paths with /../ in them refuse 
                   2986: 	# to deal with
                   2987: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2988:     } else {
                   2989: 	my $udir = &propath($udom,$uname);
                   2990: 	if (-e $udir) {
1.264     albertel 2991: 	    my $newdir=$udir.'/userfiles/'.$ufile.'/';
                   2992: 	    if (!&mkpath($newdir)) {
                   2993: 		&Failure($client, "failed\n", "$cmd:$tail");
1.236     albertel 2994: 	    }
1.264     albertel 2995: 	    &Reply($client, "ok\n", "$cmd:$tail");
1.236     albertel 2996: 	} else {
                   2997: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2998: 	}
                   2999:     }
                   3000:     return 1;
                   3001: }
                   3002: &register_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
                   3003: 
1.237     albertel 3004: #
                   3005: #   rename a file in a user's home directory userfiles subdirectory.
                   3006: # Parameters:
                   3007: #    cmd   - the Lond request keyword that got us here.
                   3008: #    tail  - the part of the command past the keyword.
                   3009: #    client- File descriptor connected with the client.
                   3010: #
                   3011: # Returns:
                   3012: #    1    - Continue processing.
                   3013: sub rename_user_file_handler {
                   3014:     my ($cmd, $tail, $client) = @_;
                   3015: 
                   3016:     my ($udom,$uname,$old,$new) = split(/:/, $tail);
                   3017:     $old=&unescape($old);
                   3018:     $new=&unescape($new);
                   3019:     if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
                   3020: 	# any files paths with /../ in them refuse to deal with
                   3021: 	&Failure($client, "refused\n", "$cmd:$tail");
                   3022:     } else {
                   3023: 	my $udir = &propath($udom,$uname);
                   3024: 	if (-e $udir) {
                   3025: 	    my $oldfile=$udir.'/userfiles/'.$old;
                   3026: 	    my $newfile=$udir.'/userfiles/'.$new;
                   3027: 	    if (-e $newfile) {
                   3028: 		&Failure($client, "exists\n", "$cmd:$tail");
                   3029: 	    } elsif (! -e $oldfile) {
                   3030: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   3031: 	    } else {
                   3032: 		if (!rename($oldfile,$newfile)) {
                   3033: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   3034: 		} else {
                   3035: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   3036: 		}
                   3037: 	    }
                   3038: 	} else {
                   3039: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   3040: 	}
                   3041:     }
                   3042:     return 1;
                   3043: }
                   3044: &register_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
                   3045: 
1.227     foxr     3046: #
1.382     albertel 3047: #  Checks if the specified user has an active session on the server
                   3048: #  return ok if so, not_found if not
                   3049: #
                   3050: # Parameters:
                   3051: #   cmd      - The request keyword that dispatched to tus.
                   3052: #   tail     - The tail of the request (colon separated parameters).
                   3053: #   client   - Filehandle open on the client.
                   3054: # Return:
                   3055: #    1.
                   3056: sub user_has_session_handler {
                   3057:     my ($cmd, $tail, $client) = @_;
                   3058: 
                   3059:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
                   3060:     
                   3061:     opendir(DIR,$perlvar{'lonIDsDir'});
                   3062:     my $filename;
                   3063:     while ($filename=readdir(DIR)) {
                   3064: 	last if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/);
                   3065:     }
                   3066:     if ($filename) {
                   3067: 	&Reply($client, "ok\n", "$cmd:$tail");
                   3068:     } else {
                   3069: 	&Failure($client, "not_found\n", "$cmd:$tail");
                   3070:     }
                   3071:     return 1;
                   3072: 
                   3073: }
                   3074: &register_handler("userhassession", \&user_has_session_handler, 0,1,0);
                   3075: 
1.560     raeburn  3076: sub del_usersession_handler {
                   3077:     my ($cmd, $tail, $client) = @_;
                   3078: 
                   3079:     my $result;
                   3080:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
                   3081:     if (($udom =~ /^$LONCAPA::match_domain$/) && ($uname =~ /^$LONCAPA::match_username$/)) {
                   3082:         my $lonidsdir = $perlvar{'lonIDsDir'};
                   3083:         if (-d $lonidsdir) {
                   3084:             if (opendir(DIR,$lonidsdir)) {
                   3085:                 my $filename;
                   3086:                 while ($filename=readdir(DIR)) {
                   3087:                     if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/) {
                   3088:                         if (tie(my %oldenv,'GDBM_File',"$lonidsdir/$filename",
                   3089:                                 &GDBM_READER(),0640)) {
                   3090:                             my $linkedfile;
                   3091:                             if (exists($oldenv{'user.linkedenv'})) {
                   3092:                                 $linkedfile = $oldenv{'user.linkedenv'};
                   3093:                             }
                   3094:                             untie(%oldenv);
                   3095:                             $result = unlink("$lonidsdir/$filename");
                   3096:                             if ($result) {
                   3097:                                 if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   3098:                                     if (-l "$lonidsdir/$linkedfile.id") {
                   3099:                                         unlink("$lonidsdir/$linkedfile.id");
                   3100:                                     }
                   3101:                                 }
                   3102:                             }
                   3103:                         } else {
                   3104:                             $result = unlink("$lonidsdir/$filename");
                   3105:                         }
                   3106:                         last;
                   3107:                     }
                   3108:                 }
                   3109:             }
                   3110:         }
                   3111:         if ($result == 1) {
                   3112:             &Reply($client, "$result\n", "$cmd:$tail");
                   3113:         } else {
                   3114:             &Reply($client, "not_found\n", "$cmd:$tail");
                   3115:         }
                   3116:     } else {
                   3117:         &Failure($client, "invalid_user\n", "$cmd:$tail");
                   3118:     }
                   3119:     return 1;
                   3120: }
                   3121: 
                   3122: &register_handler("delusersession", \&del_usersession_handler, 0,1,0);
                   3123: 
1.382     albertel 3124: #
1.263     albertel 3125: #  Authenticate access to a user file by checking that the token the user's 
                   3126: #  passed also exists in their session file
1.227     foxr     3127: #
                   3128: # Parameters:
                   3129: #   cmd      - The request keyword that dispatched to tus.
                   3130: #   tail     - The tail of the request (colon separated parameters).
                   3131: #   client   - Filehandle open on the client.
                   3132: # Return:
                   3133: #    1.
                   3134: sub token_auth_user_file_handler {
                   3135:     my ($cmd, $tail, $client) = @_;
                   3136: 
                   3137:     my ($fname, $session) = split(/:/, $tail);
                   3138:     
                   3139:     chomp($session);
1.393     raeburn  3140:     my $reply="non_auth";
1.343     albertel 3141:     my $file = $perlvar{'lonIDsDir'}.'/'.$session.'.id';
                   3142:     if (open(ENVIN,"$file")) {
1.332     albertel 3143: 	flock(ENVIN,LOCK_SH);
1.343     albertel 3144: 	tie(my %disk_env,'GDBM_File',"$file",&GDBM_READER(),0640);
                   3145: 	if (exists($disk_env{"userfile.$fname"})) {
1.393     raeburn  3146: 	    $reply="ok";
1.343     albertel 3147: 	} else {
                   3148: 	    foreach my $envname (keys(%disk_env)) {
                   3149: 		if ($envname=~ m|^userfile\.\Q$fname\E|) {
1.393     raeburn  3150: 		    $reply="ok";
1.343     albertel 3151: 		    last;
                   3152: 		}
                   3153: 	    }
1.227     foxr     3154: 	}
1.343     albertel 3155: 	untie(%disk_env);
1.227     foxr     3156: 	close(ENVIN);
1.387     albertel 3157: 	&Reply($client, \$reply, "$cmd:$tail");
1.227     foxr     3158:     } else {
                   3159: 	&Failure($client, "invalid_token\n", "$cmd:$tail");
                   3160:     }
                   3161:     return 1;
                   3162: 
                   3163: }
                   3164: &register_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
1.229     foxr     3165: 
                   3166: #
                   3167: #   Unsubscribe from a resource.
                   3168: #
                   3169: # Parameters:
                   3170: #    $cmd      - The command that got us here.
                   3171: #    $tail     - Tail of the command (remaining parameters).
                   3172: #    $client   - File descriptor connected to client.
                   3173: # Returns
                   3174: #     0        - Requested to exit, caller should shut down.
                   3175: #     1        - Continue processing.
                   3176: #
                   3177: sub unsubscribe_handler {
                   3178:     my ($cmd, $tail, $client) = @_;
                   3179: 
                   3180:     my $userinput= "$cmd:$tail";
                   3181:     
                   3182:     my ($fname) = split(/:/,$tail); # Split in case there's extrs.
                   3183: 
                   3184:     &Debug("Unsubscribing $fname");
                   3185:     if (-e $fname) {
                   3186: 	&Debug("Exists");
                   3187: 	&Reply($client, &unsub($fname,$clientip), $userinput);
                   3188:     } else {
                   3189: 	&Failure($client, "not_found\n", $userinput);
                   3190:     }
                   3191:     return 1;
                   3192: }
                   3193: &register_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
1.263     albertel 3194: 
1.230     foxr     3195: #   Subscribe to a resource
                   3196: #
                   3197: # Parameters:
                   3198: #    $cmd      - The command that got us here.
                   3199: #    $tail     - Tail of the command (remaining parameters).
                   3200: #    $client   - File descriptor connected to client.
                   3201: # Returns
                   3202: #     0        - Requested to exit, caller should shut down.
                   3203: #     1        - Continue processing.
                   3204: #
                   3205: sub subscribe_handler {
                   3206:     my ($cmd, $tail, $client)= @_;
                   3207: 
                   3208:     my $userinput  = "$cmd:$tail";
                   3209: 
                   3210:     &Reply( $client, &subscribe($userinput,$clientip), $userinput);
                   3211: 
                   3212:     return 1;
                   3213: }
                   3214: &register_handler("sub", \&subscribe_handler, 0, 1, 0);
                   3215: 
                   3216: #
1.379     albertel 3217: #   Determine the latest version of a resource (it looks for the highest
                   3218: #   past version and then returns that +1)
1.230     foxr     3219: #
                   3220: # Parameters:
                   3221: #    $cmd      - The command that got us here.
                   3222: #    $tail     - Tail of the command (remaining parameters).
1.379     albertel 3223: #                 (Should consist of an absolute path to a file)
1.230     foxr     3224: #    $client   - File descriptor connected to client.
                   3225: # Returns
                   3226: #     0        - Requested to exit, caller should shut down.
                   3227: #     1        - Continue processing.
                   3228: #
                   3229: sub current_version_handler {
                   3230:     my ($cmd, $tail, $client) = @_;
                   3231: 
                   3232:     my $userinput= "$cmd:$tail";
                   3233:    
                   3234:     my $fname   = $tail;
                   3235:     &Reply( $client, &currentversion($fname)."\n", $userinput);
                   3236:     return 1;
                   3237: 
                   3238: }
                   3239: &register_handler("currentversion", \&current_version_handler, 0, 1, 0);
                   3240: 
                   3241: #  Make an entry in a user's activity log.
                   3242: #
                   3243: # Parameters:
                   3244: #    $cmd      - The command that got us here.
                   3245: #    $tail     - Tail of the command (remaining parameters).
                   3246: #    $client   - File descriptor connected to client.
                   3247: # Returns
                   3248: #     0        - Requested to exit, caller should shut down.
                   3249: #     1        - Continue processing.
                   3250: #
                   3251: sub activity_log_handler {
                   3252:     my ($cmd, $tail, $client) = @_;
                   3253: 
                   3254: 
                   3255:     my $userinput= "$cmd:$tail";
                   3256: 
                   3257:     my ($udom,$uname,$what)=split(/:/,$tail);
                   3258:     chomp($what);
                   3259:     my $proname=&propath($udom,$uname);
                   3260:     my $now=time;
                   3261:     my $hfh;
                   3262:     if ($hfh=IO::File->new(">>$proname/activity.log")) { 
                   3263: 	print $hfh "$now:$clientname:$what\n";
                   3264: 	&Reply( $client, "ok\n", $userinput); 
                   3265:     } else {
                   3266: 	&Failure($client, "error: ".($!+0)." IO::File->new Failed "
                   3267: 		 ."while attempting log\n", 
                   3268: 		 $userinput);
                   3269:     }
                   3270: 
                   3271:     return 1;
                   3272: }
1.263     albertel 3273: &register_handler("log", \&activity_log_handler, 0, 1, 0);
1.230     foxr     3274: 
                   3275: #
                   3276: #   Put a namespace entry in a user profile hash.
                   3277: #   My druthers would be for this to be an encrypted interaction too.
                   3278: #   anything that might be an inadvertent covert channel about either
                   3279: #   user authentication or user personal information....
                   3280: #
                   3281: # Parameters:
                   3282: #    $cmd      - The command that got us here.
                   3283: #    $tail     - Tail of the command (remaining parameters).
                   3284: #    $client   - File descriptor connected to client.
                   3285: # Returns
                   3286: #     0        - Requested to exit, caller should shut down.
                   3287: #     1        - Continue processing.
                   3288: #
                   3289: sub put_user_profile_entry {
                   3290:     my ($cmd, $tail, $client)  = @_;
1.229     foxr     3291: 
1.230     foxr     3292:     my $userinput = "$cmd:$tail";
                   3293:     
1.242     raeburn  3294:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
1.230     foxr     3295:     if ($namespace ne 'roles') {
                   3296: 	chomp($what);
                   3297: 	my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3298: 				  &GDBM_WRCREAT(),"P",$what);
                   3299: 	if($hashref) {
                   3300: 	    my @pairs=split(/\&/,$what);
                   3301: 	    foreach my $pair (@pairs) {
                   3302: 		my ($key,$value)=split(/=/,$pair);
                   3303: 		$hashref->{$key}=$value;
                   3304: 	    }
1.311     albertel 3305: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     3306: 		&Reply( $client, "ok\n", $userinput);
                   3307: 	    } else {
                   3308: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3309: 			"while attempting put\n", 
                   3310: 			$userinput);
                   3311: 	    }
                   3312: 	} else {
1.316     albertel 3313: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.230     foxr     3314: 		     "while attempting put\n", $userinput);
                   3315: 	}
                   3316:     } else {
                   3317:         &Failure( $client, "refused\n", $userinput);
                   3318:     }
                   3319:     
                   3320:     return 1;
                   3321: }
                   3322: &register_handler("put", \&put_user_profile_entry, 0, 1, 0);
                   3323: 
1.283     albertel 3324: #   Put a piece of new data in hash, returns error if entry already exists
                   3325: # Parameters:
                   3326: #    $cmd      - The command that got us here.
                   3327: #    $tail     - Tail of the command (remaining parameters).
                   3328: #    $client   - File descriptor connected to client.
                   3329: # Returns
                   3330: #     0        - Requested to exit, caller should shut down.
                   3331: #     1        - Continue processing.
                   3332: #
                   3333: sub newput_user_profile_entry {
                   3334:     my ($cmd, $tail, $client)  = @_;
                   3335: 
                   3336:     my $userinput = "$cmd:$tail";
                   3337: 
                   3338:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
                   3339:     if ($namespace eq 'roles') {
                   3340:         &Failure( $client, "refused\n", $userinput);
                   3341: 	return 1;
                   3342:     }
                   3343: 
                   3344:     chomp($what);
                   3345: 
                   3346:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3347: 				 &GDBM_WRCREAT(),"N",$what);
                   3348:     if(!$hashref) {
1.316     albertel 3349: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.283     albertel 3350: 		  "while attempting put\n", $userinput);
                   3351: 	return 1;
                   3352:     }
                   3353: 
                   3354:     my @pairs=split(/\&/,$what);
                   3355:     foreach my $pair (@pairs) {
                   3356: 	my ($key,$value)=split(/=/,$pair);
                   3357: 	if (exists($hashref->{$key})) {
1.513     raeburn  3358:             if (!&untie_user_hash($hashref)) {
                   3359:                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
                   3360:                          "while attempting newput - early out as key exists");
                   3361:             }
                   3362:             &Failure($client, "key_exists: ".$key."\n",$userinput);
                   3363:             return 1;
1.283     albertel 3364: 	}
                   3365:     }
                   3366: 
                   3367:     foreach my $pair (@pairs) {
                   3368: 	my ($key,$value)=split(/=/,$pair);
                   3369: 	$hashref->{$key}=$value;
                   3370:     }
                   3371: 
1.311     albertel 3372:     if (&untie_user_hash($hashref)) {
1.283     albertel 3373: 	&Reply( $client, "ok\n", $userinput);
                   3374:     } else {
                   3375: 	&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3376: 		 "while attempting put\n", 
                   3377: 		 $userinput);
                   3378:     }
                   3379:     return 1;
                   3380: }
                   3381: &register_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
                   3382: 
1.230     foxr     3383: # 
                   3384: #   Increment a profile entry in the user history file.
                   3385: #   The history contains keyword value pairs.  In this case,
                   3386: #   The value itself is a pair of numbers.  The first, the current value
                   3387: #   the second an increment that this function applies to the current
                   3388: #   value.
                   3389: #
                   3390: # Parameters:
                   3391: #    $cmd      - The command that got us here.
                   3392: #    $tail     - Tail of the command (remaining parameters).
                   3393: #    $client   - File descriptor connected to client.
                   3394: # Returns
                   3395: #     0        - Requested to exit, caller should shut down.
                   3396: #     1        - Continue processing.
                   3397: #
                   3398: sub increment_user_value_handler {
                   3399:     my ($cmd, $tail, $client) = @_;
                   3400:     
                   3401:     my $userinput   = "$cmd:$tail";
                   3402:     
                   3403:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
                   3404:     if ($namespace ne 'roles') {
                   3405:         chomp($what);
                   3406: 	my $hashref = &tie_user_hash($udom, $uname,
                   3407: 				     $namespace, &GDBM_WRCREAT(),
                   3408: 				     "P",$what);
                   3409: 	if ($hashref) {
                   3410: 	    my @pairs=split(/\&/,$what);
                   3411: 	    foreach my $pair (@pairs) {
                   3412: 		my ($key,$value)=split(/=/,$pair);
1.284     raeburn  3413:                 $value = &unescape($value);
1.230     foxr     3414: 		# We could check that we have a number...
                   3415: 		if (! defined($value) || $value eq '') {
                   3416: 		    $value = 1;
                   3417: 		}
                   3418: 		$hashref->{$key}+=$value;
1.284     raeburn  3419:                 if ($namespace eq 'nohist_resourcetracker') {
                   3420:                     if ($hashref->{$key} < 0) {
                   3421:                         $hashref->{$key} = 0;
                   3422:                     }
                   3423:                 }
1.230     foxr     3424: 	    }
1.311     albertel 3425: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     3426: 		&Reply( $client, "ok\n", $userinput);
                   3427: 	    } else {
                   3428: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3429: 			 "while attempting inc\n", $userinput);
                   3430: 	    }
                   3431: 	} else {
                   3432: 	    &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3433: 		     "while attempting inc\n", $userinput);
                   3434: 	}
                   3435:     } else {
                   3436: 	&Failure($client, "refused\n", $userinput);
                   3437:     }
                   3438:     
                   3439:     return 1;
                   3440: }
                   3441: &register_handler("inc", \&increment_user_value_handler, 0, 1, 0);
                   3442: 
                   3443: #
                   3444: #   Put a new role for a user.  Roles are LonCAPA's packaging of permissions.
                   3445: #   Each 'role' a user has implies a set of permissions.  Adding a new role
                   3446: #   for a person grants the permissions packaged with that role
                   3447: #   to that user when the role is selected.
                   3448: #
                   3449: # Parameters:
                   3450: #    $cmd       - The command string (rolesput).
                   3451: #    $tail      - The remainder of the request line.  For rolesput this
                   3452: #                 consists of a colon separated list that contains:
                   3453: #                 The domain and user that is granting the role (logged).
                   3454: #                 The domain and user that is getting the role.
                   3455: #                 The roles being granted as a set of & separated pairs.
                   3456: #                 each pair a key value pair.
                   3457: #    $client    - File descriptor connected to the client.
                   3458: # Returns:
                   3459: #     0         - If the daemon should exit
                   3460: #     1         - To continue processing.
                   3461: #
                   3462: #
                   3463: sub roles_put_handler {
                   3464:     my ($cmd, $tail, $client) = @_;
                   3465: 
                   3466:     my $userinput  = "$cmd:$tail";
                   3467: 
                   3468:     my ( $exedom, $exeuser, $udom, $uname,  $what) = split(/:/,$tail);
                   3469:     
                   3470: 
                   3471:     my $namespace='roles';
                   3472:     chomp($what);
                   3473:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3474: 				 &GDBM_WRCREAT(), "P",
                   3475: 				 "$exedom:$exeuser:$what");
                   3476:     #
                   3477:     #  Log the attempt to set a role.  The {}'s here ensure that the file 
                   3478:     #  handle is open for the minimal amount of time.  Since the flush
                   3479:     #  is done on close this improves the chances the log will be an un-
                   3480:     #  corrupted ordered thing.
                   3481:     if ($hashref) {
1.261     foxr     3482: 	my $pass_entry = &get_auth_type($udom, $uname);
                   3483: 	my ($auth_type,$pwd)  = split(/:/, $pass_entry);
                   3484: 	$auth_type = $auth_type.":";
1.230     foxr     3485: 	my @pairs=split(/\&/,$what);
                   3486: 	foreach my $pair (@pairs) {
                   3487: 	    my ($key,$value)=split(/=/,$pair);
                   3488: 	    &manage_permissions($key, $udom, $uname,
1.260     foxr     3489: 			       $auth_type);
1.230     foxr     3490: 	    $hashref->{$key}=$value;
                   3491: 	}
1.311     albertel 3492: 	if (&untie_user_hash($hashref)) {
1.230     foxr     3493: 	    &Reply($client, "ok\n", $userinput);
                   3494: 	} else {
                   3495: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3496: 		     "while attempting rolesput\n", $userinput);
                   3497: 	}
                   3498:     } else {
                   3499: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3500: 		 "while attempting rolesput\n", $userinput);
                   3501:     }
                   3502:     return 1;
                   3503: }
                   3504: &register_handler("rolesput", \&roles_put_handler, 1,1,0);  # Encoded client only.
                   3505: 
                   3506: #
1.231     foxr     3507: #   Deletes (removes) a role for a user.   This is equivalent to removing
                   3508: #  a permissions package associated with the role from the user's profile.
                   3509: #
                   3510: # Parameters:
                   3511: #     $cmd                 - The command (rolesdel)
                   3512: #     $tail                - The remainder of the request line. This consists
                   3513: #                             of:
                   3514: #                             The domain and user requesting the change (logged)
                   3515: #                             The domain and user being changed.
                   3516: #                             The roles being revoked.  These are shipped to us
                   3517: #                             as a bunch of & separated role name keywords.
                   3518: #     $client              - The file handle open on the client.
                   3519: # Returns:
                   3520: #     1                    - Continue processing
                   3521: #     0                    - Exit.
                   3522: #
                   3523: sub roles_delete_handler {
                   3524:     my ($cmd, $tail, $client)  = @_;
                   3525: 
                   3526:     my $userinput    = "$cmd:$tail";
                   3527:    
                   3528:     my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
                   3529:     &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
                   3530: 	   "what = ".$what);
                   3531:     my $namespace='roles';
                   3532:     chomp($what);
                   3533:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3534: 				 &GDBM_WRCREAT(), "D",
                   3535: 				 "$exedom:$exeuser:$what");
                   3536:     
                   3537:     if ($hashref) {
                   3538: 	my @rolekeys=split(/\&/,$what);
                   3539: 	
                   3540: 	foreach my $key (@rolekeys) {
                   3541: 	    delete $hashref->{$key};
                   3542: 	}
1.315     albertel 3543: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3544: 	    &Reply($client, "ok\n", $userinput);
                   3545: 	} else {
                   3546: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3547: 		     "while attempting rolesdel\n", $userinput);
                   3548: 	}
                   3549:     } else {
                   3550:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3551: 		 "while attempting rolesdel\n", $userinput);
                   3552:     }
                   3553:     
                   3554:     return 1;
                   3555: }
                   3556: &register_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
                   3557: 
                   3558: # Unencrypted get from a user's profile database.  See 
                   3559: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
                   3560: # This function retrieves a keyed item from a specific named database in the
                   3561: # user's directory.
                   3562: #
                   3563: # Parameters:
                   3564: #   $cmd             - Command request keyword (get).
                   3565: #   $tail            - Tail of the command.  This is a colon separated list
                   3566: #                      consisting of the domain and username that uniquely
                   3567: #                      identifies the profile,
                   3568: #                      The 'namespace' which selects the gdbm file to 
                   3569: #                      do the lookup in, 
                   3570: #                      & separated list of keys to lookup.  Note that
                   3571: #                      the values are returned as an & separated list too.
                   3572: #   $client          - File descriptor open on the client.
                   3573: # Returns:
                   3574: #   1       - Continue processing.
                   3575: #   0       - Exit.
                   3576: #
                   3577: sub get_profile_entry {
                   3578:     my ($cmd, $tail, $client) = @_;
                   3579: 
                   3580:     my $userinput= "$cmd:$tail";
                   3581:    
                   3582:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   3583:     chomp($what);
1.255     foxr     3584: 
1.390     raeburn  3585: 
1.255     foxr     3586:     my $replystring = read_profile($udom, $uname, $namespace, $what);
                   3587:     my ($first) = split(/:/,$replystring);
                   3588:     if($first ne "error") {
1.387     albertel 3589: 	&Reply($client, \$replystring, $userinput);
1.231     foxr     3590:     } else {
1.255     foxr     3591: 	&Failure($client, $replystring." while attempting get\n", $userinput);
1.231     foxr     3592:     }
                   3593:     return 1;
1.255     foxr     3594: 
                   3595: 
1.231     foxr     3596: }
                   3597: &register_handler("get", \&get_profile_entry, 0,1,0);
                   3598: 
                   3599: #
                   3600: #  Process the encrypted get request.  Note that the request is sent
                   3601: #  in clear, but the reply is encrypted.  This is a small covert channel:
                   3602: #  information about the sensitive keys is given to the snooper.  Just not
                   3603: #  information about the values of the sensitive key.  Hmm if I wanted to
                   3604: #  know these I'd snoop for the egets. Get the profile item names from them
                   3605: #  and then issue a get for them since there's no enforcement of the
                   3606: #  requirement of an encrypted get for particular profile items.  If I
                   3607: #  were re-doing this, I'd force the request to be encrypted as well as the
                   3608: #  reply.  I'd also just enforce encrypted transactions for all gets since
                   3609: #  that would prevent any covert channel snooping.
                   3610: #
                   3611: #  Parameters:
                   3612: #     $cmd               - Command keyword of request (eget).
1.536     raeburn  3613: #     $tail              - Tail of the command.  See GetProfileEntry
                   3614: #                          for more information about this.
1.231     foxr     3615: #     $client            - File open on the client.
                   3616: #  Returns:
                   3617: #     1      - Continue processing
                   3618: #     0      - server should exit.
                   3619: sub get_profile_entry_encrypted {
                   3620:     my ($cmd, $tail, $client) = @_;
                   3621: 
                   3622:     my $userinput = "$cmd:$tail";
                   3623:    
1.339     albertel 3624:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
1.231     foxr     3625:     chomp($what);
1.255     foxr     3626:     my $qresult = read_profile($udom, $uname, $namespace, $what);
                   3627:     my ($first) = split(/:/, $qresult);
                   3628:     if($first ne "error") {
                   3629: 	
                   3630: 	if ($cipher) {
                   3631: 	    my $cmdlength=length($qresult);
                   3632: 	    $qresult.="         ";
                   3633: 	    my $encqresult='';
                   3634: 	    for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   3635: 		$encqresult.= unpack("H16", 
                   3636: 				     $cipher->encrypt(substr($qresult,
                   3637: 							     $encidx,
                   3638: 							     8)));
                   3639: 	    }
                   3640: 	    &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
                   3641: 	} else {
1.231     foxr     3642: 		&Failure( $client, "error:no_key\n", $userinput);
                   3643: 	    }
                   3644:     } else {
1.255     foxr     3645: 	&Failure($client, "$qresult while attempting eget\n", $userinput);
                   3646: 
1.231     foxr     3647:     }
                   3648:     
                   3649:     return 1;
                   3650: }
1.255     foxr     3651: &register_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
1.263     albertel 3652: 
1.231     foxr     3653: #
                   3654: #   Deletes a key in a user profile database.
                   3655: #   
                   3656: #   Parameters:
                   3657: #       $cmd                  - Command keyword (del).
                   3658: #       $tail                 - Command tail.  IN this case a colon
                   3659: #                               separated list containing:
                   3660: #                               The domain and user that identifies uniquely
                   3661: #                               the identity of the user.
                   3662: #                               The profile namespace (name of the profile
                   3663: #                               database file).
                   3664: #                               & separated list of keywords to delete.
                   3665: #       $client              - File open on client socket.
                   3666: # Returns:
                   3667: #     1   - Continue processing
                   3668: #     0   - Exit server.
                   3669: #
                   3670: #
                   3671: sub delete_profile_entry {
                   3672:     my ($cmd, $tail, $client) = @_;
                   3673: 
                   3674:     my $userinput = "cmd:$tail";
                   3675: 
                   3676:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   3677:     chomp($what);
                   3678:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3679: 				 &GDBM_WRCREAT(),
                   3680: 				 "D",$what);
                   3681:     if ($hashref) {
                   3682:         my @keys=split(/\&/,$what);
                   3683: 	foreach my $key (@keys) {
                   3684: 	    delete($hashref->{$key});
                   3685: 	}
1.315     albertel 3686: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3687: 	    &Reply($client, "ok\n", $userinput);
                   3688: 	} else {
                   3689: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3690: 		    "while attempting del\n", $userinput);
                   3691: 	}
                   3692:     } else {
                   3693: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3694: 		 "while attempting del\n", $userinput);
                   3695:     }
                   3696:     return 1;
                   3697: }
                   3698: &register_handler("del", \&delete_profile_entry, 0, 1, 0);
1.263     albertel 3699: 
1.231     foxr     3700: #
                   3701: #  List the set of keys that are defined in a profile database file.
                   3702: #  A successful reply from this will contain an & separated list of
                   3703: #  the keys. 
                   3704: # Parameters:
                   3705: #     $cmd              - Command request (keys).
                   3706: #     $tail             - Remainder of the request, a colon separated
                   3707: #                         list containing domain/user that identifies the
                   3708: #                         user being queried, and the database namespace
                   3709: #                         (database filename essentially).
                   3710: #     $client           - File open on the client.
                   3711: #  Returns:
                   3712: #    1    - Continue processing.
                   3713: #    0    - Exit the server.
                   3714: #
                   3715: sub get_profile_keys {
                   3716:     my ($cmd, $tail, $client) = @_;
                   3717: 
                   3718:     my $userinput = "$cmd:$tail";
                   3719: 
                   3720:     my ($udom,$uname,$namespace)=split(/:/,$tail);
                   3721:     my $qresult='';
                   3722:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3723: 				  &GDBM_READER());
                   3724:     if ($hashref) {
                   3725: 	foreach my $key (keys %$hashref) {
                   3726: 	    $qresult.="$key&";
                   3727: 	}
1.315     albertel 3728: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3729: 	    $qresult=~s/\&$//;
1.387     albertel 3730: 	    &Reply($client, \$qresult, $userinput);
1.231     foxr     3731: 	} else {
                   3732: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3733: 		    "while attempting keys\n", $userinput);
                   3734: 	}
                   3735:     } else {
                   3736: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3737: 		 "while attempting keys\n", $userinput);
                   3738:     }
                   3739:    
                   3740:     return 1;
                   3741: }
                   3742: &register_handler("keys", \&get_profile_keys, 0, 1, 0);
                   3743: 
                   3744: #
                   3745: #   Dump the contents of a user profile database.
                   3746: #   Note that this constitutes a very large covert channel too since
                   3747: #   the dump will return sensitive information that is not encrypted.
                   3748: #   The naive security assumption is that the session negotiation ensures
                   3749: #   our client is trusted and I don't believe that's assured at present.
                   3750: #   Sure want badly to go to ssl or tls.  Of course if my peer isn't really
                   3751: #   a LonCAPA node they could have negotiated an encryption key too so >sigh<.
                   3752: # 
                   3753: #  Parameters:
                   3754: #     $cmd           - The command request keyword (currentdump).
                   3755: #     $tail          - Remainder of the request, consisting of a colon
                   3756: #                      separated list that has the domain/username and
                   3757: #                      the namespace to dump (database file).
                   3758: #     $client        - file open on the remote client.
                   3759: # Returns:
                   3760: #     1    - Continue processing.
                   3761: #     0    - Exit the server.
                   3762: #
                   3763: sub dump_profile_database {
                   3764:     my ($cmd, $tail, $client) = @_;
                   3765: 
1.494     droeschl 3766:     my $res = LONCAPA::Lond::dump_profile_database($tail);
                   3767: 
                   3768:     if ($res =~ /^error:/) {
                   3769:         Failure($client, \$res, "$cmd:$tail");
                   3770:     } else {
                   3771:         Reply($client, \$res, "$cmd:$tail");
                   3772:     }
                   3773: 
                   3774:     return 1;  
                   3775: 
                   3776:     #TODO remove 
1.231     foxr     3777:     my $userinput = "$cmd:$tail";
                   3778:    
                   3779:     my ($udom,$uname,$namespace) = split(/:/,$tail);
                   3780:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3781: 				 &GDBM_READER());
                   3782:     if ($hashref) {
                   3783: 	# Structure of %data:
                   3784: 	# $data{$symb}->{$parameter}=$value;
                   3785: 	# $data{$symb}->{'v.'.$parameter}=$version;
                   3786: 	# since $parameter will be unescaped, we do not
                   3787:  	# have to worry about silly parameter names...
                   3788: 	
                   3789:         my $qresult='';
                   3790: 	my %data = ();                     # A hash of anonymous hashes..
                   3791: 	while (my ($key,$value) = each(%$hashref)) {
                   3792: 	    my ($v,$symb,$param) = split(/:/,$key);
                   3793: 	    next if ($v eq 'version' || $symb eq 'keys');
                   3794: 	    next if (exists($data{$symb}) && 
                   3795: 		     exists($data{$symb}->{$param}) &&
                   3796: 		     $data{$symb}->{'v.'.$param} > $v);
                   3797: 	    $data{$symb}->{$param}=$value;
                   3798: 	    $data{$symb}->{'v.'.$param}=$v;
                   3799: 	}
1.311     albertel 3800: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3801: 	    while (my ($symb,$param_hash) = each(%data)) {
                   3802: 		while(my ($param,$value) = each (%$param_hash)){
                   3803: 		    next if ($param =~ /^v\./);       # Ignore versions...
                   3804: 		    #
                   3805: 		    #   Just dump the symb=value pairs separated by &
                   3806: 		    #
                   3807: 		    $qresult.=$symb.':'.$param.'='.$value.'&';
                   3808: 		}
                   3809: 	    }
                   3810: 	    chop($qresult);
1.387     albertel 3811: 	    &Reply($client , \$qresult, $userinput);
1.231     foxr     3812: 	} else {
                   3813: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3814: 		     "while attempting currentdump\n", $userinput);
                   3815: 	}
                   3816:     } else {
                   3817: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3818: 		"while attempting currentdump\n", $userinput);
                   3819:     }
                   3820: 
                   3821:     return 1;
                   3822: }
                   3823: &register_handler("currentdump", \&dump_profile_database, 0, 1, 0);
                   3824: 
                   3825: #
                   3826: #   Dump a profile database with an optional regular expression
                   3827: #   to match against the keys.  In this dump, no effort is made
                   3828: #   to separate symb from version information. Presumably the
                   3829: #   databases that are dumped by this command are of a different
                   3830: #   structure.  Need to look at this and improve the documentation of
                   3831: #   both this and the currentdump handler.
                   3832: # Parameters:
                   3833: #    $cmd                     - The command keyword.
                   3834: #    $tail                    - All of the characters after the $cmd:
                   3835: #                               These are expected to be a colon
                   3836: #                               separated list containing:
                   3837: #                               domain/user - identifying the user.
                   3838: #                               namespace   - identifying the database.
                   3839: #                               regexp      - optional regular expression
                   3840: #                                             that is matched against
                   3841: #                                             database keywords to do
                   3842: #                                             selective dumps.
1.488     raeburn  3843: #                               range       - optional range of entries
                   3844: #                                             e.g., 10-20 would return the
                   3845: #                                             10th to 19th items, etc.  
1.231     foxr     3846: #   $client                   - Channel open on the client.
                   3847: # Returns:
                   3848: #    1    - Continue processing.
                   3849: # Side effects:
                   3850: #    response is written to $client.
                   3851: #
                   3852: sub dump_with_regexp {
                   3853:     my ($cmd, $tail, $client) = @_;
                   3854: 
1.494     droeschl 3855:     my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
1.490     droeschl 3856:     
                   3857:     if ($res =~ /^error:/) {
                   3858:         Failure($client, \$res, "$cmd:$tail");
                   3859:     } else {
                   3860:         Reply($client, \$res, "$cmd:$tail");
                   3861:     }
1.231     foxr     3862: 
                   3863:     return 1;
                   3864: }
                   3865: &register_handler("dump", \&dump_with_regexp, 0, 1, 0);
                   3866: 
1.568     raeburn  3867: #
                   3868: #  Process the encrypted dump request. Original call should
                   3869: #  be from lonnet::dump() with seventh arg ($encrypt) set to
                   3870: #  1, to ensure that both request and response are encrypted.
                   3871: #
                   3872: #  Parameters:
                   3873: #     $cmd               - Command keyword of request (edump).
                   3874: #     $tail              - Tail of the command.
                   3875: #                          See &dump_with_regexp for more
                   3876: #                          information about this.
                   3877: #     $client            - File open on the client.
                   3878: #  Returns:
                   3879: #     1      - Continue processing
                   3880: #     0      - server should exit.
                   3881: #
                   3882: 
                   3883: sub encrypted_dump_with_regexp {
                   3884:     my ($cmd, $tail, $client) = @_;
                   3885:     my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
                   3886: 
                   3887:     if ($res =~ /^error:/) {
                   3888:         Failure($client, \$res, "$cmd:$tail");
                   3889:     } else {
                   3890:         if ($cipher) {
                   3891:             my $cmdlength=length($res);
                   3892:             $res.="         ";
                   3893:             my $encres='';
                   3894:             for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   3895:                 $encres.= unpack("H16",
                   3896:                                  $cipher->encrypt(substr($res,
                   3897:                                                          $encidx,
                   3898:                                                          8)));
                   3899:             }
                   3900:             &Reply( $client,"enc:$cmdlength:$encres\n","$cmd:$tail");
                   3901:         } else {
                   3902:             &Failure( $client, "error:no_key\n","$cmd:$tail");
                   3903:         }
                   3904:     }
                   3905: }
                   3906: &register_handler("edump", \&encrypted_dump_with_regexp, 0, 1, 0);
                   3907: 
1.231     foxr     3908: #  Store a set of key=value pairs associated with a versioned name.
                   3909: #
                   3910: #  Parameters:
                   3911: #    $cmd                - Request command keyword.
                   3912: #    $tail               - Tail of the request.  This is a colon
                   3913: #                          separated list containing:
                   3914: #                          domain/user - User and authentication domain.
                   3915: #                          namespace   - Name of the database being modified
                   3916: #                          rid         - Resource keyword to modify.
                   3917: #                          what        - new value associated with rid.
1.512     raeburn  3918: #                          laststore   - (optional) version=timestamp
                   3919: #                                        for most recent transaction for rid
                   3920: #                                        in namespace, when cstore was called
1.231     foxr     3921: #
                   3922: #    $client             - Socket open on the client.
                   3923: #
                   3924: #
                   3925: #  Returns:
                   3926: #      1 (keep on processing).
                   3927: #  Side-Effects:
                   3928: #    Writes to the client
1.512     raeburn  3929: #    Successful storage will cause either 'ok', or, if $laststore was included
                   3930: #    in the tail of the request, and the version number for the last transaction
                   3931: #    is larger than the version in $laststore, delay:$numtrans , where $numtrans
                   3932: #    is the number of store evevnts recorded for rid in namespace since
                   3933: #    lonnet::store() was called by the client.
                   3934: #
1.231     foxr     3935: sub store_handler {
                   3936:     my ($cmd, $tail, $client) = @_;
                   3937:  
                   3938:     my $userinput = "$cmd:$tail";
1.512     raeburn  3939:     chomp($tail);
                   3940:     my ($udom,$uname,$namespace,$rid,$what,$laststore) =split(/:/,$tail);
1.231     foxr     3941:     if ($namespace ne 'roles') {
                   3942: 
                   3943: 	my @pairs=split(/\&/,$what);
                   3944: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
1.268     albertel 3945: 				       &GDBM_WRCREAT(), "S",
1.231     foxr     3946: 				       "$rid:$what");
                   3947: 	if ($hashref) {
                   3948: 	    my $now = time;
1.512     raeburn  3949:             my $numtrans;
                   3950:             if ($laststore) {
                   3951:                 my ($previousversion,$previoustime) = split(/\=/,$laststore);
                   3952:                 my ($lastversion,$lasttime) = (0,0);
                   3953:                 $lastversion = $hashref->{"version:$rid"};
                   3954:                 if ($lastversion) {
                   3955:                     $lasttime = $hashref->{"$lastversion:$rid:timestamp"};
                   3956:                 }
                   3957:                 if (($previousversion) && ($previousversion !~ /\D/)) {
                   3958:                     if (($lastversion > $previousversion) && ($lasttime >= $previoustime)) {
                   3959:                         $numtrans = $lastversion - $previousversion;
                   3960:                     }
                   3961:                 } elsif ($lastversion) {
                   3962:                     $numtrans = $lastversion;
                   3963:                 }
                   3964:                 if ($numtrans) {
                   3965:                     $numtrans =~ s/D//g;
                   3966:                 }
                   3967:             }
1.231     foxr     3968: 	    $hashref->{"version:$rid"}++;
                   3969: 	    my $version=$hashref->{"version:$rid"};
                   3970: 	    my $allkeys=''; 
                   3971: 	    foreach my $pair (@pairs) {
                   3972: 		my ($key,$value)=split(/=/,$pair);
                   3973: 		$allkeys.=$key.':';
                   3974: 		$hashref->{"$version:$rid:$key"}=$value;
                   3975: 	    }
                   3976: 	    $hashref->{"$version:$rid:timestamp"}=$now;
                   3977: 	    $allkeys.='timestamp';
                   3978: 	    $hashref->{"$version:keys:$rid"}=$allkeys;
1.311     albertel 3979: 	    if (&untie_user_hash($hashref)) {
1.512     raeburn  3980:                 my $msg = 'ok';
                   3981:                 if ($numtrans) {
                   3982:                     $msg = 'delay:'.$numtrans;
                   3983:                 }
                   3984: 		&Reply($client, "$msg\n", $userinput);
1.231     foxr     3985: 	    } else {
                   3986: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3987: 			"while attempting store\n", $userinput);
                   3988: 	    }
                   3989: 	} else {
                   3990: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3991: 		     "while attempting store\n", $userinput);
                   3992: 	}
                   3993:     } else {
                   3994: 	&Failure($client, "refused\n", $userinput);
                   3995:     }
                   3996: 
                   3997:     return 1;
                   3998: }
                   3999: &register_handler("store", \&store_handler, 0, 1, 0);
1.263     albertel 4000: 
1.323     albertel 4001: #  Modify a set of key=value pairs associated with a versioned name.
                   4002: #
                   4003: #  Parameters:
                   4004: #    $cmd                - Request command keyword.
                   4005: #    $tail               - Tail of the request.  This is a colon
                   4006: #                          separated list containing:
                   4007: #                          domain/user - User and authentication domain.
                   4008: #                          namespace   - Name of the database being modified
                   4009: #                          rid         - Resource keyword to modify.
                   4010: #                          v           - Version item to modify
                   4011: #                          what        - new value associated with rid.
                   4012: #
                   4013: #    $client             - Socket open on the client.
                   4014: #
                   4015: #
                   4016: #  Returns:
                   4017: #      1 (keep on processing).
                   4018: #  Side-Effects:
                   4019: #    Writes to the client
                   4020: sub putstore_handler {
                   4021:     my ($cmd, $tail, $client) = @_;
                   4022:  
                   4023:     my $userinput = "$cmd:$tail";
                   4024: 
                   4025:     my ($udom,$uname,$namespace,$rid,$v,$what) =split(/:/,$tail);
                   4026:     if ($namespace ne 'roles') {
                   4027: 
                   4028: 	chomp($what);
                   4029: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
                   4030: 				       &GDBM_WRCREAT(), "M",
                   4031: 				       "$rid:$v:$what");
                   4032: 	if ($hashref) {
                   4033: 	    my $now = time;
                   4034: 	    my %data = &hash_extract($what);
                   4035: 	    my @allkeys;
                   4036: 	    while (my($key,$value) = each(%data)) {
                   4037: 		push(@allkeys,$key);
                   4038: 		$hashref->{"$v:$rid:$key"} = $value;
                   4039: 	    }
                   4040: 	    my $allkeys = join(':',@allkeys);
                   4041: 	    $hashref->{"$v:keys:$rid"}=$allkeys;
                   4042: 
                   4043: 	    if (&untie_user_hash($hashref)) {
                   4044: 		&Reply($client, "ok\n", $userinput);
                   4045: 	    } else {
                   4046: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4047: 			"while attempting store\n", $userinput);
                   4048: 	    }
                   4049: 	} else {
                   4050: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4051: 		     "while attempting store\n", $userinput);
                   4052: 	}
                   4053:     } else {
                   4054: 	&Failure($client, "refused\n", $userinput);
                   4055:     }
                   4056: 
                   4057:     return 1;
                   4058: }
                   4059: &register_handler("putstore", \&putstore_handler, 0, 1, 0);
                   4060: 
                   4061: sub hash_extract {
                   4062:     my ($str)=@_;
                   4063:     my %hash;
                   4064:     foreach my $pair (split(/\&/,$str)) {
                   4065: 	my ($key,$value)=split(/=/,$pair);
                   4066: 	$hash{$key}=$value;
                   4067:     }
                   4068:     return (%hash);
                   4069: }
                   4070: sub hash_to_str {
                   4071:     my ($hash_ref)=@_;
                   4072:     my $str;
                   4073:     foreach my $key (keys(%$hash_ref)) {
                   4074: 	$str.=$key.'='.$hash_ref->{$key}.'&';
                   4075:     }
                   4076:     $str=~s/\&$//;
                   4077:     return $str;
                   4078: }
                   4079: 
1.231     foxr     4080: #
                   4081: #  Dump out all versions of a resource that has key=value pairs associated
                   4082: # with it for each version.  These resources are built up via the store
                   4083: # command.
                   4084: #
                   4085: #  Parameters:
                   4086: #     $cmd               - Command keyword.
                   4087: #     $tail              - Remainder of the request which consists of:
                   4088: #                          domain/user   - User and auth. domain.
                   4089: #                          namespace     - name of resource database.
                   4090: #                          rid           - Resource id.
                   4091: #    $client             - socket open on the client.
                   4092: #
                   4093: # Returns:
                   4094: #      1  indicating the caller should not yet exit.
                   4095: # Side-effects:
                   4096: #   Writes a reply to the client.
                   4097: #   The reply is a string of the following shape:
                   4098: #   version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
                   4099: #    Where the 1 above represents version 1.
                   4100: #    this continues for all pairs of keys in all versions.
                   4101: #
                   4102: #
                   4103: #    
                   4104: #
                   4105: sub restore_handler {
                   4106:     my ($cmd, $tail, $client) = @_;
                   4107: 
                   4108:     my $userinput = "$cmd:$tail";	# Only used for logging purposes.
1.351     banghart 4109:     my ($udom,$uname,$namespace,$rid) = split(/:/,$tail);
1.352     albertel 4110:     $namespace=~s/\//\_/g;
1.350     albertel 4111:     $namespace = &LONCAPA::clean_username($namespace);
1.349     albertel 4112: 
1.231     foxr     4113:     chomp($rid);
                   4114:     my $qresult='';
1.309     albertel 4115:     my $hashref = &tie_user_hash($udom, $uname, $namespace, &GDBM_READER());
                   4116:     if ($hashref) {
                   4117: 	my $version=$hashref->{"version:$rid"};
1.231     foxr     4118: 	$qresult.="version=$version&";
                   4119: 	my $scope;
                   4120: 	for ($scope=1;$scope<=$version;$scope++) {
1.309     albertel 4121: 	    my $vkeys=$hashref->{"$scope:keys:$rid"};
1.231     foxr     4122: 	    my @keys=split(/:/,$vkeys);
                   4123: 	    my $key;
                   4124: 	    $qresult.="$scope:keys=$vkeys&";
                   4125: 	    foreach $key (@keys) {
1.309     albertel 4126: 		$qresult.="$scope:$key=".$hashref->{"$scope:$rid:$key"}."&";
1.231     foxr     4127: 	    }                                  
                   4128: 	}
1.311     albertel 4129: 	if (&untie_user_hash($hashref)) {
1.231     foxr     4130: 	    $qresult=~s/\&$//;
1.387     albertel 4131: 	    &Reply( $client, \$qresult, $userinput);
1.231     foxr     4132: 	} else {
                   4133: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4134: 		    "while attempting restore\n", $userinput);
                   4135: 	}
                   4136:     } else {
                   4137: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4138: 		"while attempting restore\n", $userinput);
                   4139:     }
                   4140:   
                   4141:     return 1;
                   4142: 
                   4143: 
                   4144: }
                   4145: &register_handler("restore", \&restore_handler, 0,1,0);
1.234     foxr     4146: 
                   4147: #
1.324     raeburn  4148: #   Add a chat message to a synchronous discussion board.
1.234     foxr     4149: #
                   4150: # Parameters:
                   4151: #    $cmd                - Request keyword.
                   4152: #    $tail               - Tail of the command. A colon separated list
                   4153: #                          containing:
                   4154: #                          cdom    - Domain on which the chat board lives
1.324     raeburn  4155: #                          cnum    - Course containing the chat board.
                   4156: #                          newpost - Body of the posting.
                   4157: #                          group   - Optional group, if chat board is only 
                   4158: #                                    accessible in a group within the course 
1.234     foxr     4159: #   $client              - Socket open on the client.
                   4160: # Returns:
                   4161: #   1    - Indicating caller should keep on processing.
                   4162: #
                   4163: # Side-effects:
                   4164: #   writes a reply to the client.
                   4165: #
                   4166: #
                   4167: sub send_chat_handler {
                   4168:     my ($cmd, $tail, $client) = @_;
                   4169: 
                   4170:     
                   4171:     my $userinput = "$cmd:$tail";
                   4172: 
1.324     raeburn  4173:     my ($cdom,$cnum,$newpost,$group)=split(/\:/,$tail);
                   4174:     &chat_add($cdom,$cnum,$newpost,$group);
1.234     foxr     4175:     &Reply($client, "ok\n", $userinput);
                   4176: 
                   4177:     return 1;
                   4178: }
                   4179: &register_handler("chatsend", \&send_chat_handler, 0, 1, 0);
1.263     albertel 4180: 
1.234     foxr     4181: #
1.324     raeburn  4182: #   Retrieve the set of chat messages from a discussion board.
1.234     foxr     4183: #
                   4184: #  Parameters:
                   4185: #    $cmd             - Command keyword that initiated the request.
                   4186: #    $tail            - Remainder of the request after the command
                   4187: #                       keyword.  In this case a colon separated list of
                   4188: #                       chat domain    - Which discussion board.
                   4189: #                       chat id        - Discussion thread(?)
                   4190: #                       domain/user    - Authentication domain and username
                   4191: #                                        of the requesting person.
1.324     raeburn  4192: #                       group          - Optional course group containing
                   4193: #                                        the board.      
1.234     foxr     4194: #   $client           - Socket open on the client program.
                   4195: # Returns:
                   4196: #    1     - continue processing
                   4197: # Side effects:
                   4198: #    Response is written to the client.
                   4199: #
                   4200: sub retrieve_chat_handler {
                   4201:     my ($cmd, $tail, $client) = @_;
                   4202: 
                   4203: 
                   4204:     my $userinput = "$cmd:$tail";
                   4205: 
1.324     raeburn  4206:     my ($cdom,$cnum,$udom,$uname,$group)=split(/\:/,$tail);
1.234     foxr     4207:     my $reply='';
1.324     raeburn  4208:     foreach (&get_chat($cdom,$cnum,$udom,$uname,$group)) {
1.234     foxr     4209: 	$reply.=&escape($_).':';
                   4210:     }
                   4211:     $reply=~s/\:$//;
1.387     albertel 4212:     &Reply($client, \$reply, $userinput);
1.234     foxr     4213: 
                   4214: 
                   4215:     return 1;
                   4216: }
                   4217: &register_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
                   4218: 
                   4219: #
                   4220: #  Initiate a query of an sql database.  SQL query repsonses get put in
                   4221: #  a file for later retrieval.  This prevents sql query results from
                   4222: #  bottlenecking the system.  Note that with loncnew, perhaps this is
                   4223: #  less of an issue since multiple outstanding requests can be concurrently
                   4224: #  serviced.
                   4225: #
                   4226: #  Parameters:
1.535     raeburn  4227: #     $cmd       - Command keyword that initiated the request.
1.234     foxr     4228: #     $tail      - Remainder of the command after the keyword.
                   4229: #                  For this function, this consists of a query and
                   4230: #                  3 arguments that are self-documentingly labelled
                   4231: #                  in the original arg1, arg2, arg3.
                   4232: #     $client    - Socket open on the client.
                   4233: # Return:
                   4234: #    1   - Indicating processing should continue.
                   4235: # Side-effects:
                   4236: #    a reply is written to $client.
                   4237: #
                   4238: sub send_query_handler {
                   4239:     my ($cmd, $tail, $client) = @_;
                   4240: 
                   4241:     my $userinput = "$cmd:$tail";
                   4242: 
                   4243:     my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
                   4244:     $query=~s/\n*$//g;
1.534     raeburn  4245:     if (($query eq 'usersearch') || ($query eq 'instdirsearch')) {
                   4246:         my $usersearchconf = &get_usersearch_config($currentdomainid,'directorysrch');
                   4247:         my $earlyout;
                   4248:         if (ref($usersearchconf) eq 'HASH') {
                   4249:             if ($currentdomainid eq $clienthomedom) {
                   4250:                 if ($query eq 'usersearch') {
                   4251:                     if ($usersearchconf->{'lcavailable'} eq '0') {
                   4252:                         $earlyout = 1;
                   4253:                     }
                   4254:                 } else {
                   4255:                     if ($usersearchconf->{'available'} eq '0') {
                   4256:                         $earlyout = 1;
                   4257:                     }
                   4258:                 }
                   4259:             } else {
                   4260:                 if ($query eq 'usersearch') {
                   4261:                     if ($usersearchconf->{'lclocalonly'}) {
                   4262:                         $earlyout = 1;
                   4263:                     }
                   4264:                 } else {
                   4265:                     if ($usersearchconf->{'localonly'}) {
                   4266:                         $earlyout = 1;
                   4267:                     }
                   4268:                 }
                   4269:             }
                   4270:         }
                   4271:         if ($earlyout) {
                   4272:             &Reply($client, "query_not_authorized\n");
                   4273:             return 1;
                   4274:         }
                   4275:     }
1.234     foxr     4276:     &Reply($client, "". &sql_reply("$clientname\&$query".
                   4277: 				"\&$arg1"."\&$arg2"."\&$arg3")."\n",
                   4278: 	  $userinput);
                   4279:     
                   4280:     return 1;
                   4281: }
                   4282: &register_handler("querysend", \&send_query_handler, 0, 1, 0);
                   4283: 
                   4284: #
                   4285: #   Add a reply to an sql query.  SQL queries are done asyncrhonously.
                   4286: #   The query is submitted via a "querysend" transaction.
                   4287: #   There it is passed on to the lonsql daemon, queued and issued to
                   4288: #   mysql.
                   4289: #     This transaction is invoked when the sql transaction is complete
                   4290: #   it stores the query results in flie and indicates query completion.
                   4291: #   presumably local software then fetches this response... I'm guessing
                   4292: #   the sequence is: lonc does a querysend, we ask lonsql to do it.
                   4293: #   lonsql on completion of the query interacts with the lond of our
                   4294: #   client to do a query reply storing two files:
                   4295: #    - id     - The results of the query.
                   4296: #    - id.end - Indicating the transaction completed. 
                   4297: #    NOTE: id is a unique id assigned to the query and querysend time.
                   4298: # Parameters:
                   4299: #    $cmd        - Command keyword that initiated this request.
                   4300: #    $tail       - Remainder of the tail.  In this case that's a colon
                   4301: #                  separated list containing the query Id and the 
                   4302: #                  results of the query.
                   4303: #    $client     - Socket open on the client.
                   4304: # Return:
                   4305: #    1           - Indicating that we should continue processing.
                   4306: # Side effects:
                   4307: #    ok written to the client.
                   4308: #
                   4309: sub reply_query_handler {
                   4310:     my ($cmd, $tail, $client) = @_;
                   4311: 
                   4312: 
                   4313:     my $userinput = "$cmd:$tail";
                   4314: 
1.339     albertel 4315:     my ($id,$reply)=split(/:/,$tail); 
1.234     foxr     4316:     my $store;
                   4317:     my $execdir=$perlvar{'lonDaemons'};
                   4318:     if ($store=IO::File->new(">$execdir/tmp/$id")) {
                   4319: 	$reply=~s/\&/\n/g;
                   4320: 	print $store $reply;
                   4321: 	close $store;
                   4322: 	my $store2=IO::File->new(">$execdir/tmp/$id.end");
                   4323: 	print $store2 "done\n";
                   4324: 	close $store2;
                   4325: 	&Reply($client, "ok\n", $userinput);
                   4326:     } else {
                   4327: 	&Failure($client, "error: ".($!+0)
                   4328: 		." IO::File->new Failed ".
                   4329: 		"while attempting queryreply\n", $userinput);
                   4330:     }
                   4331:  
                   4332: 
                   4333:     return 1;
                   4334: }
                   4335: &register_handler("queryreply", \&reply_query_handler, 0, 1, 0);
                   4336: 
                   4337: #
                   4338: #  Process the courseidput request.  Not quite sure what this means
                   4339: #  at the system level sense.  It appears a gdbm file in the 
                   4340: #  /home/httpd/lonUsers/$domain/nohist_courseids is tied and
                   4341: #  a set of entries made in that database.
                   4342: #
                   4343: # Parameters:
                   4344: #   $cmd      - The command keyword that initiated this request.
                   4345: #   $tail     - Tail of the command.  In this case consists of a colon
                   4346: #               separated list contaning the domain to apply this to and
                   4347: #               an ampersand separated list of keyword=value pairs.
1.272     raeburn  4348: #               Each value is a colon separated list that includes:  
                   4349: #               description, institutional code and course owner.
                   4350: #               For backward compatibility with versions included
                   4351: #               in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
                   4352: #               code and/or course owner are preserved from the existing 
                   4353: #               record when writing a new record in response to 1.1 or 
                   4354: #               1.2 implementations of lonnet::flushcourselogs().   
                   4355: #                      
1.234     foxr     4356: #   $client   - Socket open on the client.
                   4357: # Returns:
                   4358: #   1    - indicating that processing should continue
                   4359: #
                   4360: # Side effects:
                   4361: #   reply is written to the client.
                   4362: #
                   4363: sub put_course_id_handler {
                   4364:     my ($cmd, $tail, $client) = @_;
                   4365: 
                   4366: 
                   4367:     my $userinput = "$cmd:$tail";
                   4368: 
1.266     raeburn  4369:     my ($udom, $what) = split(/:/, $tail,2);
1.234     foxr     4370:     chomp($what);
                   4371:     my $now=time;
                   4372:     my @pairs=split(/\&/,$what);
                   4373: 
                   4374:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   4375:     if ($hashref) {
                   4376: 	foreach my $pair (@pairs) {
1.271     raeburn  4377:             my ($key,$courseinfo) = split(/=/,$pair,2);
                   4378:             $courseinfo =~ s/=/:/g;
1.384     raeburn  4379:             if (defined($hashref->{$key})) {
                   4380:                 my $value = &Apache::lonnet::thaw_unescape($hashref->{$key});
                   4381:                 if (ref($value) eq 'HASH') {
                   4382:                     my @items = ('description','inst_code','owner','type');
                   4383:                     my @new_items = split(/:/,$courseinfo,-1);
                   4384:                     my %storehash; 
                   4385:                     for (my $i=0; $i<@new_items; $i++) {
1.391     raeburn  4386:                         $storehash{$items[$i]} = &unescape($new_items[$i]);
1.384     raeburn  4387:                     }
                   4388:                     $hashref->{$key} = 
                   4389:                         &Apache::lonnet::freeze_escape(\%storehash);
                   4390:                     my $unesc_key = &unescape($key);
                   4391:                     $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
                   4392:                     next;
1.383     raeburn  4393:                 }
1.384     raeburn  4394:             }
                   4395:             my @current_items = split(/:/,$hashref->{$key},-1);
                   4396:             shift(@current_items); # remove description
                   4397:             pop(@current_items);   # remove last access
                   4398:             my $numcurrent = scalar(@current_items);
                   4399:             if ($numcurrent > 3) {
                   4400:                 $numcurrent = 3;
                   4401:             }
                   4402:             my @new_items = split(/:/,$courseinfo,-1);
                   4403:             my $numnew = scalar(@new_items);
                   4404:             if ($numcurrent > 0) {
                   4405:                 if ($numnew <= $numcurrent) { # flushcourselogs() from pre 2.2 
                   4406:                     for (my $j=$numcurrent-$numnew; $j>=0; $j--) {
                   4407:                         $courseinfo .= ':'.$current_items[$numcurrent-$j-1];
1.333     raeburn  4408:                     }
1.272     raeburn  4409:                 }
                   4410:             }
1.384     raeburn  4411:             $hashref->{$key}=$courseinfo.':'.$now;
1.234     foxr     4412: 	}
1.311     albertel 4413: 	if (&untie_domain_hash($hashref)) {
1.253     foxr     4414: 	    &Reply( $client, "ok\n", $userinput);
1.234     foxr     4415: 	} else {
1.253     foxr     4416: 	    &Failure($client, "error: ".($!+0)
1.234     foxr     4417: 		     ." untie(GDBM) Failed ".
                   4418: 		     "while attempting courseidput\n", $userinput);
                   4419: 	}
                   4420:     } else {
1.253     foxr     4421: 	&Failure($client, "error: ".($!+0)
1.234     foxr     4422: 		 ." tie(GDBM) Failed ".
                   4423: 		 "while attempting courseidput\n", $userinput);
                   4424:     }
                   4425: 
                   4426:     return 1;
                   4427: }
                   4428: &register_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
                   4429: 
1.383     raeburn  4430: sub put_course_id_hash_handler {
                   4431:     my ($cmd, $tail, $client) = @_;
                   4432:     my $userinput = "$cmd:$tail";
1.384     raeburn  4433:     my ($udom,$mode,$what) = split(/:/, $tail,3);
1.383     raeburn  4434:     chomp($what);
                   4435:     my $now=time;
                   4436:     my @pairs=split(/\&/,$what);
1.384     raeburn  4437:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
1.383     raeburn  4438:     if ($hashref) {
                   4439:         foreach my $pair (@pairs) {
                   4440:             my ($key,$value)=split(/=/,$pair);
1.384     raeburn  4441:             my $unesc_key = &unescape($key);
                   4442:             if ($mode ne 'timeonly') {
                   4443:                 if (!defined($hashref->{&escape('lasttime:'.$unesc_key)})) {
                   4444:                     my $curritems = &Apache::lonnet::thaw_unescape($key); 
                   4445:                     if (ref($curritems) ne 'HASH') {
                   4446:                         my @current_items = split(/:/,$hashref->{$key},-1);
                   4447:                         my $lasttime = pop(@current_items);
                   4448:                         $hashref->{&escape('lasttime:'.$unesc_key)} = $lasttime;
                   4449:                     } else {
                   4450:                         $hashref->{&escape('lasttime:'.$unesc_key)} = '';
                   4451:                     }
                   4452:                 } 
                   4453:                 $hashref->{$key} = $value;
                   4454:             }
                   4455:             if ($mode ne 'notime') {
                   4456:                 $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
                   4457:             }
1.383     raeburn  4458:         }
                   4459:         if (&untie_domain_hash($hashref)) {
                   4460:             &Reply($client, "ok\n", $userinput);
                   4461:         } else {
                   4462:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4463:                      "while attempting courseidputhash\n", $userinput);
                   4464:         }
                   4465:     } else {
                   4466:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4467:                   "while attempting courseidputhash\n", $userinput);
                   4468:     }
                   4469:     return 1;
                   4470: }
                   4471: &register_handler("courseidputhash", \&put_course_id_hash_handler, 0, 1, 0);
                   4472: 
1.234     foxr     4473: #  Retrieves the value of a course id resource keyword pattern
                   4474: #  defined since a starting date.  Both the starting date and the
                   4475: #  keyword pattern are optional.  If the starting date is not supplied it
                   4476: #  is treated as the beginning of time.  If the pattern is not found,
                   4477: #  it is treatred as "." matching everything.
                   4478: #
                   4479: #  Parameters:
                   4480: #     $cmd     - Command keyword that resulted in us being dispatched.
                   4481: #     $tail    - The remainder of the command that, in this case, consists
                   4482: #                of a colon separated list of:
                   4483: #                 domain   - The domain in which the course database is 
                   4484: #                            defined.
                   4485: #                 since    - Optional parameter describing the minimum
                   4486: #                            time of definition(?) of the resources that
                   4487: #                            will match the dump.
                   4488: #                 description - regular expression that is used to filter
                   4489: #                            the dump.  Only keywords matching this regexp
                   4490: #                            will be used.
1.272     raeburn  4491: #                 institutional code - optional supplied code to filter 
                   4492: #                            the dump. Only courses with an institutional code 
                   4493: #                            that match the supplied code will be returned.
1.336     raeburn  4494: #                 owner    - optional supplied username and domain of owner to
                   4495: #                            filter the dump.  Only courses for which the course
                   4496: #                            owner matches the supplied username and/or domain
                   4497: #                            will be returned. Pre-2.2.0 legacy entries from 
                   4498: #                            nohist_courseiddump will only contain usernames.
1.384     raeburn  4499: #                 type     - optional parameter for selection 
1.418     raeburn  4500: #                 regexp_ok - if 1 or -1 allow the supplied institutional code
                   4501: #                            filter to behave as a regular expression:
                   4502: #	                      1 will not exclude the course if the instcode matches the RE 
                   4503: #                            -1 will exclude the course if the instcode matches the RE
1.384     raeburn  4504: #                 rtn_as_hash - whether to return the information available for
                   4505: #                            each matched item as a frozen hash of all 
                   4506: #                            key, value pairs in the item's hash, or as a 
                   4507: #                            colon-separated list of (in order) description,
                   4508: #                            institutional code, and course owner.
1.404     raeburn  4509: #                 selfenrollonly - filter by courses allowing self-enrollment  
                   4510: #                                  now or in the future (selfenrollonly = 1).
                   4511: #                 catfilter - filter by course category, assigned to a course 
                   4512: #                             using manually defined categories (i.e., not
1.407     raeburn  4513: #                             self-cataloging based on on institutional code).   
1.404     raeburn  4514: #                 showhidden - include course in results even if course  
1.407     raeburn  4515: #                              was set to be excluded from course catalog (DC only).
1.404     raeburn  4516: #                 caller -  if set to 'coursecatalog', courses set to be hidden
                   4517: #                           from course catalog will be excluded from results (unless
                   4518: #                           overridden by "showhidden".
1.427     raeburn  4519: #                 cloner - escaped username:domain of course cloner (if picking course to
1.419     raeburn  4520: #                          clone).
                   4521: #                 cc_clone_list - escaped comma separated list of courses for which 
                   4522: #                                 course cloner has active CC role (and so can clone
                   4523: #                                 automatically).
1.427     raeburn  4524: #                 cloneonly - filter by courses for which cloner has rights to clone.
                   4525: #                 createdbefore - include courses for which creation date preceeded this date.
                   4526: #                 createdafter - include courses for which creation date followed this date.
                   4527: #                 creationcontext - include courses created in specified context 
1.404     raeburn  4528: #
1.445     raeburn  4529: #                 domcloner - flag to indicate if user can create CCs in course's domain.
1.505     raeburn  4530: #                             If so, ability to clone course is automatic.
                   4531: #                 hasuniquecode - filter by courses for which a six character unique code has 
                   4532: #                                 been set.
1.445     raeburn  4533: #
1.234     foxr     4534: #     $client  - The socket open on the client.
                   4535: # Returns:
                   4536: #    1     - Continue processing.
                   4537: # Side Effects:
                   4538: #   a reply is written to $client.
                   4539: sub dump_course_id_handler {
                   4540:     my ($cmd, $tail, $client) = @_;
1.494     droeschl 4541: 
                   4542:     my $res = LONCAPA::Lond::dump_course_id_handler($tail);
                   4543:     if ($res =~ /^error:/) {
                   4544:         Failure($client, \$res, "$cmd:$tail");
                   4545:     } else {
                   4546:         Reply($client, \$res, "$cmd:$tail");
                   4547:     }
                   4548: 
                   4549:     return 1;  
                   4550: 
                   4551:     #TODO remove
1.234     foxr     4552:     my $userinput = "$cmd:$tail";
                   4553: 
1.333     raeburn  4554:     my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter,
1.404     raeburn  4555:         $typefilter,$regexp_ok,$rtn_as_hash,$selfenrollonly,$catfilter,$showhidden,
1.427     raeburn  4556:         $caller,$cloner,$cc_clone_list,$cloneonly,$createdbefore,$createdafter,
1.505     raeburn  4557:         $creationcontext,$domcloner,$hasuniquecode) =split(/:/,$tail);
1.397     raeburn  4558:     my $now = time;
1.419     raeburn  4559:     my ($cloneruname,$clonerudom,%cc_clone);
1.234     foxr     4560:     if (defined($description)) {
                   4561: 	$description=&unescape($description);
                   4562:     } else {
                   4563: 	$description='.';
                   4564:     }
1.266     raeburn  4565:     if (defined($instcodefilter)) {
                   4566:         $instcodefilter=&unescape($instcodefilter);
                   4567:     } else {
                   4568:         $instcodefilter='.';
                   4569:     }
1.336     raeburn  4570:     my ($ownerunamefilter,$ownerdomfilter);
1.266     raeburn  4571:     if (defined($ownerfilter)) {
                   4572:         $ownerfilter=&unescape($ownerfilter);
1.336     raeburn  4573:         if ($ownerfilter ne '.' && defined($ownerfilter)) {
                   4574:             if ($ownerfilter =~ /^([^:]*):([^:]*)$/) {
                   4575:                  $ownerunamefilter = $1;
                   4576:                  $ownerdomfilter = $2;
                   4577:             } else {
                   4578:                 $ownerunamefilter = $ownerfilter;
                   4579:                 $ownerdomfilter = '';
                   4580:             }
                   4581:         }
1.266     raeburn  4582:     } else {
                   4583:         $ownerfilter='.';
                   4584:     }
1.336     raeburn  4585: 
1.282     raeburn  4586:     if (defined($coursefilter)) {
                   4587:         $coursefilter=&unescape($coursefilter);
                   4588:     } else {
                   4589:         $coursefilter='.';
                   4590:     }
1.333     raeburn  4591:     if (defined($typefilter)) {
                   4592:         $typefilter=&unescape($typefilter);
                   4593:     } else {
                   4594:         $typefilter='.';
                   4595:     }
1.344     raeburn  4596:     if (defined($regexp_ok)) {
                   4597:         $regexp_ok=&unescape($regexp_ok);
                   4598:     }
1.401     raeburn  4599:     if (defined($catfilter)) {
                   4600:         $catfilter=&unescape($catfilter);
                   4601:     }
1.419     raeburn  4602:     if (defined($cloner)) {
                   4603:         $cloner = &unescape($cloner);
                   4604:         ($cloneruname,$clonerudom) = ($cloner =~ /^($LONCAPA::match_username):($LONCAPA::match_domain)$/); 
                   4605:     }
                   4606:     if (defined($cc_clone_list)) {
                   4607:         $cc_clone_list = &unescape($cc_clone_list);
                   4608:         my @cc_cloners = split('&',$cc_clone_list);
                   4609:         foreach my $cid (@cc_cloners) {
                   4610:             my ($clonedom,$clonenum) = split(':',$cid);
                   4611:             next if ($clonedom ne $udom); 
                   4612:             $cc_clone{$clonedom.'_'.$clonenum} = 1;
                   4613:         } 
                   4614:     }
1.431     raeburn  4615:     if ($createdbefore ne '') {
1.427     raeburn  4616:         $createdbefore = &unescape($createdbefore);
                   4617:     } else {
                   4618:        $createdbefore = 0;
                   4619:     }
1.431     raeburn  4620:     if ($createdafter ne '') {
1.427     raeburn  4621:         $createdafter = &unescape($createdafter);
                   4622:     } else {
                   4623:         $createdafter = 0;
                   4624:     }
1.431     raeburn  4625:     if ($creationcontext ne '') {
1.427     raeburn  4626:         $creationcontext = &unescape($creationcontext);
                   4627:     } else {
                   4628:         $creationcontext = '.';
                   4629:     }
1.505     raeburn  4630:     unless ($hasuniquecode) {
                   4631:         $hasuniquecode = '.';
                   4632:     }
1.384     raeburn  4633:     my $unpack = 1;
1.485     raeburn  4634:     if ($description eq '.' && $instcodefilter eq '.' && $ownerfilter eq '.' && 
1.384     raeburn  4635:         $typefilter eq '.') {
                   4636:         $unpack = 0;
                   4637:     }
                   4638:     if (!defined($since)) { $since=0; }
1.234     foxr     4639:     my $qresult='';
                   4640:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   4641:     if ($hashref) {
1.384     raeburn  4642: 	while (my ($key,$value) = each(%$hashref)) {
1.397     raeburn  4643:             my ($unesc_key,$lasttime_key,$lasttime,$is_hash,%val,
1.427     raeburn  4644:                 %unesc_val,$selfenroll_end,$selfenroll_types,$created,
                   4645:                 $context);
1.384     raeburn  4646:             $unesc_key = &unescape($key);
                   4647:             if ($unesc_key =~ /^lasttime:/) {
                   4648:                 next;
                   4649:             } else {
                   4650:                 $lasttime_key = &escape('lasttime:'.$unesc_key);
                   4651:             }
                   4652:             if ($hashref->{$lasttime_key} ne '') {
                   4653:                 $lasttime = $hashref->{$lasttime_key};
                   4654:                 next if ($lasttime<$since);
                   4655:             }
1.419     raeburn  4656:             my ($canclone,$valchange);
1.384     raeburn  4657:             my $items = &Apache::lonnet::thaw_unescape($value);
                   4658:             if (ref($items) eq 'HASH') {
1.429     raeburn  4659:                 if ($hashref->{$lasttime_key} eq '') {
1.430     raeburn  4660:                     next if ($since > 1);
1.429     raeburn  4661:                 }
1.384     raeburn  4662:                 $is_hash =  1;
1.445     raeburn  4663:                 if ($domcloner) {
                   4664:                     $canclone = 1;
                   4665:                 } elsif (defined($clonerudom)) {
1.419     raeburn  4666:                     if ($items->{'cloners'}) {
                   4667:                         my @cloneable = split(',',$items->{'cloners'});
                   4668:                         if (@cloneable) {
                   4669:                             if (grep(/^\*$/,@cloneable))  {
                   4670:                                 $canclone = 1;
                   4671:                             } elsif (grep(/^\*:\Q$clonerudom\E$/,@cloneable)) {
                   4672:                                 $canclone = 1;
                   4673:                             } elsif (grep(/^\Q$cloneruname\E:\Q$clonerudom\E$/,@cloneable)) {
                   4674:                                 $canclone = 1;
                   4675:                             }
                   4676:                         }
                   4677:                         unless ($canclone) {
                   4678:                             if ($cloneruname ne '' && $clonerudom ne '') {
                   4679:                                 if ($cc_clone{$unesc_key}) {
                   4680:                                     $canclone = 1;
                   4681:                                     $items->{'cloners'} .= ','.$cloneruname.':'.
                   4682:                                                            $clonerudom;
                   4683:                                     $valchange = 1;
                   4684:                                 }
                   4685:                             }
                   4686:                         }
                   4687:                     } elsif (defined($cloneruname)) {
                   4688:                         if ($cc_clone{$unesc_key}) {
                   4689:                             $canclone = 1;
                   4690:                             $items->{'cloners'} = $cloneruname.':'.$clonerudom;
                   4691:                             $valchange = 1;
                   4692:                         }
1.437     raeburn  4693:                         unless ($canclone) {
                   4694:                             if ($items->{'owner'} =~ /:/) {
                   4695:                                 if ($items->{'owner'} eq $cloner) {
                   4696:                                     $canclone = 1;
                   4697:                                 }
1.444     raeburn  4698:                             } elsif ($cloner eq $items->{'owner'}.':'.$udom) {
1.437     raeburn  4699:                                 $canclone = 1;
                   4700:                             }
                   4701:                             if ($canclone) {
                   4702:                                 $items->{'cloners'} = $cloneruname.':'.$clonerudom;
                   4703:                                 $valchange = 1;
                   4704:                             }
                   4705:                         }
1.419     raeburn  4706:                     }
                   4707:                 }
1.384     raeburn  4708:                 if ($unpack || !$rtn_as_hash) {
                   4709:                     $unesc_val{'descr'} = $items->{'description'};
                   4710:                     $unesc_val{'inst_code'} = $items->{'inst_code'};
                   4711:                     $unesc_val{'owner'} = $items->{'owner'};
                   4712:                     $unesc_val{'type'} = $items->{'type'};
1.419     raeburn  4713:                     $unesc_val{'cloners'} = $items->{'cloners'};
1.427     raeburn  4714:                     $unesc_val{'created'} = $items->{'created'};
                   4715:                     $unesc_val{'context'} = $items->{'context'};
1.404     raeburn  4716:                 }
                   4717:                 $selfenroll_types = $items->{'selfenroll_types'};
                   4718:                 $selfenroll_end = $items->{'selfenroll_end_date'};
1.427     raeburn  4719:                 $created = $items->{'created'};
                   4720:                 $context = $items->{'context'};
1.505     raeburn  4721:                 if ($hasuniquecode ne '.') {
                   4722:                     next unless ($items->{'uniquecode'});
                   4723:                 }
1.404     raeburn  4724:                 if ($selfenrollonly) {
                   4725:                     next if (!$selfenroll_types);
                   4726:                     if (($selfenroll_end > 0) && ($selfenroll_end <= $now)) {
                   4727:                         next;
1.397     raeburn  4728:                     }
1.404     raeburn  4729:                 }
1.427     raeburn  4730:                 if ($creationcontext ne '.') {
                   4731:                     next if (($context ne '') && ($context ne $creationcontext));  
                   4732:                 }
                   4733:                 if ($createdbefore > 0) {
                   4734:                     next if (($created eq '') || ($created > $createdbefore));   
                   4735:                 }
                   4736:                 if ($createdafter > 0) {
                   4737:                     next if (($created eq '') || ($created <= $createdafter)); 
                   4738:                 }
1.404     raeburn  4739:                 if ($catfilter ne '') {
1.406     raeburn  4740:                     next if ($items->{'categories'} eq '');
                   4741:                     my @categories = split('&',$items->{'categories'}); 
1.407     raeburn  4742:                     next if (@categories == 0);
                   4743:                     my @subcats = split('&',$catfilter);
                   4744:                     my $matchcat = 0;
                   4745:                     foreach my $cat (@categories) {
                   4746:                         if (grep(/^\Q$cat\E$/,@subcats)) {
                   4747:                             $matchcat = 1;
                   4748:                             last;
                   4749:                         }
                   4750:                     }
                   4751:                     next if (!$matchcat);
1.404     raeburn  4752:                 }
                   4753:                 if ($caller eq 'coursecatalog') {
1.405     raeburn  4754:                     if ($items->{'hidefromcat'} eq 'yes') {
                   4755:                         next if !$showhidden;
1.401     raeburn  4756:                     }
1.384     raeburn  4757:                 }
1.383     raeburn  4758:             } else {
1.401     raeburn  4759:                 next if ($catfilter ne '');
1.419     raeburn  4760:                 next if ($selfenrollonly);
1.427     raeburn  4761:                 next if ($createdbefore || $createdafter);
                   4762:                 next if ($creationcontext ne '.');
1.419     raeburn  4763:                 if ((defined($clonerudom)) && (defined($cloneruname)))  {
                   4764:                     if ($cc_clone{$unesc_key}) {
                   4765:                         $canclone = 1;
                   4766:                         $val{'cloners'} = &escape($cloneruname.':'.$clonerudom);
                   4767:                     }
                   4768:                 }
1.384     raeburn  4769:                 $is_hash =  0;
1.388     raeburn  4770:                 my @courseitems = split(/:/,$value);
1.403     raeburn  4771:                 $lasttime = pop(@courseitems);
1.402     raeburn  4772:                 if ($hashref->{$lasttime_key} eq '') {
                   4773:                     next if ($lasttime<$since);
                   4774:                 }
1.384     raeburn  4775: 	        ($val{'descr'},$val{'inst_code'},$val{'owner'},$val{'type'}) = @courseitems;
1.383     raeburn  4776:             }
1.419     raeburn  4777:             if ($cloneonly) {
                   4778:                next unless ($canclone);
                   4779:             }
1.266     raeburn  4780:             my $match = 1;
1.384     raeburn  4781: 	    if ($description ne '.') {
                   4782:                 if (!$is_hash) {
                   4783:                     $unesc_val{'descr'} = &unescape($val{'descr'});
                   4784:                 }
                   4785:                 if (eval{$unesc_val{'descr'} !~ /\Q$description\E/i}) {
1.266     raeburn  4786:                     $match = 0;
1.384     raeburn  4787:                 }
1.266     raeburn  4788:             }
1.384     raeburn  4789:             if ($instcodefilter ne '.') {
                   4790:                 if (!$is_hash) {
                   4791:                     $unesc_val{'inst_code'} = &unescape($val{'inst_code'});
                   4792:                 }
1.418     raeburn  4793:                 if ($regexp_ok == 1) {
1.384     raeburn  4794:                     if (eval{$unesc_val{'inst_code'} !~ /$instcodefilter/}) {
1.344     raeburn  4795:                         $match = 0;
                   4796:                     }
1.418     raeburn  4797:                 } elsif ($regexp_ok == -1) {
                   4798:                     if (eval{$unesc_val{'inst_code'} =~ /$instcodefilter/}) {
                   4799:                         $match = 0;
                   4800:                     }
1.344     raeburn  4801:                 } else {
1.384     raeburn  4802:                     if (eval{$unesc_val{'inst_code'} !~ /\Q$instcodefilter\E/i}) {
1.344     raeburn  4803:                         $match = 0;
                   4804:                     }
1.266     raeburn  4805:                 }
1.234     foxr     4806: 	    }
1.384     raeburn  4807:             if ($ownerfilter ne '.') {
                   4808:                 if (!$is_hash) {
                   4809:                     $unesc_val{'owner'} = &unescape($val{'owner'});
                   4810:                 }
1.336     raeburn  4811:                 if (($ownerunamefilter ne '') && ($ownerdomfilter ne '')) {
1.384     raeburn  4812:                     if ($unesc_val{'owner'} =~ /:/) {
                   4813:                         if (eval{$unesc_val{'owner'} !~ 
                   4814:                              /\Q$ownerunamefilter\E:\Q$ownerdomfilter\E$/i}) {
1.336     raeburn  4815:                             $match = 0;
                   4816:                         } 
                   4817:                     } else {
1.384     raeburn  4818:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336     raeburn  4819:                             $match = 0;
                   4820:                         }
                   4821:                     }
                   4822:                 } elsif ($ownerunamefilter ne '') {
1.384     raeburn  4823:                     if ($unesc_val{'owner'} =~ /:/) {
                   4824:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E:[^:]+$/i}) {
1.336     raeburn  4825:                              $match = 0;
                   4826:                         }
                   4827:                     } else {
1.384     raeburn  4828:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336     raeburn  4829:                             $match = 0;
                   4830:                         }
                   4831:                     }
                   4832:                 } elsif ($ownerdomfilter ne '') {
1.384     raeburn  4833:                     if ($unesc_val{'owner'} =~ /:/) {
                   4834:                         if (eval{$unesc_val{'owner'} !~ /^[^:]+:\Q$ownerdomfilter\E/}) {
1.336     raeburn  4835:                              $match = 0;
                   4836:                         }
                   4837:                     } else {
                   4838:                         if ($ownerdomfilter ne $udom) {
                   4839:                             $match = 0;
                   4840:                         }
                   4841:                     }
1.266     raeburn  4842:                 }
                   4843:             }
1.384     raeburn  4844:             if ($coursefilter ne '.') {
                   4845:                 if (eval{$unesc_key !~ /^$udom(_)\Q$coursefilter\E$/}) {
1.282     raeburn  4846:                     $match = 0;
                   4847:                 }
                   4848:             }
1.384     raeburn  4849:             if ($typefilter ne '.') {
                   4850:                 if (!$is_hash) {
                   4851:                     $unesc_val{'type'} = &unescape($val{'type'});
                   4852:                 }
                   4853:                 if ($unesc_val{'type'} eq '') {
1.333     raeburn  4854:                     if ($typefilter ne 'Course') {
                   4855:                         $match = 0;
                   4856:                     }
1.383     raeburn  4857:                 } else {
1.384     raeburn  4858:                     if (eval{$unesc_val{'type'} !~ /^\Q$typefilter\E$/}) {
1.333     raeburn  4859:                         $match = 0;
                   4860:                     }
                   4861:                 }
                   4862:             }
1.266     raeburn  4863:             if ($match == 1) {
1.384     raeburn  4864:                 if ($rtn_as_hash) {
                   4865:                     if ($is_hash) {
1.419     raeburn  4866:                         if ($valchange) {
                   4867:                             my $newvalue = &Apache::lonnet::freeze_escape($items);
                   4868:                             $qresult.=$key.'='.$newvalue.'&';
                   4869:                         } else {
                   4870:                             $qresult.=$key.'='.$value.'&';
                   4871:                         }
1.384     raeburn  4872:                     } else {
1.388     raeburn  4873:                         my %rtnhash = ( 'description' => &unescape($val{'descr'}),
                   4874:                                         'inst_code' => &unescape($val{'inst_code'}),
                   4875:                                         'owner'     => &unescape($val{'owner'}),
                   4876:                                         'type'      => &unescape($val{'type'}),
1.419     raeburn  4877:                                         'cloners'   => &unescape($val{'cloners'}),
1.384     raeburn  4878:                                       );
                   4879:                         my $items = &Apache::lonnet::freeze_escape(\%rtnhash);
                   4880:                         $qresult.=$key.'='.$items.'&';
                   4881:                     }
1.383     raeburn  4882:                 } else {
1.384     raeburn  4883:                     if ($is_hash) {
                   4884:                         $qresult .= $key.'='.&escape($unesc_val{'descr'}).':'.
                   4885:                                     &escape($unesc_val{'inst_code'}).':'.
                   4886:                                     &escape($unesc_val{'owner'}).'&';
                   4887:                     } else {
                   4888:                         $qresult .= $key.'='.$val{'descr'}.':'.$val{'inst_code'}.
                   4889:                                     ':'.$val{'owner'}.'&';
                   4890:                     }
1.383     raeburn  4891:                 }
1.266     raeburn  4892:             }
1.234     foxr     4893: 	}
1.311     albertel 4894: 	if (&untie_domain_hash($hashref)) {
1.234     foxr     4895: 	    chop($qresult);
1.387     albertel 4896: 	    &Reply($client, \$qresult, $userinput);
1.234     foxr     4897: 	} else {
                   4898: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4899: 		    "while attempting courseiddump\n", $userinput);
                   4900: 	}
                   4901:     } else {
                   4902: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4903: 		"while attempting courseiddump\n", $userinput);
                   4904:     }
                   4905:     return 1;
                   4906: }
                   4907: &register_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
1.238     foxr     4908: 
1.438     raeburn  4909: sub course_lastaccess_handler {
                   4910:     my ($cmd, $tail, $client) = @_;
                   4911:     my $userinput = "$cmd:$tail";
                   4912:     my ($cdom,$cnum) = split(':',$tail); 
                   4913:     my (%lastaccess,$qresult);
                   4914:     my $hashref = &tie_domain_hash($cdom, "nohist_courseids", &GDBM_WRCREAT());
                   4915:     if ($hashref) {
                   4916:         while (my ($key,$value) = each(%$hashref)) {
                   4917:             my ($unesc_key,$lasttime);
                   4918:             $unesc_key = &unescape($key);
                   4919:             if ($cnum) {
                   4920:                 next unless ($unesc_key =~ /\Q$cdom\E_\Q$cnum\E$/);
                   4921:             }
                   4922:             if ($unesc_key =~ /^lasttime:($LONCAPA::match_domain\_$LONCAPA::match_courseid)/) {
                   4923:                 $lastaccess{$1} = $value;
                   4924:             } else {
                   4925:                 my $items = &Apache::lonnet::thaw_unescape($value);
                   4926:                 if (ref($items) eq 'HASH') {
                   4927:                     unless ($lastaccess{$unesc_key}) {
                   4928:                         $lastaccess{$unesc_key} = '';
                   4929:                     }
                   4930:                 } else {
                   4931:                     my @courseitems = split(':',$value);
                   4932:                     $lastaccess{$unesc_key} = pop(@courseitems);
                   4933:                 }
                   4934:             }
                   4935:         }
                   4936:         foreach my $cid (sort(keys(%lastaccess))) {
                   4937:             $qresult.=&escape($cid).'='.$lastaccess{$cid}.'&'; 
                   4938:         }
                   4939:         if (&untie_domain_hash($hashref)) {
                   4940:             if ($qresult) {
                   4941:                 chop($qresult);
                   4942:             }
                   4943:             &Reply($client, \$qresult, $userinput);
                   4944:         } else {
                   4945:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4946:                     "while attempting lastacourseaccess\n", $userinput);
                   4947:         }
                   4948:     } else {
                   4949:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4950:                 "while attempting lastcourseaccess\n", $userinput);
                   4951:     }
                   4952:     return 1;
                   4953: }
                   4954: &register_handler("courselastaccess",\&course_lastaccess_handler, 0, 1, 0);
                   4955: 
1.561     raeburn  4956: sub course_sessions_handler {
                   4957:     my ($cmd, $tail, $client) = @_;
                   4958:     my $userinput = "$cmd:$tail";
                   4959:     my ($cdom,$cnum,$lastactivity) = split(':',$tail);
                   4960:     my $dbsuffix = '_'.$cdom.'_'.$cnum.'.db';
                   4961:     my (%sessions,$qresult);
                   4962:     my $now=time;
                   4963:     if (opendir(DIR,$perlvar{'lonIDsDir'})) {
                   4964:         my $filename;
                   4965:         while ($filename=readdir(DIR)) {
                   4966:             next if ($filename=~/^\./);
                   4967:             next if ($filename=~/^publicuser_/);
                   4968:             next if ($filename=~/^[a-f0-9]+_(linked|lti_\d+)\.id$/);
1.562     raeburn  4969:             if ($filename =~ /^($LONCAPA::match_username)_\d+_($LONCAPA::match_domain)_/) {
1.561     raeburn  4970:                 my ($uname,$udom) = ($1,$2);
1.562     raeburn  4971:                 next unless (-e "$perlvar{'lonDaemons'}/tmp/$uname$dbsuffix");
1.561     raeburn  4972:                 my $mtime = (stat("$perlvar{'lonIDsDir'}/$filename"))[9];
                   4973:                 if ($lastactivity < 0) {
1.563     raeburn  4974:                     next if ($mtime-$now > $lastactivity);
1.561     raeburn  4975:                 } else {
1.563     raeburn  4976:                     next if ($now-$mtime > $lastactivity);
1.561     raeburn  4977:                 }
                   4978:                 $sessions{$uname.':'.$udom} = $mtime;
                   4979:             }
                   4980:         }
                   4981:         closedir(DIR); 
                   4982:     }
                   4983:     foreach my $user (keys(%sessions)) {
                   4984:         $qresult.=&escape($user).'='.$sessions{$user}.'&';
                   4985:     }
                   4986:     if ($qresult) {
                   4987:         chop($qresult);
                   4988:     }
                   4989:     &Reply($client, \$qresult, $userinput);
                   4990:     return 1;
                   4991: }
                   4992: &register_handler("coursesessions",\&course_sessions_handler, 0, 1, 0);
                   4993: 
1.238     foxr     4994: #
1.348     raeburn  4995: # Puts an unencrypted entry in a namespace db file at the domain level 
                   4996: #
                   4997: # Parameters:
                   4998: #    $cmd      - The command that got us here.
                   4999: #    $tail     - Tail of the command (remaining parameters).
                   5000: #    $client   - File descriptor connected to client.
                   5001: # Returns
                   5002: #     0        - Requested to exit, caller should shut down.
                   5003: #     1        - Continue processing.
                   5004: #  Side effects:
                   5005: #     reply is written to $client.
                   5006: #
                   5007: sub put_domain_handler {
                   5008:     my ($cmd,$tail,$client) = @_;
                   5009: 
                   5010:     my $userinput = "$cmd:$tail";
                   5011: 
                   5012:     my ($udom,$namespace,$what) =split(/:/,$tail,3);
                   5013:     chomp($what);
                   5014:     my @pairs=split(/\&/,$what);
                   5015:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_WRCREAT(),
                   5016:                                    "P", $what);
                   5017:     if ($hashref) {
                   5018:         foreach my $pair (@pairs) {
                   5019:             my ($key,$value)=split(/=/,$pair);
                   5020:             $hashref->{$key}=$value;
                   5021:         }
                   5022:         if (&untie_domain_hash($hashref)) {
                   5023:             &Reply($client, "ok\n", $userinput);
                   5024:         } else {
                   5025:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5026:                      "while attempting putdom\n", $userinput);
                   5027:         }
                   5028:     } else {
                   5029:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5030:                   "while attempting putdom\n", $userinput);
                   5031:     }
                   5032: 
                   5033:     return 1;
                   5034: }
                   5035: &register_handler("putdom", \&put_domain_handler, 0, 1, 0);
                   5036: 
1.517     raeburn  5037: # Updates one or more entries in clickers.db file at the domain level
                   5038: #
                   5039: # Parameters:
                   5040: #    $cmd      - The command that got us here.
                   5041: #    $tail     - Tail of the command (remaining parameters).
                   5042: #                In this case a colon separated list containing:
                   5043: #                (a) the domain for which we are updating the entries,
                   5044: #                (b) the action required -- add or del -- and
                   5045: #                (c) a &-separated list of entries to add or delete.
                   5046: #    $client   - File descriptor connected to client.
                   5047: # Returns
                   5048: #     1        - Continue processing.
                   5049: #     0        - Requested to exit, caller should shut down.
                   5050: #  Side effects:
                   5051: #     reply is written to $client.
                   5052: #
                   5053: 
                   5054: 
                   5055: sub update_clickers {
                   5056:     my ($cmd, $tail, $client)  = @_;
                   5057: 
                   5058:     my $userinput = "$cmd:$tail";
                   5059:     my ($udom,$action,$what) =split(/:/,$tail,3);
                   5060:     chomp($what);
                   5061: 
                   5062:     my $hashref = &tie_domain_hash($udom, "clickers", &GDBM_WRCREAT(),
                   5063:                                  "U","$action:$what");
                   5064: 
                   5065:     if (!$hashref) {
                   5066:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5067:                   "while attempting updateclickers\n", $userinput);
                   5068:         return 1;
                   5069:     }
                   5070: 
                   5071:     my @pairs=split(/\&/,$what);
                   5072:     foreach my $pair (@pairs) {
                   5073:         my ($key,$value)=split(/=/,$pair);
                   5074:         if ($action eq 'add') {
                   5075:             if (exists($hashref->{$key})) {
                   5076:                 my @newvals = split(/,/,&unescape($value));
                   5077:                 my @currvals = split(/,/,&unescape($hashref->{$key}));
                   5078:                 my @merged = sort(keys(%{{map { $_ => 1 } (@newvals,@currvals)}}));
                   5079:                 $hashref->{$key}=&escape(join(',',@merged));
                   5080:             } else {
                   5081:                 $hashref->{$key}=$value;
                   5082:             }
                   5083:         } elsif ($action eq 'del') {
                   5084:             if (exists($hashref->{$key})) {
                   5085:                 my %current;
                   5086:                 map { $current{$_} = 1; } split(/,/,&unescape($hashref->{$key}));
                   5087:                 map { delete($current{$_}); } split(/,/,&unescape($value));
                   5088:                 if (keys(%current)) {
                   5089:                     $hashref->{$key}=&escape(join(',',sort(keys(%current))));
                   5090:                 } else {
                   5091:                     delete($hashref->{$key});
                   5092:                 }
                   5093:             }
                   5094:         }
                   5095:     }
                   5096:     if (&untie_user_hash($hashref)) {
                   5097:         &Reply( $client, "ok\n", $userinput);
                   5098:     } else {
                   5099:         &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   5100:                  "while attempting put\n",
                   5101:                  $userinput);
                   5102:     }
                   5103:     return 1;
                   5104: }
                   5105: &register_handler("updateclickers", \&update_clickers, 0, 1, 0);
                   5106: 
                   5107: 
                   5108: # Deletes one or more entries in a namespace db file at the domain level
                   5109: #
                   5110: # Parameters:
                   5111: #    $cmd      - The command that got us here.
                   5112: #    $tail     - Tail of the command (remaining parameters).
                   5113: #                In this case a colon separated list containing:
                   5114: #                (a) the domain for which we are deleting the entries,
                   5115: #                (b) &-separated list of keys to delete.  
                   5116: #    $client   - File descriptor connected to client.
                   5117: # Returns
                   5118: #     1        - Continue processing.
                   5119: #     0        - Requested to exit, caller should shut down.
                   5120: #  Side effects:
                   5121: #     reply is written to $client.
                   5122: #
                   5123: 
                   5124: sub del_domain_handler {
                   5125:     my ($cmd,$tail,$client) = @_;
                   5126: 
                   5127:     my $userinput = "$cmd:$tail";
                   5128: 
                   5129:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   5130:     chomp($what);
                   5131:     my $hashref = &tie_domain_hash($udom,$namespace,&GDBM_WRCREAT(),
                   5132:                                    "D", $what);
                   5133:     if ($hashref) {
                   5134:         my @keys=split(/\&/,$what);
                   5135:         foreach my $key (@keys) {
                   5136:             delete($hashref->{$key});
                   5137:         }
                   5138:         if (&untie_user_hash($hashref)) {
                   5139:             &Reply($client, "ok\n", $userinput);
                   5140:         } else {
                   5141:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5142:                     "while attempting deldom\n", $userinput);
                   5143:         }
                   5144:     } else {
                   5145:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5146:                  "while attempting deldom\n", $userinput);
                   5147:     }
                   5148:     return 1;
                   5149: }
                   5150: &register_handler("deldom", \&del_domain_handler, 0, 1, 0);
                   5151: 
                   5152: 
1.348     raeburn  5153: # Unencrypted get from the namespace database file at the domain level.
                   5154: # This function retrieves a keyed item from a specific named database in the
                   5155: # domain directory.
                   5156: #
                   5157: # Parameters:
1.565     raeburn  5158: #   $cmd             - Command request keyword (getdom).
1.348     raeburn  5159: #   $tail            - Tail of the command.  This is a colon separated list
                   5160: #                      consisting of the domain and the 'namespace' 
                   5161: #                      which selects the gdbm file to do the lookup in,
                   5162: #                      & separated list of keys to lookup.  Note that
                   5163: #                      the values are returned as an & separated list too.
                   5164: #   $client          - File descriptor open on the client.
                   5165: # Returns:
                   5166: #   1       - Continue processing.
                   5167: #   0       - Exit.
                   5168: #  Side effects:
                   5169: #     reply is written to $client.
                   5170: #
                   5171: 
                   5172: sub get_domain_handler {
                   5173:     my ($cmd, $tail, $client) = @_;
                   5174: 
1.536     raeburn  5175:     my $userinput = "$cmd:$tail";
                   5176: 
                   5177:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
1.573     raeburn  5178:     if (($namespace =~ /^enc/) || ($namespace eq 'private')) {
1.536     raeburn  5179:         &Failure( $client, "refused\n", $userinput);
                   5180:     } else {
1.565     raeburn  5181:         my $res = LONCAPA::Lond::get_dom($userinput);
                   5182:         if ($res =~ /^error:/) {
                   5183:             &Failure($client, \$res, $userinput);
1.536     raeburn  5184:         } else {
1.565     raeburn  5185:             &Reply($client, \$res, $userinput);
1.536     raeburn  5186:         }
                   5187:     }
                   5188: 
                   5189:     return 1;
                   5190: }
                   5191: &register_handler("getdom", \&get_domain_handler, 0, 1, 0);
                   5192: 
1.572     raeburn  5193: #
                   5194: # Encrypted get from the namespace database file at the domain level.
                   5195: # This function retrieves a keyed item from a specific named database in the
                   5196: # domain directory.
                   5197: #
                   5198: # Parameters:
                   5199: #   $cmd             - Command request keyword (egetdom).
                   5200: #   $tail            - Tail of the command.  This is a colon separated list
                   5201: #                      consisting of the domain and the 'namespace'
                   5202: #                      which selects the gdbm file to do the lookup in,
                   5203: #                      & separated list of keys to lookup.  Note that
                   5204: #                      the values are returned as an & separated list too.
                   5205: #   $client          - File descriptor open on the client.
                   5206: # Returns:
                   5207: #   1       - Continue processing.
                   5208: #   0       - Exit.
                   5209: #  Side effects:
                   5210: #     reply is encrypted before being written to $client.
                   5211: #
1.536     raeburn  5212: sub encrypted_get_domain_handler {
                   5213:     my ($cmd, $tail, $client) = @_;
                   5214: 
                   5215:     my $userinput = "$cmd:$tail";
1.348     raeburn  5216: 
1.573     raeburn  5217:     my ($udom,$namespace,$what) = split(/:/,$tail,3);
                   5218:     if ($namespace eq 'private') {
                   5219:         &Failure( $client, "refused\n", $userinput);
1.565     raeburn  5220:     } else {
1.573     raeburn  5221:         my $res = LONCAPA::Lond::get_dom($userinput);
                   5222:         if ($res =~ /^error:/) {
                   5223:             &Failure($client, \$res, $userinput);
                   5224:         } else {
                   5225:             if ($cipher) {
                   5226:                 my $cmdlength=length($res);
                   5227:                 $res.="         ";
                   5228:                 my $encres='';
                   5229:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   5230:                     $encres.= unpack("H16",
                   5231:                                      $cipher->encrypt(substr($res,
                   5232:                                                              $encidx,
                   5233:                                                              8)));
                   5234:                 }
                   5235:                 &Reply( $client,"enc:$cmdlength:$encres\n",$userinput);
                   5236:             } else {
                   5237:                 &Failure( $client, "error:no_key\n",$userinput);
1.536     raeburn  5238:             }
1.348     raeburn  5239:         }
                   5240:     }
                   5241:     return 1;
                   5242: }
1.536     raeburn  5243: &register_handler("egetdom", \&encrypted_get_domain_handler, 1, 1, 0);
1.348     raeburn  5244: 
1.420     raeburn  5245: #
1.572     raeburn  5246: # Encrypted get from the namespace database file at the domain level.
                   5247: # This function retrieves a keyed item from a specific named database in the
                   5248: # domain directory.
                   5249: #
                   5250: # Parameters:
                   5251: #   $cmd             - Command request keyword (lti).
                   5252: #   $tail            - Tail of the command.  This is a colon-separated list
                   5253: #                      consisting of the domain, coursenum, if for LTI-
                   5254: #                      enabled deep-linking to course content using
                   5255: #                      link protection configured within a course,
                   5256: #                      context (=deeplink) if for LTI-enabled deep-linking
                   5257: #                      to course content using LTI Provider settings
                   5258: #                      configured within a course's domain, the (escaped)
                   5259: #                      launch URL, the (escaped) method (typically POST),
                   5260: #                      and a frozen hash of the LTI launch parameters
                   5261: #                      from the LTI payload.
                   5262: #   $client          - File descriptor open on the client.
                   5263: # Returns:
                   5264: #   1       - Continue processing.
                   5265: #   0       - Exit.
                   5266: #  Side effects:
                   5267: #     The reply will contain an LTI itemID, if the signed LTI payload
1.579     raeburn  5268: #     could be verified using the consumer key and the shared secret
                   5269: #     available for that key (for the itemID) for either the course or domain,
                   5270: #     depending on values for cnum and context. The reply is encrypted before
1.572     raeburn  5271: #     being written to $client.
                   5272: #
                   5273: sub lti_handler {
                   5274:     my ($cmd, $tail, $client) = @_;
                   5275: 
                   5276:     my $userinput = "$cmd:$tail";
                   5277: 
                   5278:     my ($cdom,$cnum,$context,$escurl,$escmethod,$items) = split(/:/,$tail);
                   5279:     my $url = &unescape($escurl);
                   5280:     my $method = &unescape($escmethod);
                   5281:     my $params = &Apache::lonnet::thaw_unescape($items);
                   5282:     my $res;
                   5283:     if ($cnum ne '') {
                   5284:         $res = &LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
                   5285:     } else {
                   5286:         $res = &LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
                   5287:     }
                   5288:     if ($res =~ /^error:/) {
                   5289:         &Failure($client, \$res, $userinput);
                   5290:     } else {
                   5291:         if ($cipher) {
                   5292:             my $cmdlength=length($res);
                   5293:             $res.="         ";
                   5294:             my $encres='';
                   5295:             for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   5296:                 $encres.= unpack("H16",
                   5297:                                  $cipher->encrypt(substr($res,
                   5298:                                                          $encidx,
                   5299:                                                          8)));
                   5300:             }
                   5301:             &Reply( $client,"enc:$cmdlength:$encres\n",$userinput);
                   5302:         } else {
                   5303:             &Failure( $client, "error:no_key\n",$userinput);
                   5304:         }
                   5305:     }
                   5306:     return 1;
                   5307: }
                   5308: &register_handler("lti", \&lti_handler, 1, 1, 0);
                   5309: 
                   5310: #
1.579     raeburn  5311: # Data for LTI payload (received encrypted) are unencrypted and
1.577     raeburn  5312: # then signed with the appropriate key and secret, before re-encrypting
1.579     raeburn  5313: # the signed payload which is sent to the client for unencryption by
                   5314: # the caller: lonnet::sign_lti()) before dispatch either to a web browser
                   5315: # (launch) or to a remote web service (roster, logout, or grade).  
1.577     raeburn  5316: #
                   5317: # Parameters:
                   5318: #   $cmd             - Command request keyword (signlti).
                   5319: #   $tail            - Tail of the command.  This is a colon-separated list
                   5320: #                      consisting of the domain, coursenum (if for an External
1.578     raeburn  5321: #                      Tool defined in a course), crsdef (true if defined in
1.579     raeburn  5322: #                      a course), type (linkprot or lti)
                   5323: #                      context (launch, roster, logout, or grade),
1.578     raeburn  5324: #                      escaped launch URL, numeric ID of external tool,
1.577     raeburn  5325: #                      version number for encryption key (if tool's LTI secret was
1.578     raeburn  5326: #                      encrypted before storing), a frozen hash of LTI launch 
                   5327: #                      parameters, and a frozen hash of LTI information,
                   5328: #                      (e.g., method => 'HMAC-SHA1',
                   5329: #                             respfmt => 'to_authorization_header').
1.577     raeburn  5330: #   $client          - File descriptor open on the client.
                   5331: # Returns:
                   5332: #   1       - Continue processing.
                   5333: #   0       - Exit.
                   5334: #  Side effects:
                   5335: #     The reply will contain the LTI payload, as & separated key=value pairs,
                   5336: #     where value is itself a frozen hash, if the required key and secret
1.579     raeburn  5337: #     for the specific tool ID are available. The payload data are retrieved from
1.578     raeburn  5338: #     a call to Lond::sign_lti_payload(), and the reply is encrypted before being
1.577     raeburn  5339: #     written to $client.
                   5340: #
                   5341: sub sign_lti_handler {
                   5342:     my ($cmd, $tail, $client) = @_;
                   5343: 
                   5344:     my $userinput = "$cmd:$tail";
                   5345: 
1.579     raeburn  5346:     my ($cdom,$cnum,$crsdef,$type,$context,$escurl,
                   5347:         $ltinum,$keynum,$paramsref,$inforef) = split(/:/,$tail);
1.577     raeburn  5348:     my $url = &unescape($escurl);
                   5349:     my $params = &Apache::lonnet::thaw_unescape($paramsref);
                   5350:     my $info = &Apache::lonnet::thaw_unescape($inforef);
                   5351:     my $res =
1.579     raeburn  5352:         &LONCAPA::Lond::sign_lti_payload($cdom,$cnum,$crsdef,$type,$context,$url,$ltinum,
                   5353:                                          $keynum,$perlvar{'lonVersion'},$params,$info);
1.577     raeburn  5354:     my $result;
                   5355:     if (ref($res) eq 'HASH') {
                   5356:         foreach my $key (keys(%{$res})) {
                   5357:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($res->{$key}).'&';
                   5358:         }
                   5359:         $result =~ s/\&$//;
                   5360:     } else {
                   5361:         $result = $res;
                   5362:     }
                   5363:     if ($result =~ /^error:/) {
                   5364:         &Failure($client, \$result, $userinput);
                   5365:     } else {
                   5366:         if ($cipher) {
                   5367:             my $cmdlength=length($result);
                   5368:             $result.="         ";
                   5369:             my $encres='';
                   5370:             for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   5371:                 $encres.= unpack("H16",
                   5372:                                  $cipher->encrypt(substr($result,
                   5373:                                                          $encidx,
                   5374:                                                          8)));
                   5375:             }
                   5376:             &Reply( $client,"enc:$cmdlength:$encres\n",$userinput);
                   5377:         } else {
                   5378:             &Failure( $client, "error:no_key\n",$userinput);
                   5379:         }
                   5380:     }
                   5381:     return 1;
                   5382: }
                   5383: &register_handler("signlti", \&sign_lti_handler, 1, 1, 0);
                   5384: 
                   5385: #
1.238     foxr     5386: #  Puts an id to a domains id database. 
                   5387: #
                   5388: #  Parameters:
                   5389: #   $cmd     - The command that triggered us.
                   5390: #   $tail    - Remainder of the request other than the command. This is a 
                   5391: #              colon separated list containing:
                   5392: #              $domain  - The domain for which we are writing the id.
                   5393: #              $pairs  - The id info to write... this is and & separated list
                   5394: #                        of keyword=value.
                   5395: #   $client  - Socket open on the client.
                   5396: #  Returns:
                   5397: #    1   - Continue processing.
                   5398: #  Side effects:
                   5399: #     reply is written to $client.
                   5400: #
                   5401: sub put_id_handler {
                   5402:     my ($cmd,$tail,$client) = @_;
                   5403: 
                   5404: 
                   5405:     my $userinput = "$cmd:$tail";
                   5406: 
                   5407:     my ($udom,$what)=split(/:/,$tail);
                   5408:     chomp($what);
                   5409:     my @pairs=split(/\&/,$what);
                   5410:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   5411: 				   "P", $what);
                   5412:     if ($hashref) {
                   5413: 	foreach my $pair (@pairs) {
                   5414: 	    my ($key,$value)=split(/=/,$pair);
                   5415: 	    $hashref->{$key}=$value;
                   5416: 	}
1.311     albertel 5417: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     5418: 	    &Reply($client, "ok\n", $userinput);
                   5419: 	} else {
                   5420: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5421: 		     "while attempting idput\n", $userinput);
                   5422: 	}
                   5423:     } else {
                   5424: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5425: 		  "while attempting idput\n", $userinput);
                   5426:     }
                   5427: 
                   5428:     return 1;
                   5429: }
1.263     albertel 5430: &register_handler("idput", \&put_id_handler, 0, 1, 0);
1.238     foxr     5431: 
                   5432: #
                   5433: #  Retrieves a set of id values from the id database.
                   5434: #  Returns an & separated list of results, one for each requested id to the
                   5435: #  client.
                   5436: #
                   5437: # Parameters:
                   5438: #   $cmd       - Command keyword that caused us to be dispatched.
                   5439: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5440: #               domain - the domain whose id table we dump
                   5441: #               ids      Consists of an & separated list of
                   5442: #                        id keywords whose values will be fetched.
                   5443: #                        nonexisting keywords will have an empty value.
                   5444: #   $client    - Socket open on the client.
                   5445: #
                   5446: # Returns:
                   5447: #    1 - indicating processing should continue.
                   5448: # Side effects:
                   5449: #   An & separated list of results is written to $client.
                   5450: #
                   5451: sub get_id_handler {
                   5452:     my ($cmd, $tail, $client) = @_;
                   5453: 
                   5454:     
                   5455:     my $userinput = "$client:$tail";
                   5456:     
                   5457:     my ($udom,$what)=split(/:/,$tail);
                   5458:     chomp($what);
                   5459:     my @queries=split(/\&/,$what);
                   5460:     my $qresult='';
                   5461:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
                   5462:     if ($hashref) {
                   5463: 	for (my $i=0;$i<=$#queries;$i++) {
                   5464: 	    $qresult.="$hashref->{$queries[$i]}&";
                   5465: 	}
1.311     albertel 5466: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     5467: 	    $qresult=~s/\&$//;
1.387     albertel 5468: 	    &Reply($client, \$qresult, $userinput);
1.238     foxr     5469: 	} else {
                   5470: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5471: 		      "while attempting idget\n",$userinput);
                   5472: 	}
                   5473:     } else {
                   5474: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5475: 		 "while attempting idget\n",$userinput);
                   5476:     }
                   5477:     
                   5478:     return 1;
                   5479: }
1.263     albertel 5480: &register_handler("idget", \&get_id_handler, 0, 1, 0);
1.238     foxr     5481: 
1.501     raeburn  5482: #   Deletes one or more ids in a domain's id database.
                   5483: #
                   5484: #   Parameters:
                   5485: #       $cmd                  - Command keyword (iddel).
                   5486: #       $tail                 - Command tail.  In this case a colon
                   5487: #                               separated list containing:
                   5488: #                               The domain for which we are deleting the id(s).
                   5489: #                               &-separated list of id(s) to delete.
                   5490: #       $client               - File open on client socket.
                   5491: # Returns:
                   5492: #     1   - Continue processing
                   5493: #     0   - Exit server.
                   5494: #     
                   5495: #
                   5496: 
                   5497: sub del_id_handler {
                   5498:     my ($cmd,$tail,$client) = @_;
                   5499: 
                   5500:     my $userinput = "$cmd:$tail";
                   5501: 
                   5502:     my ($udom,$what)=split(/:/,$tail);
                   5503:     chomp($what);
                   5504:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   5505:                                    "D", $what);
                   5506:     if ($hashref) {
                   5507:         my @keys=split(/\&/,$what);
                   5508:         foreach my $key (@keys) {
                   5509:             delete($hashref->{$key});
                   5510:         }
                   5511:         if (&untie_user_hash($hashref)) {
                   5512:             &Reply($client, "ok\n", $userinput);
                   5513:         } else {
                   5514:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5515:                     "while attempting iddel\n", $userinput);
                   5516:         }
                   5517:     } else {
                   5518:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5519:                  "while attempting iddel\n", $userinput);
                   5520:     }
                   5521:     return 1;
                   5522: }
                   5523: &register_handler("iddel", \&del_id_handler, 0, 1, 0);
                   5524: 
1.238     foxr     5525: #
1.299     raeburn  5526: # Puts broadcast e-mail sent by Domain Coordinator in nohist_dcmail database 
                   5527: #
                   5528: # Parameters
                   5529: #   $cmd       - Command keyword that caused us to be dispatched.
                   5530: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5531: #               domain - the domain whose dcmail we are recording
                   5532: #               email    Consists of key=value pair 
                   5533: #                        where key is unique msgid
                   5534: #                        and value is message (in XML)
                   5535: #   $client    - Socket open on the client.
                   5536: #
                   5537: # Returns:
                   5538: #    1 - indicating processing should continue.
                   5539: # Side effects
                   5540: #     reply is written to $client.
                   5541: #
                   5542: sub put_dcmail_handler {
                   5543:     my ($cmd,$tail,$client) = @_;
                   5544:     my $userinput = "$cmd:$tail";
1.463     foxr     5545: 
                   5546: 
1.299     raeburn  5547:     my ($udom,$what)=split(/:/,$tail);
                   5548:     chomp($what);
                   5549:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   5550:     if ($hashref) {
                   5551:         my ($key,$value)=split(/=/,$what);
                   5552:         $hashref->{$key}=$value;
                   5553:     }
1.311     albertel 5554:     if (&untie_domain_hash($hashref)) {
1.299     raeburn  5555:         &Reply($client, "ok\n", $userinput);
                   5556:     } else {
                   5557:         &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5558:                  "while attempting dcmailput\n", $userinput);
                   5559:     }
                   5560:     return 1;
                   5561: }
                   5562: &register_handler("dcmailput", \&put_dcmail_handler, 0, 1, 0);
                   5563: 
                   5564: #
                   5565: # Retrieves broadcast e-mail from nohist_dcmail database
                   5566: # Returns to client an & separated list of key=value pairs,
                   5567: # where key is msgid and value is message information.
                   5568: #
                   5569: # Parameters
                   5570: #   $cmd       - Command keyword that caused us to be dispatched.
                   5571: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5572: #               domain - the domain whose dcmail table we dump
                   5573: #               startfilter - beginning of time window 
                   5574: #               endfilter - end of time window
                   5575: #               sendersfilter - & separated list of username:domain 
                   5576: #                 for senders to search for.
                   5577: #   $client    - Socket open on the client.
                   5578: #
                   5579: # Returns:
                   5580: #    1 - indicating processing should continue.
                   5581: # Side effects
                   5582: #     reply (& separated list of msgid=messageinfo pairs) is 
                   5583: #     written to $client.
                   5584: #
                   5585: sub dump_dcmail_handler {
                   5586:     my ($cmd, $tail, $client) = @_;
                   5587:                                                                                 
                   5588:     my $userinput = "$cmd:$tail";
                   5589:     my ($udom,$startfilter,$endfilter,$sendersfilter) = split(/:/,$tail);
                   5590:     chomp($sendersfilter);
                   5591:     my @senders = ();
                   5592:     if (defined($startfilter)) {
                   5593:         $startfilter=&unescape($startfilter);
                   5594:     } else {
                   5595:         $startfilter='.';
                   5596:     }
                   5597:     if (defined($endfilter)) {
                   5598:         $endfilter=&unescape($endfilter);
                   5599:     } else {
                   5600:         $endfilter='.';
                   5601:     }
                   5602:     if (defined($sendersfilter)) {
                   5603:         $sendersfilter=&unescape($sendersfilter);
1.300     albertel 5604: 	@senders = map { &unescape($_) } split(/\&/,$sendersfilter);
1.299     raeburn  5605:     }
                   5606: 
                   5607:     my $qresult='';
                   5608:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   5609:     if ($hashref) {
                   5610:         while (my ($key,$value) = each(%$hashref)) {
                   5611:             my $match = 1;
1.303     albertel 5612:             my ($timestamp,$subj,$uname,$udom) = 
                   5613: 		split(/:/,&unescape(&unescape($key)),5); # yes, twice really
1.299     raeburn  5614:             $subj = &unescape($subj);
                   5615:             unless ($startfilter eq '.' || !defined($startfilter)) {
                   5616:                 if ($timestamp < $startfilter) {
                   5617:                     $match = 0;
                   5618:                 }
                   5619:             }
                   5620:             unless ($endfilter eq '.' || !defined($endfilter)) {
                   5621:                 if ($timestamp > $endfilter) {
                   5622:                     $match = 0;
                   5623:                 }
                   5624:             }
                   5625:             unless (@senders < 1) {
                   5626:                 unless (grep/^$uname:$udom$/,@senders) {
                   5627:                     $match = 0;
                   5628:                 }
                   5629:             }
                   5630:             if ($match == 1) {
                   5631:                 $qresult.=$key.'='.$value.'&';
                   5632:             }
                   5633:         }
1.311     albertel 5634:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5635:             chop($qresult);
1.387     albertel 5636:             &Reply($client, \$qresult, $userinput);
1.299     raeburn  5637:         } else {
                   5638:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5639:                     "while attempting dcmaildump\n", $userinput);
                   5640:         }
                   5641:     } else {
                   5642:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5643:                 "while attempting dcmaildump\n", $userinput);
                   5644:     }
                   5645:     return 1;
                   5646: }
                   5647: 
                   5648: &register_handler("dcmaildump", \&dump_dcmail_handler, 0, 1, 0);
                   5649: 
                   5650: #
                   5651: # Puts domain roles in nohist_domainroles database
                   5652: #
                   5653: # Parameters
                   5654: #   $cmd       - Command keyword that caused us to be dispatched.
                   5655: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5656: #               domain - the domain whose roles we are recording  
                   5657: #               role -   Consists of key=value pair
                   5658: #                        where key is unique role
                   5659: #                        and value is start/end date information
                   5660: #   $client    - Socket open on the client.
                   5661: #
                   5662: # Returns:
                   5663: #    1 - indicating processing should continue.
                   5664: # Side effects
                   5665: #     reply is written to $client.
                   5666: #
                   5667: 
                   5668: sub put_domainroles_handler {
                   5669:     my ($cmd,$tail,$client) = @_;
                   5670: 
                   5671:     my $userinput = "$cmd:$tail";
                   5672:     my ($udom,$what)=split(/:/,$tail);
                   5673:     chomp($what);
                   5674:     my @pairs=split(/\&/,$what);
                   5675:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   5676:     if ($hashref) {
                   5677:         foreach my $pair (@pairs) {
                   5678:             my ($key,$value)=split(/=/,$pair);
                   5679:             $hashref->{$key}=$value;
                   5680:         }
1.311     albertel 5681:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5682:             &Reply($client, "ok\n", $userinput);
                   5683:         } else {
                   5684:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5685:                      "while attempting domroleput\n", $userinput);
                   5686:         }
                   5687:     } else {
                   5688:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5689:                   "while attempting domroleput\n", $userinput);
                   5690:     }
                   5691:                                                                                   
                   5692:     return 1;
                   5693: }
                   5694: 
                   5695: &register_handler("domroleput", \&put_domainroles_handler, 0, 1, 0);
                   5696: 
                   5697: #
                   5698: # Retrieves domain roles from nohist_domainroles database
                   5699: # Returns to client an & separated list of key=value pairs,
                   5700: # where key is role and value is start and end date information.
                   5701: #
                   5702: # Parameters
                   5703: #   $cmd       - Command keyword that caused us to be dispatched.
                   5704: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5705: #               domain - the domain whose domain roles table we dump
                   5706: #   $client    - Socket open on the client.
                   5707: #
                   5708: # Returns:
                   5709: #    1 - indicating processing should continue.
                   5710: # Side effects
                   5711: #     reply (& separated list of role=start/end info pairs) is
                   5712: #     written to $client.
                   5713: #
                   5714: sub dump_domainroles_handler {
                   5715:     my ($cmd, $tail, $client) = @_;
                   5716:                                                                                            
                   5717:     my $userinput = "$cmd:$tail";
                   5718:     my ($udom,$startfilter,$endfilter,$rolesfilter) = split(/:/,$tail);
                   5719:     chomp($rolesfilter);
                   5720:     my @roles = ();
                   5721:     if (defined($startfilter)) {
                   5722:         $startfilter=&unescape($startfilter);
                   5723:     } else {
                   5724:         $startfilter='.';
                   5725:     }
                   5726:     if (defined($endfilter)) {
                   5727:         $endfilter=&unescape($endfilter);
                   5728:     } else {
                   5729:         $endfilter='.';
                   5730:     }
                   5731:     if (defined($rolesfilter)) {
                   5732:         $rolesfilter=&unescape($rolesfilter);
1.300     albertel 5733: 	@roles = split(/\&/,$rolesfilter);
1.299     raeburn  5734:     }
1.421     raeburn  5735: 
1.299     raeburn  5736:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   5737:     if ($hashref) {
                   5738:         my $qresult = '';
                   5739:         while (my ($key,$value) = each(%$hashref)) {
                   5740:             my $match = 1;
1.421     raeburn  5741:             my ($end,$start) = split(/:/,&unescape($value));
1.299     raeburn  5742:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,&unescape($key));
1.421     raeburn  5743:             unless (@roles < 1) {
                   5744:                 unless (grep/^\Q$trole\E$/,@roles) {
                   5745:                     $match = 0;
                   5746:                     next;
                   5747:                 }
                   5748:             }
1.299     raeburn  5749:             unless ($startfilter eq '.' || !defined($startfilter)) {
1.415     raeburn  5750:                 if ((defined($start)) && ($start >= $startfilter)) {
1.299     raeburn  5751:                     $match = 0;
1.421     raeburn  5752:                     next;
1.299     raeburn  5753:                 }
                   5754:             }
                   5755:             unless ($endfilter eq '.' || !defined($endfilter)) {
1.421     raeburn  5756:                 if ((defined($end)) && (($end > 0) && ($end <= $endfilter))) {
1.299     raeburn  5757:                     $match = 0;
1.421     raeburn  5758:                     next;
1.299     raeburn  5759:                 }
                   5760:             }
                   5761:             if ($match == 1) {
                   5762:                 $qresult.=$key.'='.$value.'&';
                   5763:             }
                   5764:         }
1.311     albertel 5765:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5766:             chop($qresult);
1.387     albertel 5767:             &Reply($client, \$qresult, $userinput);
1.299     raeburn  5768:         } else {
                   5769:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5770:                     "while attempting domrolesdump\n", $userinput);
                   5771:         }
                   5772:     } else {
                   5773:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5774:                 "while attempting domrolesdump\n", $userinput);
                   5775:     }
                   5776:     return 1;
                   5777: }
                   5778: 
                   5779: &register_handler("domrolesdump", \&dump_domainroles_handler, 0, 1, 0);
                   5780: 
                   5781: 
1.238     foxr     5782: #  Process the tmpput command I'm not sure what this does.. Seems to
                   5783: #  create a file in the lonDaemons/tmp directory of the form $id.tmp
                   5784: # where Id is the client's ip concatenated with a sequence number.
                   5785: # The file will contain some value that is passed in.  Is this e.g.
                   5786: # a login token?
                   5787: #
                   5788: # Parameters:
                   5789: #    $cmd     - The command that got us dispatched.
                   5790: #    $tail    - The remainder of the request following $cmd:
                   5791: #               In this case this will be the contents of the file.
                   5792: #    $client  - Socket connected to the client.
                   5793: # Returns:
                   5794: #    1 indicating processing can continue.
                   5795: # Side effects:
                   5796: #   A file is created in the local filesystem.
                   5797: #   A reply is sent to the client.
                   5798: sub tmp_put_handler {
                   5799:     my ($cmd, $what, $client) = @_;
                   5800: 
                   5801:     my $userinput = "$cmd:$what";	# Reconstruct for logging.
                   5802: 
1.347     raeburn  5803:     my ($record,$context) = split(/:/,$what);
                   5804:     if ($context ne '') {
                   5805:         chomp($context);
                   5806:         $context = &unescape($context);
                   5807:     }
                   5808:     my ($id,$store);
1.238     foxr     5809:     $tmpsnum++;
1.569     raeburn  5810:     my $numtries = 0;
                   5811:     my $execdir=$perlvar{'lonDaemons'};
                   5812:     if (($context eq 'resetpw') || ($context eq 'createaccount') ||
                   5813:         ($context eq 'sso') || ($context eq 'link') || ($context eq 'retry')) {
                   5814:         $id = &md5_hex(&md5_hex(time.{}.rand().$$.$tmpsnum));
                   5815:         while ((-e "$execdir/tmp/$id.tmp") && ($numtries <10)) {
                   5816:             undef($id);
                   5817:             $id = &md5_hex(&md5_hex(time.{}.rand().$$.$tmpsnum));
                   5818:             $numtries ++;
                   5819:         }
1.347     raeburn  5820:     } else {
                   5821:         $id = $$.'_'.$clientip.'_'.$tmpsnum;
                   5822:     }
1.238     foxr     5823:     $id=~s/\W/\_/g;
1.347     raeburn  5824:     $record=~s/\n//g;
1.569     raeburn  5825:     if (($id ne '') &&
                   5826:         ($store=IO::File->new(">$execdir/tmp/$id.tmp"))) {
1.347     raeburn  5827: 	print $store $record;
1.238     foxr     5828: 	close $store;
1.387     albertel 5829: 	&Reply($client, \$id, $userinput);
1.238     foxr     5830:     } else {
                   5831: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   5832: 		  "while attempting tmpput\n", $userinput);
                   5833:     }
                   5834:     return 1;
                   5835:   
                   5836: }
                   5837: &register_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
1.263     albertel 5838: 
1.238     foxr     5839: #   Processes the tmpget command.  This command returns the contents
                   5840: #  of a temporary resource file(?) created via tmpput.
                   5841: #
                   5842: # Paramters:
                   5843: #    $cmd      - Command that got us dispatched.
                   5844: #    $id       - Tail of the command, contain the id of the resource
                   5845: #                we want to fetch.
                   5846: #    $client   - socket open on the client.
                   5847: # Return:
                   5848: #    1         - Inidcating processing can continue.
                   5849: # Side effects:
                   5850: #   A reply is sent to the client.
                   5851: #
                   5852: sub tmp_get_handler {
                   5853:     my ($cmd, $id, $client) = @_;
                   5854: 
                   5855:     my $userinput = "$cmd:$id"; 
                   5856:     
                   5857: 
                   5858:     $id=~s/\W/\_/g;
                   5859:     my $store;
                   5860:     my $execdir=$perlvar{'lonDaemons'};
                   5861:     if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
                   5862: 	my $reply=<$store>;
1.387     albertel 5863: 	&Reply( $client, \$reply, $userinput);
1.238     foxr     5864: 	close $store;
                   5865:     } else {
                   5866: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   5867: 		  "while attempting tmpget\n", $userinput);
                   5868:     }
                   5869: 
                   5870:     return 1;
                   5871: }
                   5872: &register_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
1.263     albertel 5873: 
1.238     foxr     5874: #
                   5875: #  Process the tmpdel command.  This command deletes a temp resource
                   5876: #  created by the tmpput command.
                   5877: #
                   5878: # Parameters:
                   5879: #   $cmd      - Command that got us here.
                   5880: #   $id       - Id of the temporary resource created.
                   5881: #   $client   - socket open on the client process.
                   5882: #
                   5883: # Returns:
                   5884: #   1     - Indicating processing should continue.
                   5885: # Side Effects:
                   5886: #   A file is deleted
                   5887: #   A reply is sent to the client.
                   5888: sub tmp_del_handler {
                   5889:     my ($cmd, $id, $client) = @_;
                   5890:     
                   5891:     my $userinput= "$cmd:$id";
                   5892:     
                   5893:     chomp($id);
                   5894:     $id=~s/\W/\_/g;
                   5895:     my $execdir=$perlvar{'lonDaemons'};
                   5896:     if (unlink("$execdir/tmp/$id.tmp")) {
                   5897: 	&Reply($client, "ok\n", $userinput);
                   5898:     } else {
                   5899: 	&Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
                   5900: 		  "while attempting tmpdel\n", $userinput);
                   5901:     }
                   5902:     
                   5903:     return 1;
                   5904: 
                   5905: }
                   5906: &register_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
1.263     albertel 5907: 
1.238     foxr     5908: #
1.564     raeburn  5909: #  Process the updatebalcookie command.  This command updates a
                   5910: #  cookie in the lonBalancedir directory on a load balancer node.
                   5911: #
                   5912: # Parameters:
                   5913: #   $cmd      - Command that got us here.
                   5914: #   $tail     - Tail of the request (escaped cookie: escaped current entry)
                   5915: #
                   5916: #   $client   - socket open on the client process.
                   5917: #
                   5918: # Returns:
                   5919: #   1     - Indicating processing should continue.
                   5920: # Side Effects:
                   5921: #   A cookie file is updated from the lonBalancedir directory
                   5922: #   A reply is sent to the client.
                   5923: #
                   5924: sub update_balcookie_handler {
                   5925:     my ($cmd, $tail, $client) = @_;
                   5926: 
                   5927:     my $userinput= "$cmd:$tail";
                   5928:     chomp($tail);
                   5929:     my ($cookie,$lastentry) = map { &unescape($_) } (split(/:/,$tail));
                   5930: 
                   5931:     my $updatedone;
                   5932:     if ($cookie =~ /^$LONCAPA::match_domain\_$LONCAPA::match_username\_[a-f0-9]{32}$/) {
                   5933:         my $execdir=$perlvar{'lonBalanceDir'};
                   5934:         if (-e "$execdir/$cookie.id") {
                   5935:             my $doupdate;
                   5936:             if (open(my $fh,'<',"$execdir/$cookie.id")) {
                   5937:                 while (my $line = <$fh>) {
                   5938:                     chomp($line);
                   5939:                     if ($line eq $lastentry) {
                   5940:                         $doupdate = 1;
                   5941:                         last;
                   5942:                     }
                   5943:                 }
                   5944:                 close($fh);
                   5945:             }
                   5946:             if ($doupdate) {
                   5947:                 if (open(my $fh,'>',"$execdir/$cookie.id")) {
                   5948:                     print $fh $clientname;
                   5949:                     close($fh);
                   5950:                     $updatedone = 1;
                   5951:                 }
                   5952:             }
                   5953:         }
                   5954:     }
                   5955:     if ($updatedone) {
                   5956:         &Reply($client, "ok\n", $userinput);
                   5957:     } else {
                   5958:         &Failure( $client, "error: ".($!+0)."file update failed ".
                   5959:                   "while attempting updatebalcookie\n", $userinput);
                   5960:     }
                   5961:     return 1;
                   5962: }
                   5963: &register_handler("updatebalcookie", \&update_balcookie_handler, 0, 1, 0);
                   5964: 
                   5965: #
1.551     raeburn  5966: #  Process the delbalcookie command. This command deletes a balancer
1.564     raeburn  5967: #  cookie in the lonBalancedir directory on a load balancer node.
1.551     raeburn  5968: #
                   5969: # Parameters:
                   5970: #   $cmd      - Command that got us here.
                   5971: #   $cookie   - Cookie to be deleted.
                   5972: #   $client   - socket open on the client process.
                   5973: #
                   5974: # Returns:
                   5975: #   1     - Indicating processing should continue.
                   5976: # Side Effects:
                   5977: #   A cookie file is deleted from the lonBalancedir directory
                   5978: #   A reply is sent to the client.
                   5979: sub del_balcookie_handler {
                   5980:     my ($cmd, $cookie, $client) = @_;
                   5981: 
                   5982:     my $userinput= "$cmd:$cookie";
                   5983: 
                   5984:     chomp($cookie);
1.564     raeburn  5985:     $cookie = &unescape($cookie);
1.551     raeburn  5986:     my $deleted = '';
                   5987:     if ($cookie =~ /^$LONCAPA::match_domain\_$LONCAPA::match_username\_[a-f0-9]{32}$/) {
                   5988:         my $execdir=$perlvar{'lonBalanceDir'};
                   5989:         if (-e "$execdir/$cookie.id") {
                   5990:             if (open(my $fh,'<',"$execdir/$cookie.id")) {
                   5991:                 my $dodelete;
                   5992:                 while (my $line = <$fh>) {
                   5993:                     chomp($line);
                   5994:                     if ($line eq $clientname) {
                   5995:                         $dodelete = 1;
1.554     raeburn  5996:                         last;
1.551     raeburn  5997:                     }
                   5998:                 }
1.554     raeburn  5999:                 close($fh);
1.551     raeburn  6000:                 if ($dodelete) {
                   6001:                     if (unlink("$execdir/$cookie.id")) {
                   6002:                         $deleted = 1;
                   6003:                     }
                   6004:                 }
                   6005:             }
                   6006:         }
                   6007:     }
                   6008:     if ($deleted) {
                   6009:         &Reply($client, "ok\n", $userinput);
                   6010:     } else {
                   6011:         &Failure( $client, "error: ".($!+0)."Unlinking cookie file Failed ".
                   6012:                   "while attempting delbalcookie\n", $userinput);
                   6013:     }
                   6014:     return 1;
                   6015: }
                   6016: &register_handler("delbalcookie", \&del_balcookie_handler, 0, 1, 0);
                   6017: 
                   6018: #
1.246     foxr     6019: #   Processes the setannounce command.  This command
                   6020: #   creates a file named announce.txt in the top directory of
                   6021: #   the documentn root and sets its contents.  The announce.txt file is
                   6022: #   printed in its entirety at the LonCAPA login page.  Note:
                   6023: #   once the announcement.txt fileis created it cannot be deleted.
                   6024: #   However, setting the contents of the file to empty removes the
                   6025: #   announcement from the login page of loncapa so who cares.
                   6026: #
                   6027: # Parameters:
                   6028: #    $cmd          - The command that got us dispatched.
                   6029: #    $announcement - The text of the announcement.
                   6030: #    $client       - Socket open on the client process.
                   6031: # Retunrns:
                   6032: #   1             - Indicating request processing should continue
                   6033: # Side Effects:
                   6034: #   The file {DocRoot}/announcement.txt is created.
                   6035: #   A reply is sent to $client.
                   6036: #
                   6037: sub set_announce_handler {
                   6038:     my ($cmd, $announcement, $client) = @_;
                   6039:   
                   6040:     my $userinput    = "$cmd:$announcement";
                   6041: 
                   6042:     chomp($announcement);
                   6043:     $announcement=&unescape($announcement);
                   6044:     if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
                   6045: 				'/announcement.txt')) {
                   6046: 	print $store $announcement;
                   6047: 	close $store;
                   6048: 	&Reply($client, "ok\n", $userinput);
                   6049:     } else {
                   6050: 	&Failure($client, "error: ".($!+0)."\n", $userinput);
                   6051:     }
                   6052: 
                   6053:     return 1;
                   6054: }
                   6055: &register_handler("setannounce", \&set_announce_handler, 0, 1, 0);
1.263     albertel 6056: 
1.246     foxr     6057: #
                   6058: #  Return the version of the daemon.  This can be used to determine
                   6059: #  the compatibility of cross version installations or, alternatively to
                   6060: #  simply know who's out of date and who isn't.  Note that the version
                   6061: #  is returned concatenated with the tail.
                   6062: # Parameters:
                   6063: #   $cmd        - the request that dispatched to us.
                   6064: #   $tail       - Tail of the request (client's version?).
                   6065: #   $client     - Socket open on the client.
                   6066: #Returns:
                   6067: #   1 - continue processing requests.
                   6068: # Side Effects:
                   6069: #   Replies with version to $client.
                   6070: sub get_version_handler {
                   6071:     my ($cmd, $tail, $client) = @_;
                   6072: 
                   6073:     my $userinput  = $cmd.$tail;
                   6074:     
                   6075:     &Reply($client, &version($userinput)."\n", $userinput);
                   6076: 
                   6077: 
                   6078:     return 1;
                   6079: }
                   6080: &register_handler("version", \&get_version_handler, 0, 1, 0);
1.263     albertel 6081: 
1.246     foxr     6082: #  Set the current host and domain.  This is used to support
                   6083: #  multihomed systems.  Each IP of the system, or even separate daemons
                   6084: #  on the same IP can be treated as handling a separate lonCAPA virtual
                   6085: #  machine.  This command selects the virtual lonCAPA.  The client always
                   6086: #  knows the right one since it is lonc and it is selecting the domain/system
                   6087: #  from the hosts.tab file.
                   6088: # Parameters:
                   6089: #    $cmd      - Command that dispatched us.
                   6090: #    $tail     - Tail of the command (domain/host requested).
                   6091: #    $socket   - Socket open on the client.
                   6092: #
                   6093: # Returns:
                   6094: #     1   - Indicates the program should continue to process requests.
                   6095: # Side-effects:
                   6096: #     The default domain/system context is modified for this daemon.
                   6097: #     a reply is sent to the client.
                   6098: #
                   6099: sub set_virtual_host_handler {
                   6100:     my ($cmd, $tail, $socket) = @_;
                   6101:   
                   6102:     my $userinput  ="$cmd:$tail";
                   6103: 
                   6104:     &Reply($client, &sethost($userinput)."\n", $userinput);
                   6105: 
                   6106: 
                   6107:     return 1;
                   6108: }
1.247     albertel 6109: &register_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
1.246     foxr     6110: 
                   6111: #  Process a request to exit:
                   6112: #   - "bye" is sent to the client.
                   6113: #   - The client socket is shutdown and closed.
                   6114: #   - We indicate to the caller that we should exit.
                   6115: # Formal Parameters:
                   6116: #   $cmd                - The command that got us here.
                   6117: #   $tail               - Tail of the command (empty).
                   6118: #   $client             - Socket open on the tail.
                   6119: # Returns:
                   6120: #   0      - Indicating the program should exit!!
                   6121: #
                   6122: sub exit_handler {
                   6123:     my ($cmd, $tail, $client) = @_;
                   6124: 
                   6125:     my $userinput = "$cmd:$tail";
                   6126: 
                   6127:     &logthis("Client $clientip ($clientname) hanging up: $userinput");
                   6128:     &Reply($client, "bye\n", $userinput);
                   6129:     $client->shutdown(2);        # shutdown the socket forcibly.
                   6130:     $client->close();
                   6131: 
                   6132:     return 0;
                   6133: }
1.248     foxr     6134: &register_handler("exit", \&exit_handler, 0,1,1);
                   6135: &register_handler("init", \&exit_handler, 0,1,1);
                   6136: &register_handler("quit", \&exit_handler, 0,1,1);
                   6137: 
                   6138: #  Determine if auto-enrollment is enabled.
                   6139: #  Note that the original had what I believe to be a defect.
                   6140: #  The original returned 0 if the requestor was not a registerd client.
                   6141: #  It should return "refused".
                   6142: # Formal Parameters:
                   6143: #   $cmd       - The command that invoked us.
                   6144: #   $tail      - The tail of the command (Extra command parameters.
                   6145: #   $client    - The socket open on the client that issued the request.
                   6146: # Returns:
                   6147: #    1         - Indicating processing should continue.
                   6148: #
                   6149: sub enrollment_enabled_handler {
                   6150:     my ($cmd, $tail, $client) = @_;
                   6151:     my $userinput = $cmd.":".$tail; # For logging purposes.
                   6152: 
                   6153:     
1.337     albertel 6154:     my ($cdom) = split(/:/, $tail, 2);   # Domain we're asking about.
                   6155: 
1.248     foxr     6156:     my $outcome  = &localenroll::run($cdom);
1.387     albertel 6157:     &Reply($client, \$outcome, $userinput);
1.248     foxr     6158: 
                   6159:     return 1;
                   6160: }
                   6161: &register_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
                   6162: 
1.417     raeburn  6163: #
1.423     raeburn  6164: #   Validate an institutional code used for a LON-CAPA course.          
1.417     raeburn  6165: #
                   6166: # Formal Parameters:
                   6167: #   $cmd          - The command request that got us dispatched.
                   6168: #   $tail         - The tail of the command.  In this case,
                   6169: #                   this is a colon separated set of words that will be split
                   6170: #                   into:
1.424     raeburn  6171: #                        $dom      - The domain for which the check of 
                   6172: #                                    institutional course code will occur.
                   6173: #
                   6174: #                        $instcode - The institutional code for the course
                   6175: #                                    being requested, or validated for rights
                   6176: #                                    to request.
                   6177: #
                   6178: #                        $owner    - The course requestor (who will be the
                   6179: #                                    course owner, in the form username:domain
                   6180: #
1.417     raeburn  6181: #   $client       - Socket open on the client.
                   6182: # Returns:
                   6183: #    1           - Indicating processing should continue.
                   6184: #
                   6185: sub validate_instcode_handler {
                   6186:     my ($cmd, $tail, $client) = @_;
                   6187:     my $userinput = "$cmd:$tail";
1.423     raeburn  6188:     my ($dom,$instcode,$owner) = split(/:/, $tail);
1.422     raeburn  6189:     $instcode = &unescape($instcode);
                   6190:     $owner = &unescape($owner);
1.498     raeburn  6191:     my ($outcome,$description,$credits) = 
1.426     raeburn  6192:         &localenroll::validate_instcode($dom,$instcode,$owner);
1.498     raeburn  6193:     my $result = &escape($outcome).'&'.&escape($description).'&'.
                   6194:                  &escape($credits);
1.426     raeburn  6195:     &Reply($client, \$result, $userinput);
1.417     raeburn  6196: 
                   6197:     return 1;
                   6198: }
                   6199: &register_handler("autovalidateinstcode", \&validate_instcode_handler, 0, 1, 0);
                   6200: 
1.566     raeburn  6201: #
                   6202: #  Validate co-owner for cross-listed institutional code and
                   6203: #  institutional course code itself used for a LON-CAPA course.
                   6204: #
                   6205: # Formal Parameters:
                   6206: #   $cmd          - The command request that got us dispatched.
                   6207: #   $tail         - The tail of the command.  In this case,
                   6208: #                   this is a colon separated string containing:
                   6209: #      $dom            - Course's LON-CAPA domain
                   6210: #      $instcode       - Institutional course code for the course
                   6211: #      $inst_xlist     - Institutional course Id for the crosslisting
                   6212: #      $coowner        - Username of co-owner
                   6213: #      (values for all but $dom have been escaped). 
                   6214: #
                   6215: #   $client       - Socket open on the client.
                   6216: # Returns:
                   6217: #    1           - Indicating processing should continue.
                   6218: #
                   6219: sub validate_instcrosslist_handler  {
                   6220:     my ($cmd, $tail, $client) = @_;
                   6221:     my $userinput = "$cmd:$tail";
                   6222:     my ($dom,$instcode,$inst_xlist,$coowner) = split(/:/,$tail);
                   6223:     $instcode = &unescape($instcode);
                   6224:     $inst_xlist = &unescape($inst_xlist);
                   6225:     $coowner = &unescape($coowner);
                   6226:     my $outcome = &localenroll::validate_crosslist_access($dom,$instcode,
                   6227:                                                           $inst_xlist,$coowner);
                   6228:     &Reply($client, \$outcome, $userinput);
                   6229: 
                   6230:     return 1;
                   6231: }
                   6232: &register_handler("autovalidateinstcrosslist", \&validate_instcrosslist_handler, 0, 1, 0);
                   6233: 
1.248     foxr     6234: #   Get the official sections for which auto-enrollment is possible.
                   6235: #   Since the admin people won't know about 'unofficial sections' 
                   6236: #   we cannot auto-enroll on them.
                   6237: # Formal Parameters:
                   6238: #    $cmd     - The command request that got us dispatched here.
                   6239: #    $tail    - The remainder of the request.  In our case this
                   6240: #               will be split into:
                   6241: #               $coursecode   - The course name from the admin point of view.
                   6242: #               $cdom         - The course's domain(?).
                   6243: #    $client  - Socket open on the client.
                   6244: # Returns:
                   6245: #    1    - Indiciting processing should continue.
                   6246: #
                   6247: sub get_sections_handler {
                   6248:     my ($cmd, $tail, $client) = @_;
                   6249:     my $userinput = "$cmd:$tail";
                   6250: 
                   6251:     my ($coursecode, $cdom) = split(/:/, $tail);
                   6252:     my @secs = &localenroll::get_sections($coursecode,$cdom);
                   6253:     my $seclist = &escape(join(':',@secs));
                   6254: 
1.387     albertel 6255:     &Reply($client, \$seclist, $userinput);
1.248     foxr     6256:     
                   6257: 
                   6258:     return 1;
                   6259: }
                   6260: &register_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
                   6261: 
                   6262: #   Validate the owner of a new course section.  
                   6263: #
                   6264: # Formal Parameters:
                   6265: #   $cmd      - Command that got us dispatched.
                   6266: #   $tail     - the remainder of the command.  For us this consists of a
                   6267: #               colon separated string containing:
                   6268: #                  $inst    - Course Id from the institutions point of view.
                   6269: #                  $owner   - Proposed owner of the course.
                   6270: #                  $cdom    - Domain of the course (from the institutions
                   6271: #                             point of view?)..
                   6272: #   $client   - Socket open on the client.
                   6273: #
                   6274: # Returns:
                   6275: #   1        - Processing should continue.
                   6276: #
                   6277: sub validate_course_owner_handler {
                   6278:     my ($cmd, $tail, $client)  = @_;
                   6279:     my $userinput = "$cmd:$tail";
1.470     raeburn  6280:     my ($inst_course_id, $owner, $cdom, $coowners) = split(/:/, $tail);
                   6281:     
1.336     raeburn  6282:     $owner = &unescape($owner);
1.470     raeburn  6283:     $coowners = &unescape($coowners);
                   6284:     my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom,$coowners);
1.387     albertel 6285:     &Reply($client, \$outcome, $userinput);
1.248     foxr     6286: 
                   6287: 
                   6288: 
                   6289:     return 1;
                   6290: }
                   6291: &register_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
1.263     albertel 6292: 
1.248     foxr     6293: #
                   6294: #   Validate a course section in the official schedule of classes
                   6295: #   from the institutions point of view (part of autoenrollment).
                   6296: #
                   6297: # Formal Parameters:
                   6298: #   $cmd          - The command request that got us dispatched.
                   6299: #   $tail         - The tail of the command.  In this case,
                   6300: #                   this is a colon separated set of words that will be split
                   6301: #                   into:
                   6302: #                        $inst_course_id - The course/section id from the
                   6303: #                                          institutions point of view.
                   6304: #                        $cdom           - The domain from the institutions
                   6305: #                                          point of view.
                   6306: #   $client       - Socket open on the client.
                   6307: # Returns:
                   6308: #    1           - Indicating processing should continue.
                   6309: #
                   6310: sub validate_course_section_handler {
                   6311:     my ($cmd, $tail, $client) = @_;
                   6312:     my $userinput = "$cmd:$tail";
                   6313:     my ($inst_course_id, $cdom) = split(/:/, $tail);
                   6314: 
                   6315:     my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
1.387     albertel 6316:     &Reply($client, \$outcome, $userinput);
1.248     foxr     6317: 
                   6318: 
                   6319:     return 1;
                   6320: }
                   6321: &register_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
                   6322: 
                   6323: #
1.340     raeburn  6324: #   Validate course owner's access to enrollment data for specific class section. 
                   6325: #   
                   6326: #
                   6327: # Formal Parameters:
                   6328: #    $cmd     - The command request that got us dispatched.
                   6329: #    $tail    - The tail of the command.   In this case this is a colon separated
1.542     raeburn  6330: #               set of values that will be split into:
1.340     raeburn  6331: #               $inst_class  - Institutional code for the specific class section   
1.542     raeburn  6332: #               $ownerlist   - An escaped comma-separated list of username:domain 
                   6333: #                              of the course owner, and co-owner(s).
1.340     raeburn  6334: #               $cdom        - The domain of the course from the institution's
                   6335: #                              point of view.
                   6336: #    $client  - The socket open on the client.
                   6337: # Returns:
                   6338: #    1 - continue processing.
                   6339: #
                   6340: 
                   6341: sub validate_class_access_handler {
                   6342:     my ($cmd, $tail, $client) = @_;
                   6343:     my $userinput = "$cmd:$tail";
1.383     raeburn  6344:     my ($inst_class,$ownerlist,$cdom) = split(/:/, $tail);
1.392     raeburn  6345:     my $owners = &unescape($ownerlist);
1.341     albertel 6346:     my $outcome;
                   6347:     eval {
                   6348: 	local($SIG{__DIE__})='DEFAULT';
1.392     raeburn  6349: 	$outcome=&localenroll::check_section($inst_class,$owners,$cdom);
1.341     albertel 6350:     };
1.387     albertel 6351:     &Reply($client,\$outcome, $userinput);
1.340     raeburn  6352: 
                   6353:     return 1;
                   6354: }
                   6355: &register_handler("autovalidateclass_sec", \&validate_class_access_handler, 0, 1, 0);
                   6356: 
                   6357: #
1.567     raeburn  6358: #    Modify institutional sections (using customized &instsec_reformat()
                   6359: #    routine in localenroll.pm), to either clutter or declutter, for  
                   6360: #    purposes of ensuring an institutional course section (string) can
                   6361: #    be unambiguously separated into institutional course and section.
                   6362: #
                   6363: # Formal Parameters:
                   6364: #    $cmd     - The command request that got us dispatched.
                   6365: #    $tail    - The tail of the command.   In this case this is a colon separated
                   6366: #               set of values that will be split into:
                   6367: #               $cdom        - The LON-CAPA domain of the course.
                   6368: #               $action      - Either: clutter or declutter
                   6369: #                              clutter adds character(s) to eliminate ambiguity
                   6370: #                              declutter removes the added characters (e.g., for
                   6371: #                              display of the institutional course section string.
                   6372: #               $info        - A frozen hash in which keys are: 
                   6373: #                              LON-CAPA course number:Institutional course code
                   6374: #                              and values are a reference to an array of the
                   6375: #                              items to modify -- either institutional sections,
                   6376: #                              or institutional course sections (for crosslistings). 
                   6377: #    $client  - The socket open on the client.
                   6378: # Returns:
                   6379: #    1 - continue processing.
                   6380: #   
                   6381: 
                   6382: sub instsec_reformat_handler {
                   6383:     my ($cmd, $tail, $client) = @_;
                   6384:     my $userinput = "$cmd:$tail";
                   6385:     my ($cdom,$action,$info) = split(/:/,$tail);
                   6386:     my $instsecref = &Apache::lonnet::thaw_unescape($info);
                   6387:     my ($outcome,$result);
                   6388:     eval {
                   6389:         local($SIG{__DIE__})='DEFAULT';
                   6390:         $outcome=&localenroll::instsec_reformat($cdom,$action,$instsecref);
                   6391:         if ($outcome eq 'ok') {
                   6392:             if (ref($instsecref) eq 'HASH') {
                   6393:                 foreach my $key (keys(%{$instsecref})) {
                   6394:                     $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($instsecref->{$key}).'&';
                   6395:                 }
                   6396:                 $result =~ s/\&$//;
                   6397:             }
                   6398:         }
                   6399:     };
                   6400:     if (!$@) {
                   6401:         if ($outcome eq 'ok') {
                   6402:             &Reply( $client, \$result, $userinput);
                   6403:         } else {
                   6404:             &Reply($client,\$outcome, $userinput);
                   6405:         }
                   6406:     } else {
                   6407:         &Failure($client,"unknown_cmd\n",$userinput);
                   6408:     }
                   6409:     return 1;
                   6410: }
                   6411: &register_handler("autoinstsecreformat",\&instsec_reformat_handler, 0, 1, 0);
                   6412: 
                   6413: #
1.542     raeburn  6414: #   Validate course owner or co-owners(s) access to enrollment data for all sections
                   6415: #   and crosslistings for a particular course.
                   6416: #
                   6417: #
                   6418: # Formal Parameters:
                   6419: #    $cmd     - The command request that got us dispatched.
                   6420: #    $tail    - The tail of the command.   In this case this is a colon separated
                   6421: #               set of values that will be split into:
                   6422: #               $ownerlist   - An escaped comma-separated list of username:domain
                   6423: #                              of the course owner, and co-owner(s).
                   6424: #               $cdom        - The domain of the course from the institution's
                   6425: #                              point of view.
                   6426: #               $classes     - Frozen hash of institutional course sections and
                   6427: #                              crosslistings.
                   6428: #    $client  - The socket open on the client.
                   6429: # Returns:
                   6430: #    1 - continue processing.
                   6431: #
                   6432: 
                   6433: sub validate_classes_handler {
                   6434:     my ($cmd, $tail, $client) = @_;
                   6435:     my $userinput = "$cmd:$tail";
                   6436:     my ($ownerlist,$cdom,$classes) = split(/:/, $tail);
                   6437:     my $classesref = &Apache::lonnet::thaw_unescape($classes);
                   6438:     my $owners = &unescape($ownerlist);
                   6439:     my $result;
                   6440:     eval {
                   6441:         local($SIG{__DIE__})='DEFAULT';
                   6442:         my %validations;
                   6443:         my $response = &localenroll::check_instclasses($owners,$cdom,$classesref,
                   6444:                                                        \%validations);
                   6445:         if ($response eq 'ok') {
                   6446:             foreach my $key (keys(%validations)) {
                   6447:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
                   6448:             }
                   6449:             $result =~ s/\&$//;
                   6450:         } else {
                   6451:             $result = 'error';
                   6452:         }
                   6453:     };
                   6454:     if (!$@) {
                   6455:         &Reply($client, \$result, $userinput);
                   6456:     } else {
                   6457:         &Failure($client,"unknown_cmd\n",$userinput);
                   6458:     }
                   6459:     return 1;
                   6460: }
                   6461: &register_handler("autovalidateinstclasses", \&validate_classes_handler, 0, 1, 0);
                   6462: 
                   6463: #
1.340     raeburn  6464: #   Create a password for a new LON-CAPA user added by auto-enrollment.
                   6465: #   Only used for case where authentication method for new user is localauth
1.248     foxr     6466: #
                   6467: # Formal Parameters:
                   6468: #    $cmd     - The command request that got us dispatched.
                   6469: #    $tail    - The tail of the command.   In this case this is a colon separated
                   6470: #               set of words that will be split into:
1.340     raeburn  6471: #               $authparam - An authentication parameter (localauth parameter).
1.248     foxr     6472: #               $cdom      - The domain of the course from the institution's
                   6473: #                            point of view.
                   6474: #    $client  - The socket open on the client.
                   6475: # Returns:
                   6476: #    1 - continue processing.
                   6477: #
                   6478: sub create_auto_enroll_password_handler {
                   6479:     my ($cmd, $tail, $client) = @_;
                   6480:     my $userinput = "$cmd:$tail";
                   6481: 
                   6482:     my ($authparam, $cdom) = split(/:/, $userinput);
                   6483: 
                   6484:     my ($create_passwd,$authchk);
                   6485:     ($authparam,
                   6486:      $create_passwd,
                   6487:      $authchk) = &localenroll::create_password($authparam,$cdom);
                   6488: 
                   6489:     &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
                   6490: 	   $userinput);
                   6491: 
                   6492: 
                   6493:     return 1;
                   6494: }
                   6495: &register_handler("autocreatepassword", \&create_auto_enroll_password_handler, 
                   6496: 		  0, 1, 0);
                   6497: 
1.522     raeburn  6498: sub auto_export_grades_handler {
                   6499:     my ($cmd, $tail, $client) = @_;
                   6500:     my $userinput = "$cmd:$tail";
                   6501:     my ($cdom,$cnum,$info,$data) = split(/:/,$tail);
                   6502:     my $inforef = &Apache::lonnet::thaw_unescape($info);
                   6503:     my $dataref = &Apache::lonnet::thaw_unescape($data);
                   6504:     my ($outcome,$result);;
                   6505:     eval {
                   6506:         local($SIG{__DIE__})='DEFAULT';
                   6507:         my %rtnhash;
                   6508:         $outcome=&localenroll::export_grades($cdom,$cnum,$inforef,$dataref,\%rtnhash);
                   6509:         if ($outcome eq 'ok') {
                   6510:             foreach my $key (keys(%rtnhash)) {
                   6511:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
                   6512:             }
                   6513:             $result =~ s/\&$//;
                   6514:         }
                   6515:     };
                   6516:     if (!$@) {
                   6517:         if ($outcome eq 'ok') {
                   6518:             if ($cipher) {
                   6519:                 my $cmdlength=length($result);
                   6520:                 $result.="         ";
                   6521:                 my $encresult='';
                   6522:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   6523:                     $encresult.= unpack("H16",
                   6524:                                         $cipher->encrypt(substr($result,
                   6525:                                                                 $encidx,
                   6526:                                                                 8)));
                   6527:                 }
                   6528:                 &Reply( $client, "enc:$cmdlength:$encresult\n", $userinput);
                   6529:             } else {
                   6530:                 &Failure( $client, "error:no_key\n", $userinput);
                   6531:             }
                   6532:         } else {
                   6533:             &Reply($client, "$outcome\n", $userinput);
                   6534:         }
                   6535:     } else {
                   6536:         &Failure($client,"export_error\n",$userinput);
                   6537:     }
                   6538:     return 1;
                   6539: }
                   6540: &register_handler("autoexportgrades", \&auto_export_grades_handler,
1.536     raeburn  6541:                   1, 1, 0);
1.522     raeburn  6542: 
1.248     foxr     6543: #   Retrieve and remove temporary files created by/during autoenrollment.
                   6544: #
                   6545: # Formal Parameters:
                   6546: #    $cmd      - The command that got us dispatched.
                   6547: #    $tail     - The tail of the command.  In our case this is a colon 
                   6548: #                separated list that will be split into:
1.526     raeburn  6549: #                $filename - The name of the file to retrieve.
1.248     foxr     6550: #                            The filename is given as a path relative to
                   6551: #                            the LonCAPA temp file directory.
                   6552: #    $client   - Socket open on the client.
                   6553: #
                   6554: # Returns:
                   6555: #   1     - Continue processing.
                   6556: sub retrieve_auto_file_handler {
                   6557:     my ($cmd, $tail, $client)    = @_;
                   6558:     my $userinput                = "cmd:$tail";
                   6559: 
                   6560:     my ($filename)   = split(/:/, $tail);
                   6561: 
                   6562:     my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
1.521     raeburn  6563: 
                   6564:     if ($filename =~m{/\.\./}) {
                   6565:         &Failure($client, "refused\n", $userinput);
1.526     raeburn  6566:     } elsif ($filename !~ /^$LONCAPA::match_domain\_$LONCAPA::match_courseid\_.+_classlist\.xml$/) {
                   6567:         &Failure($client, "refused\n", $userinput);
1.521     raeburn  6568:     } elsif ( (-e $source) && ($filename ne '') ) {
1.248     foxr     6569: 	my $reply = '';
                   6570: 	if (open(my $fh,$source)) {
                   6571: 	    while (<$fh>) {
                   6572: 		chomp($_);
                   6573: 		$_ =~ s/^\s+//g;
                   6574: 		$_ =~ s/\s+$//g;
                   6575: 		$reply .= $_;
                   6576: 	    }
                   6577: 	    close($fh);
                   6578: 	    &Reply($client, &escape($reply)."\n", $userinput);
                   6579: 
                   6580: #   Does this have to be uncommented??!?  (RF).
                   6581: #
                   6582: #                                unlink($source);
                   6583: 	} else {
                   6584: 	    &Failure($client, "error\n", $userinput);
                   6585: 	}
                   6586:     } else {
                   6587: 	&Failure($client, "error\n", $userinput);
                   6588:     }
                   6589:     
                   6590: 
                   6591:     return 1;
                   6592: }
                   6593: &register_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
                   6594: 
1.423     raeburn  6595: sub crsreq_checks_handler {
                   6596:     my ($cmd, $tail, $client) = @_;
                   6597:     my $userinput = "$cmd:$tail";
                   6598:     my $dom = $tail;
                   6599:     my $result;
1.519     raeburn  6600:     my @reqtypes = ('official','unofficial','community','textbook','placement');
1.423     raeburn  6601:     eval {
                   6602:         local($SIG{__DIE__})='DEFAULT';
                   6603:         my %validations;
1.424     raeburn  6604:         my $response = &localenroll::crsreq_checks($dom,\@reqtypes,
                   6605:                                                    \%validations);
1.423     raeburn  6606:         if ($response eq 'ok') { 
                   6607:             foreach my $key (keys(%validations)) {
                   6608:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
                   6609:             }
                   6610:             $result =~ s/\&$//;
                   6611:         } else {
                   6612:             $result = 'error';
                   6613:         }
                   6614:     };
                   6615:     if (!$@) {
                   6616:         &Reply($client, \$result, $userinput);
                   6617:     } else {
                   6618:         &Failure($client,"unknown_cmd\n",$userinput);
                   6619:     }
                   6620:     return 1;
                   6621: }
                   6622: &register_handler("autocrsreqchecks", \&crsreq_checks_handler, 0, 1, 0);
                   6623: 
                   6624: sub validate_crsreq_handler {
                   6625:     my ($cmd, $tail, $client) = @_;
                   6626:     my $userinput = "$cmd:$tail";
1.508     raeburn  6627:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$customdata) = split(/:/, $tail);
1.423     raeburn  6628:     $instcode = &unescape($instcode);
                   6629:     $owner = &unescape($owner);
                   6630:     $crstype = &unescape($crstype);
                   6631:     $inststatuslist = &unescape($inststatuslist);
                   6632:     $instcode = &unescape($instcode);
                   6633:     $instseclist = &unescape($instseclist);
1.508     raeburn  6634:     my $custominfo = &Apache::lonnet::thaw_unescape($customdata);
1.423     raeburn  6635:     my $outcome;
                   6636:     eval {
                   6637:         local($SIG{__DIE__})='DEFAULT';
                   6638:         $outcome = &localenroll::validate_crsreq($dom,$owner,$crstype,
                   6639:                                                  $inststatuslist,$instcode,
1.508     raeburn  6640:                                                  $instseclist,$custominfo);
1.423     raeburn  6641:     };
                   6642:     if (!$@) {
                   6643:         &Reply($client, \$outcome, $userinput);
                   6644:     } else {
                   6645:         &Failure($client,"unknown_cmd\n",$userinput);
                   6646:     }
                   6647:     return 1;
                   6648: }
                   6649: &register_handler("autocrsreqvalidation", \&validate_crsreq_handler, 0, 1, 0);
                   6650: 
1.506     raeburn  6651: sub crsreq_update_handler {
                   6652:     my ($cmd, $tail, $client) = @_;
                   6653:     my $userinput = "$cmd:$tail";
1.509     raeburn  6654:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,$code,
                   6655:         $accessstart,$accessend,$infohashref) =
1.506     raeburn  6656:         split(/:/, $tail);
                   6657:     $crstype = &unescape($crstype);
                   6658:     $action = &unescape($action);
                   6659:     $ownername = &unescape($ownername);
                   6660:     $ownerdomain = &unescape($ownerdomain);
                   6661:     $fullname = &unescape($fullname);
                   6662:     $title = &unescape($title);
                   6663:     $code = &unescape($code);
1.509     raeburn  6664:     $accessstart = &unescape($accessstart);
                   6665:     $accessend = &unescape($accessend);
1.506     raeburn  6666:     my $incoming = &Apache::lonnet::thaw_unescape($infohashref);
                   6667:     my ($result,$outcome);
                   6668:     eval {
                   6669:         local($SIG{__DIE__})='DEFAULT';
                   6670:         my %rtnhash;
                   6671:         $outcome = &localenroll::crsreq_updates($cdom,$cnum,$crstype,$action,
                   6672:                                                 $ownername,$ownerdomain,$fullname,
1.509     raeburn  6673:                                                 $title,$code,$accessstart,$accessend,
                   6674:                                                 $incoming,\%rtnhash);
1.506     raeburn  6675:         if ($outcome eq 'ok') {
1.515     raeburn  6676:             my @posskeys = qw(createdweb createdmsg createdcustomized createdactions queuedweb queuedmsg formitems reviewweb validationjs onload javascript);
1.506     raeburn  6677:             foreach my $key (keys(%rtnhash)) {
                   6678:                 if (grep(/^\Q$key\E/,@posskeys)) {
                   6679:                     $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
                   6680:                 }
                   6681:             }
                   6682:             $result =~ s/\&$//;
                   6683:         }
                   6684:     };
                   6685:     if (!$@) {
                   6686:         if ($outcome eq 'ok') {
                   6687:             &Reply($client, \$result, $userinput);
                   6688:         } else {
                   6689:             &Reply($client, "format_error\n", $userinput);
                   6690:         }
                   6691:     } else {
                   6692:         &Failure($client,"unknown_cmd\n",$userinput);
                   6693:     }
                   6694:     return 1;
                   6695: }
                   6696: &register_handler("autocrsrequpdate", \&crsreq_update_handler, 0, 1, 0);
                   6697: 
1.248     foxr     6698: #
                   6699: #   Read and retrieve institutional code format (for support form).
                   6700: # Formal Parameters:
                   6701: #    $cmd        - Command that dispatched us.
                   6702: #    $tail       - Tail of the command.  In this case it conatins 
                   6703: #                  the course domain and the coursename.
                   6704: #    $client     - Socket open on the client.
                   6705: # Returns:
                   6706: #    1     - Continue processing.
                   6707: #
                   6708: sub get_institutional_code_format_handler {
                   6709:     my ($cmd, $tail, $client)   = @_;
                   6710:     my $userinput               = "$cmd:$tail";
                   6711: 
                   6712:     my $reply;
                   6713:     my($cdom,$course) = split(/:/,$tail);
                   6714:     my @pairs = split/\&/,$course;
                   6715:     my %instcodes = ();
                   6716:     my %codes = ();
                   6717:     my @codetitles = ();
                   6718:     my %cat_titles = ();
                   6719:     my %cat_order = ();
                   6720:     foreach (@pairs) {
                   6721: 	my ($key,$value) = split/=/,$_;
                   6722: 	$instcodes{&unescape($key)} = &unescape($value);
                   6723:     }
                   6724:     my $formatreply = &localenroll::instcode_format($cdom,
                   6725: 						    \%instcodes,
                   6726: 						    \%codes,
                   6727: 						    \@codetitles,
                   6728: 						    \%cat_titles,
                   6729: 						    \%cat_order);
                   6730:     if ($formatreply eq 'ok') {
1.365     albertel 6731: 	my $codes_str = &Apache::lonnet::hash2str(%codes);
                   6732: 	my $codetitles_str = &Apache::lonnet::array2str(@codetitles);
                   6733: 	my $cat_titles_str = &Apache::lonnet::hash2str(%cat_titles);
                   6734: 	my $cat_order_str = &Apache::lonnet::hash2str(%cat_order);
1.248     foxr     6735: 	&Reply($client,
                   6736: 	       $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
                   6737: 	       .$cat_order_str."\n",
                   6738: 	       $userinput);
                   6739:     } else {
                   6740: 	# this else branch added by RF since if not ok, lonc will
                   6741: 	# hang waiting on reply until timeout.
                   6742: 	#
                   6743: 	&Reply($client, "format_error\n", $userinput);
                   6744:     }
                   6745:     
                   6746:     return 1;
                   6747: }
1.265     albertel 6748: &register_handler("autoinstcodeformat",
                   6749: 		  \&get_institutional_code_format_handler,0,1,0);
1.246     foxr     6750: 
1.345     raeburn  6751: sub get_institutional_defaults_handler {
                   6752:     my ($cmd, $tail, $client)   = @_;
                   6753:     my $userinput               = "$cmd:$tail";
                   6754: 
                   6755:     my $dom = $tail;
                   6756:     my %defaults_hash;
                   6757:     my @code_order;
                   6758:     my $outcome;
                   6759:     eval {
                   6760:         local($SIG{__DIE__})='DEFAULT';
                   6761:         $outcome = &localenroll::instcode_defaults($dom,\%defaults_hash,
                   6762:                                                    \@code_order);
                   6763:     };
                   6764:     if (!$@) {
                   6765:         if ($outcome eq 'ok') {
                   6766:             my $result='';
                   6767:             while (my ($key,$value) = each(%defaults_hash)) {
                   6768:                 $result.=&escape($key).'='.&escape($value).'&';
                   6769:             }
                   6770:             $result .= 'code_order='.&escape(join('&',@code_order));
1.387     albertel 6771:             &Reply($client,\$result,$userinput);
1.345     raeburn  6772:         } else {
                   6773:             &Reply($client,"error\n", $userinput);
                   6774:         }
                   6775:     } else {
                   6776:         &Failure($client,"unknown_cmd\n",$userinput);
                   6777:     }
                   6778: }
                   6779: &register_handler("autoinstcodedefaults",
                   6780:                   \&get_institutional_defaults_handler,0,1,0);
                   6781: 
1.416     raeburn  6782: sub get_possible_instcodes_handler {
                   6783:     my ($cmd, $tail, $client)   = @_;
                   6784:     my $userinput               = "$cmd:$tail";
                   6785: 
                   6786:     my $reply;
                   6787:     my $cdom = $tail;
1.417     raeburn  6788:     my (@codetitles,%cat_titles,%cat_order,@code_order);
1.416     raeburn  6789:     my $formatreply = &localenroll::possible_instcodes($cdom,
                   6790:                                                        \@codetitles,
                   6791:                                                        \%cat_titles,
1.417     raeburn  6792:                                                        \%cat_order,
                   6793:                                                        \@code_order);
1.416     raeburn  6794:     if ($formatreply eq 'ok') {
                   6795:         my $result = join('&',map {&escape($_);} (@codetitles)).':';
1.417     raeburn  6796:         $result .= join('&',map {&escape($_);} (@code_order)).':';
1.416     raeburn  6797:         foreach my $key (keys(%cat_titles)) {
                   6798:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_titles{$key}).'&';
                   6799:         }
                   6800:         $result =~ s/\&$//;
                   6801:         $result .= ':';
                   6802:         foreach my $key (keys(%cat_order)) {
                   6803:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_order{$key}).'&';
                   6804:         }
                   6805:         $result =~ s/\&$//;
                   6806:         &Reply($client,\$result,$userinput);
                   6807:     } else {
                   6808:         &Reply($client, "format_error\n", $userinput);
                   6809:     }
                   6810:     return 1;
                   6811: }
                   6812: &register_handler("autopossibleinstcodes",
                   6813:                   \&get_possible_instcodes_handler,0,1,0);
                   6814: 
1.381     raeburn  6815: sub get_institutional_user_rules {
                   6816:     my ($cmd, $tail, $client)   = @_;
                   6817:     my $userinput               = "$cmd:$tail";
                   6818:     my $dom = &unescape($tail);
                   6819:     my (%rules_hash,@rules_order);
                   6820:     my $outcome;
                   6821:     eval {
                   6822:         local($SIG{__DIE__})='DEFAULT';
                   6823:         $outcome = &localenroll::username_rules($dom,\%rules_hash,\@rules_order);
                   6824:     };
                   6825:     if (!$@) {
                   6826:         if ($outcome eq 'ok') {
                   6827:             my $result;
                   6828:             foreach my $key (keys(%rules_hash)) {
                   6829:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6830:             }
                   6831:             $result =~ s/\&$//;
                   6832:             $result .= ':';
                   6833:             if (@rules_order > 0) {
                   6834:                 foreach my $item (@rules_order) {
                   6835:                     $result .= &escape($item).'&';
                   6836:                 }
                   6837:             }
                   6838:             $result =~ s/\&$//;
1.387     albertel 6839:             &Reply($client,\$result,$userinput);
1.381     raeburn  6840:         } else {
                   6841:             &Reply($client,"error\n", $userinput);
                   6842:         }
                   6843:     } else {
                   6844:         &Failure($client,"unknown_cmd\n",$userinput);
                   6845:     }
                   6846: }
                   6847: &register_handler("instuserrules",\&get_institutional_user_rules,0,1,0);
                   6848: 
1.389     raeburn  6849: sub get_institutional_id_rules {
                   6850:     my ($cmd, $tail, $client)   = @_;
                   6851:     my $userinput               = "$cmd:$tail";
                   6852:     my $dom = &unescape($tail);
                   6853:     my (%rules_hash,@rules_order);
                   6854:     my $outcome;
                   6855:     eval {
                   6856:         local($SIG{__DIE__})='DEFAULT';
                   6857:         $outcome = &localenroll::id_rules($dom,\%rules_hash,\@rules_order);
                   6858:     };
                   6859:     if (!$@) {
                   6860:         if ($outcome eq 'ok') {
                   6861:             my $result;
                   6862:             foreach my $key (keys(%rules_hash)) {
                   6863:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6864:             }
                   6865:             $result =~ s/\&$//;
                   6866:             $result .= ':';
                   6867:             if (@rules_order > 0) {
                   6868:                 foreach my $item (@rules_order) {
                   6869:                     $result .= &escape($item).'&';
                   6870:                 }
                   6871:             }
                   6872:             $result =~ s/\&$//;
                   6873:             &Reply($client,\$result,$userinput);
                   6874:         } else {
                   6875:             &Reply($client,"error\n", $userinput);
                   6876:         }
                   6877:     } else {
                   6878:         &Failure($client,"unknown_cmd\n",$userinput);
                   6879:     }
                   6880: }
                   6881: &register_handler("instidrules",\&get_institutional_id_rules,0,1,0);
                   6882: 
1.397     raeburn  6883: sub get_institutional_selfcreate_rules {
1.396     raeburn  6884:     my ($cmd, $tail, $client)   = @_;
                   6885:     my $userinput               = "$cmd:$tail";
                   6886:     my $dom = &unescape($tail);
                   6887:     my (%rules_hash,@rules_order);
                   6888:     my $outcome;
                   6889:     eval {
                   6890:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  6891:         $outcome = &localenroll::selfcreate_rules($dom,\%rules_hash,\@rules_order);
1.396     raeburn  6892:     };
                   6893:     if (!$@) {
                   6894:         if ($outcome eq 'ok') {
                   6895:             my $result;
                   6896:             foreach my $key (keys(%rules_hash)) {
                   6897:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6898:             }
                   6899:             $result =~ s/\&$//;
                   6900:             $result .= ':';
                   6901:             if (@rules_order > 0) {
                   6902:                 foreach my $item (@rules_order) {
                   6903:                     $result .= &escape($item).'&';
                   6904:                 }
                   6905:             }
                   6906:             $result =~ s/\&$//;
                   6907:             &Reply($client,\$result,$userinput);
                   6908:         } else {
                   6909:             &Reply($client,"error\n", $userinput);
                   6910:         }
                   6911:     } else {
                   6912:         &Failure($client,"unknown_cmd\n",$userinput);
                   6913:     }
                   6914: }
1.397     raeburn  6915: &register_handler("instemailrules",\&get_institutional_selfcreate_rules,0,1,0);
1.396     raeburn  6916: 
1.575     raeburn  6917: sub get_unamemap_rules {
                   6918:     my ($cmd, $tail, $client)   = @_;
                   6919:     my $userinput               = "$cmd:$tail";
                   6920:     my $dom = &unescape($tail);
                   6921:     my (%rules_hash,@rules_order);
                   6922:     my $outcome;
                   6923:     eval {
                   6924:         local($SIG{__DIE__})='DEFAULT';
                   6925:         $outcome = &localenroll::unamemap_rules($dom,\%rules_hash,\@rules_order);
                   6926:     };
                   6927:     if (!$@) {
                   6928:         if ($outcome eq 'ok') {
                   6929:             my $result;
                   6930:             foreach my $key (keys(%rules_hash)) {
                   6931:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6932:             }
                   6933:             $result =~ s/\&$//;
                   6934:             $result .= ':';
                   6935:             if (@rules_order > 0) {
                   6936:                 foreach my $item (@rules_order) {
                   6937:                     $result .= &escape($item).'&';
                   6938:                 }
                   6939:             }
                   6940:             $result =~ s/\&$//;
                   6941:             &Reply($client,\$result,$userinput);
                   6942:         } else {
                   6943:             &Reply($client,"error\n", $userinput);
                   6944:         }
                   6945:     } else {
                   6946:         &Failure($client,"unknown_cmd\n",$userinput);
                   6947:     }
                   6948: }
                   6949: &register_handler("unamemaprules",\&get_unamemap_rules,0,1,0);
1.381     raeburn  6950: 
                   6951: sub institutional_username_check {
                   6952:     my ($cmd, $tail, $client)   = @_;
                   6953:     my $userinput               = "$cmd:$tail";
                   6954:     my %rulecheck;
                   6955:     my $outcome;
                   6956:     my ($udom,$uname,@rules) = split(/:/,$tail);
                   6957:     $udom = &unescape($udom);
                   6958:     $uname = &unescape($uname);
                   6959:     @rules = map {&unescape($_);} (@rules);
                   6960:     eval {
                   6961:         local($SIG{__DIE__})='DEFAULT';
                   6962:         $outcome = &localenroll::username_check($udom,$uname,\@rules,\%rulecheck);
                   6963:     };
                   6964:     if (!$@) {
                   6965:         if ($outcome eq 'ok') {
                   6966:             my $result='';
                   6967:             foreach my $key (keys(%rulecheck)) {
                   6968:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6969:             }
1.387     albertel 6970:             &Reply($client,\$result,$userinput);
1.381     raeburn  6971:         } else {
                   6972:             &Reply($client,"error\n", $userinput);
                   6973:         }
                   6974:     } else {
                   6975:         &Failure($client,"unknown_cmd\n",$userinput);
                   6976:     }
                   6977: }
                   6978: &register_handler("instrulecheck",\&institutional_username_check,0,1,0);
                   6979: 
1.389     raeburn  6980: sub institutional_id_check {
                   6981:     my ($cmd, $tail, $client)   = @_;
                   6982:     my $userinput               = "$cmd:$tail";
                   6983:     my %rulecheck;
                   6984:     my $outcome;
                   6985:     my ($udom,$id,@rules) = split(/:/,$tail);
                   6986:     $udom = &unescape($udom);
                   6987:     $id = &unescape($id);
                   6988:     @rules = map {&unescape($_);} (@rules);
                   6989:     eval {
                   6990:         local($SIG{__DIE__})='DEFAULT';
                   6991:         $outcome = &localenroll::id_check($udom,$id,\@rules,\%rulecheck);
                   6992:     };
                   6993:     if (!$@) {
                   6994:         if ($outcome eq 'ok') {
                   6995:             my $result='';
                   6996:             foreach my $key (keys(%rulecheck)) {
                   6997:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6998:             }
                   6999:             &Reply($client,\$result,$userinput);
                   7000:         } else {
                   7001:             &Reply($client,"error\n", $userinput);
                   7002:         }
                   7003:     } else {
                   7004:         &Failure($client,"unknown_cmd\n",$userinput);
                   7005:     }
                   7006: }
                   7007: &register_handler("instidrulecheck",\&institutional_id_check,0,1,0);
1.345     raeburn  7008: 
1.397     raeburn  7009: sub institutional_selfcreate_check {
1.396     raeburn  7010:     my ($cmd, $tail, $client)   = @_;
                   7011:     my $userinput               = "$cmd:$tail";
                   7012:     my %rulecheck;
                   7013:     my $outcome;
                   7014:     my ($udom,$email,@rules) = split(/:/,$tail);
                   7015:     $udom = &unescape($udom);
                   7016:     $email = &unescape($email);
                   7017:     @rules = map {&unescape($_);} (@rules);
                   7018:     eval {
                   7019:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  7020:         $outcome = &localenroll::selfcreate_check($udom,$email,\@rules,\%rulecheck);
1.396     raeburn  7021:     };
                   7022:     if (!$@) {
                   7023:         if ($outcome eq 'ok') {
                   7024:             my $result='';
                   7025:             foreach my $key (keys(%rulecheck)) {
                   7026:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   7027:             }
                   7028:             &Reply($client,\$result,$userinput);
                   7029:         } else {
                   7030:             &Reply($client,"error\n", $userinput);
                   7031:         }
                   7032:     } else {
                   7033:         &Failure($client,"unknown_cmd\n",$userinput);
                   7034:     }
                   7035: }
1.397     raeburn  7036: &register_handler("instselfcreatecheck",\&institutional_selfcreate_check,0,1,0);
1.396     raeburn  7037: 
1.317     raeburn  7038: # Get domain specific conditions for import of student photographs to a course
                   7039: #
                   7040: # Retrieves information from photo_permission subroutine in localenroll.
                   7041: # Returns outcome (ok) if no processing errors, and whether course owner is 
                   7042: # required to accept conditions of use (yes/no).
                   7043: #
                   7044: #    
                   7045: sub photo_permission_handler {
                   7046:     my ($cmd, $tail, $client)   = @_;
                   7047:     my $userinput               = "$cmd:$tail";
                   7048:     my $cdom = $tail;
                   7049:     my ($perm_reqd,$conditions);
1.320     albertel 7050:     my $outcome;
                   7051:     eval {
                   7052: 	local($SIG{__DIE__})='DEFAULT';
                   7053: 	$outcome = &localenroll::photo_permission($cdom,\$perm_reqd,
                   7054: 						  \$conditions);
                   7055:     };
                   7056:     if (!$@) {
                   7057: 	&Reply($client, &escape($outcome.':'.$perm_reqd.':'. $conditions)."\n",
                   7058: 	       $userinput);
                   7059:     } else {
                   7060: 	&Failure($client,"unknown_cmd\n",$userinput);
                   7061:     }
                   7062:     return 1;
1.317     raeburn  7063: }
                   7064: &register_handler("autophotopermission",\&photo_permission_handler,0,1,0);
                   7065: 
                   7066: #
                   7067: # Checks if student photo is available for a user in the domain, in the user's
                   7068: # directory (in /userfiles/internal/studentphoto.jpg).
                   7069: # Uses localstudentphoto:fetch() to ensure there is an up to date copy of
                   7070: # the student's photo.   
                   7071: 
                   7072: sub photo_check_handler {
                   7073:     my ($cmd, $tail, $client)   = @_;
                   7074:     my $userinput               = "$cmd:$tail";
                   7075:     my ($udom,$uname,$pid) = split(/:/,$tail);
                   7076:     $udom = &unescape($udom);
                   7077:     $uname = &unescape($uname);
                   7078:     $pid = &unescape($pid);
                   7079:     my $path=&propath($udom,$uname).'/userfiles/internal/';
                   7080:     if (!-e $path) {
                   7081:         &mkpath($path);
                   7082:     }
                   7083:     my $response;
                   7084:     my $result = &localstudentphoto::fetch($udom,$uname,$pid,\$response);
                   7085:     $result .= ':'.$response;
                   7086:     &Reply($client, &escape($result)."\n",$userinput);
1.320     albertel 7087:     return 1;
1.317     raeburn  7088: }
                   7089: &register_handler("autophotocheck",\&photo_check_handler,0,1,0);
                   7090: 
                   7091: #
                   7092: # Retrieve information from localenroll about whether to provide a button     
                   7093: # for users who have enbled import of student photos to initiate an 
                   7094: # update of photo files for registered students. Also include 
                   7095: # comment to display alongside button.  
                   7096: 
                   7097: sub photo_choice_handler {
                   7098:     my ($cmd, $tail, $client) = @_;
                   7099:     my $userinput             = "$cmd:$tail";
                   7100:     my $cdom                  = &unescape($tail);
1.320     albertel 7101:     my ($update,$comment);
                   7102:     eval {
                   7103: 	local($SIG{__DIE__})='DEFAULT';
                   7104: 	($update,$comment)    = &localenroll::manager_photo_update($cdom);
                   7105:     };
                   7106:     if (!$@) {
                   7107: 	&Reply($client,&escape($update).':'.&escape($comment)."\n",$userinput);
                   7108:     } else {
                   7109: 	&Failure($client,"unknown_cmd\n",$userinput);
                   7110:     }
                   7111:     return 1;
1.317     raeburn  7112: }
                   7113: &register_handler("autophotochoice",\&photo_choice_handler,0,1,0);
                   7114: 
1.265     albertel 7115: #
                   7116: # Gets a student's photo to exist (in the correct image type) in the user's 
                   7117: # directory.
                   7118: # Formal Parameters:
                   7119: #    $cmd     - The command request that got us dispatched.
                   7120: #    $tail    - A colon separated set of words that will be split into:
                   7121: #               $domain - student's domain
                   7122: #               $uname  - student username
                   7123: #               $type   - image type desired
                   7124: #    $client  - The socket open on the client.
                   7125: # Returns:
                   7126: #    1 - continue processing.
1.317     raeburn  7127: 
1.265     albertel 7128: sub student_photo_handler {
                   7129:     my ($cmd, $tail, $client) = @_;
1.317     raeburn  7130:     my ($domain,$uname,$ext,$type) = split(/:/, $tail);
1.265     albertel 7131: 
1.317     raeburn  7132:     my $path=&propath($domain,$uname). '/userfiles/internal/';
                   7133:     my $filename = 'studentphoto.'.$ext;
                   7134:     if ($type eq 'thumbnail') {
                   7135:         $filename = 'studentphoto_tn.'.$ext;
                   7136:     }
                   7137:     if (-e $path.$filename) {
1.265     albertel 7138: 	&Reply($client,"ok\n","$cmd:$tail");
                   7139: 	return 1;
                   7140:     }
                   7141:     &mkpath($path);
1.317     raeburn  7142:     my $file;
                   7143:     if ($type eq 'thumbnail') {
1.320     albertel 7144: 	eval {
                   7145: 	    local($SIG{__DIE__})='DEFAULT';
                   7146: 	    $file=&localstudentphoto::fetch_thumbnail($domain,$uname);
                   7147: 	};
1.317     raeburn  7148:     } else {
                   7149:         $file=&localstudentphoto::fetch($domain,$uname);
                   7150:     }
1.265     albertel 7151:     if (!$file) {
                   7152: 	&Failure($client,"unavailable\n","$cmd:$tail");
                   7153: 	return 1;
                   7154:     }
1.317     raeburn  7155:     if (!-e $path.$filename) { &convert_photo($file,$path.$filename); }
                   7156:     if (-e $path.$filename) {
1.265     albertel 7157: 	&Reply($client,"ok\n","$cmd:$tail");
                   7158: 	return 1;
                   7159:     }
                   7160:     &Failure($client,"unable_to_convert\n","$cmd:$tail");
                   7161:     return 1;
                   7162: }
                   7163: &register_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
1.246     foxr     7164: 
1.361     raeburn  7165: sub inst_usertypes_handler {
                   7166:     my ($cmd, $domain, $client) = @_;
                   7167:     my $res;
                   7168:     my $userinput = $cmd.":".$domain; # For logging purposes.
1.370     albertel 7169:     my (%typeshash,@order,$result);
                   7170:     eval {
                   7171: 	local($SIG{__DIE__})='DEFAULT';
                   7172: 	$result=&localenroll::inst_usertypes($domain,\%typeshash,\@order);
                   7173:     };
                   7174:     if ($result eq 'ok') {
1.361     raeburn  7175:         if (keys(%typeshash) > 0) {
                   7176:             foreach my $key (keys(%typeshash)) {
                   7177:                 $res.=&escape($key).'='.&escape($typeshash{$key}).'&';
                   7178:             }
                   7179:         }
                   7180:         $res=~s/\&$//;
                   7181:         $res .= ':';
                   7182:         if (@order > 0) {
                   7183:             foreach my $item (@order) {
                   7184:                 $res .= &escape($item).'&';
                   7185:             }
                   7186:         }
                   7187:         $res=~s/\&$//;
                   7188:     }
1.387     albertel 7189:     &Reply($client, \$res, $userinput);
1.361     raeburn  7190:     return 1;
                   7191: }
                   7192: &register_handler("inst_usertypes", \&inst_usertypes_handler, 0, 1, 0);
                   7193: 
1.264     albertel 7194: # mkpath makes all directories for a file, expects an absolute path with a
                   7195: # file or a trailing / if just a dir is passed
                   7196: # returns 1 on success 0 on failure
                   7197: sub mkpath {
                   7198:     my ($file)=@_;
                   7199:     my @parts=split(/\//,$file,-1);
                   7200:     my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
                   7201:     for (my $i=3;$i<= ($#parts-1);$i++) {
1.265     albertel 7202: 	$now.='/'.$parts[$i]; 
1.264     albertel 7203: 	if (!-e $now) {
                   7204: 	    if  (!mkdir($now,0770)) { return 0; }
                   7205: 	}
                   7206:     }
                   7207:     return 1;
                   7208: }
                   7209: 
1.207     foxr     7210: #---------------------------------------------------------------
                   7211: #
                   7212: #   Getting, decoding and dispatching requests:
                   7213: #
                   7214: #
                   7215: #   Get a Request:
                   7216: #   Gets a Request message from the client.  The transaction
                   7217: #   is defined as a 'line' of text.  We remove the new line
                   7218: #   from the text line.  
1.226     foxr     7219: #
1.211     albertel 7220: sub get_request {
1.207     foxr     7221:     my $input = <$client>;
                   7222:     chomp($input);
1.226     foxr     7223: 
1.234     foxr     7224:     &Debug("get_request: Request = $input\n");
1.207     foxr     7225: 
                   7226:     &status('Processing '.$clientname.':'.$input);
                   7227: 
                   7228:     return $input;
                   7229: }
1.212     foxr     7230: #---------------------------------------------------------------
                   7231: #
                   7232: #  Process a request.  This sub should shrink as each action
                   7233: #  gets farmed out into a separat sub that is registered 
                   7234: #  with the dispatch hash.  
                   7235: #
                   7236: # Parameters:
                   7237: #    user_input   - The request received from the client (lonc).
1.525     raeburn  7238: #
1.212     foxr     7239: # Returns:
                   7240: #    true to keep processing, false if caller should exit.
                   7241: #
                   7242: sub process_request {
1.525     raeburn  7243:     my ($userinput) = @_; # Easier for now to break style than to
                   7244:                           # fix all the userinput -> user_input.
1.212     foxr     7245:     my $wasenc    = 0;		# True if request was encrypted.
                   7246: # ------------------------------------------------------------ See if encrypted
1.322     albertel 7247:     # for command
                   7248:     # sethost:<server>
                   7249:     # <command>:<args>
                   7250:     #   we just send it to the processor
                   7251:     # for
                   7252:     # sethost:<server>:<command>:<args>
                   7253:     #  we do the implict set host and then do the command
                   7254:     if ($userinput =~ /^sethost:/) {
                   7255: 	(my $cmd,my $newid,$userinput) = split(':',$userinput,3);
                   7256: 	if (defined($userinput)) {
                   7257: 	    &sethost("$cmd:$newid");
                   7258: 	} else {
                   7259: 	    $userinput = "$cmd:$newid";
                   7260: 	}
                   7261:     }
                   7262: 
1.212     foxr     7263:     if ($userinput =~ /^enc/) {
                   7264: 	$userinput = decipher($userinput);
                   7265: 	$wasenc=1;
                   7266: 	if(!$userinput) {	# Cipher not defined.
1.251     foxr     7267: 	    &Failure($client, "error: Encrypted data without negotated key\n");
1.212     foxr     7268: 	    return 0;
                   7269: 	}
                   7270:     }
                   7271:     Debug("process_request: $userinput\n");
                   7272:     
1.213     foxr     7273:     #  
                   7274:     #   The 'correct way' to add a command to lond is now to
                   7275:     #   write a sub to execute it and Add it to the command dispatch
                   7276:     #   hash via a call to register_handler..  The comments to that
                   7277:     #   sub should give you enough to go on to show how to do this
                   7278:     #   along with the examples that are building up as this code
                   7279:     #   is getting refactored.   Until all branches of the
                   7280:     #   if/elseif monster below have been factored out into
                   7281:     #   separate procesor subs, if the dispatch hash is missing
                   7282:     #   the command keyword, we will fall through to the remainder
                   7283:     #   of the if/else chain below in order to keep this thing in 
                   7284:     #   working order throughout the transmogrification.
                   7285: 
                   7286:     my ($command, $tail) = split(/:/, $userinput, 2);
                   7287:     chomp($command);
                   7288:     chomp($tail);
                   7289:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
1.214     foxr     7290:     $command =~ s/(\r)//;	# And this too for parameterless commands.
                   7291:     if(!$tail) {
                   7292: 	$tail ="";		# defined but blank.
                   7293:     }
1.213     foxr     7294: 
                   7295:     &Debug("Command received: $command, encoded = $wasenc");
                   7296: 
                   7297:     if(defined $Dispatcher{$command}) {
                   7298: 
                   7299: 	my $dispatch_info = $Dispatcher{$command};
                   7300: 	my $handler       = $$dispatch_info[0];
                   7301: 	my $need_encode   = $$dispatch_info[1];
                   7302: 	my $client_types  = $$dispatch_info[2];
                   7303: 	Debug("Matched dispatch hash: mustencode: $need_encode "
                   7304: 	      ."ClientType $client_types");
                   7305:       
                   7306: 	#  Validate the request:
                   7307:       
                   7308: 	my $ok = 1;
                   7309: 	my $requesterprivs = 0;
                   7310: 	if(&isClient()) {
                   7311: 	    $requesterprivs |= $CLIENT_OK;
                   7312: 	}
                   7313: 	if(&isManager()) {
                   7314: 	    $requesterprivs |= $MANAGER_OK;
                   7315: 	}
                   7316: 	if($need_encode && (!$wasenc)) {
                   7317: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
                   7318: 	    $ok = 0;
                   7319: 	}
                   7320: 	if(($client_types & $requesterprivs) == 0) {
                   7321: 	    Debug("Client not privileged to do this operation");
                   7322: 	    $ok = 0;
                   7323: 	}
1.525     raeburn  7324:         if ($ok) {
1.535     raeburn  7325:             my $realcommand = $command;
                   7326:             if ($command eq 'querysend') {
                   7327:                 my ($query,$rest)=split(/\:/,$tail,2);
                   7328:                 $query=~s/\n*$//g;
                   7329:                 my @possqueries = 
                   7330:                     qw(userlog courselog fetchenrollment institutionalphotos usersearch instdirsearch getinstuser getmultinstusers);
                   7331:                 if (grep(/^\Q$query\E$/,@possqueries)) {
                   7332:                     $command .= '_'.$query;
                   7333:                 } elsif ($query eq 'prepare activity log') {
                   7334:                     $command .= '_activitylog';
                   7335:                 }
                   7336:             }
1.525     raeburn  7337:             if (ref($trust{$command}) eq 'HASH') {
                   7338:                 my $donechecks;
                   7339:                 if ($trust{$command}{'anywhere'}) {
                   7340:                    $donechecks = 1;
                   7341:                 } elsif ($trust{$command}{'manageronly'}) {
                   7342:                     unless (&isManager()) {
                   7343:                         $ok = 0;
                   7344:                     }
                   7345:                     $donechecks = 1;
                   7346:                 } elsif ($trust{$command}{'institutiononly'}) {
                   7347:                     unless ($clientsameinst) {
                   7348:                         $ok = 0;
                   7349:                     }
                   7350:                     $donechecks = 1;
                   7351:                 } elsif ($clientsameinst) {
                   7352:                     $donechecks = 1;
                   7353:                 }
                   7354:                 unless ($donechecks) {
                   7355:                     foreach my $rule (keys(%{$trust{$command}})) {
                   7356:                         next if ($rule eq 'remote');
                   7357:                         if ($trust{$command}{$rule}) {
                   7358:                             if ($clientprohibited{$rule}) {
                   7359:                                 $ok = 0;
                   7360:                             } else {
                   7361:                                 $ok = 1;
                   7362:                                 $donechecks = 1;
                   7363:                                 last;
                   7364:                             }
                   7365:                         }
                   7366:                     }
                   7367:                 }
                   7368:                 unless ($donechecks) {
                   7369:                     if ($trust{$command}{'remote'}) {
                   7370:                         if ($clientremoteok) {
                   7371:                             $ok = 1;
                   7372:                         } else {
                   7373:                             $ok = 0;
                   7374:                         } 
                   7375:                     }
                   7376:                 }
                   7377:             }
1.535     raeburn  7378:             $command = $realcommand;
1.525     raeburn  7379:         }
1.213     foxr     7380: 
                   7381: 	if($ok) {
                   7382: 	    Debug("Dispatching to handler $command $tail");
                   7383: 	    my $keep_going = &$handler($command, $tail, $client);
                   7384: 	    return $keep_going;
                   7385: 	} else {
                   7386: 	    Debug("Refusing to dispatch because client did not match requirements");
                   7387: 	    Failure($client, "refused\n", $userinput);
                   7388: 	    return 1;
                   7389: 	}
1.525     raeburn  7390:     }
1.213     foxr     7391: 
1.262     foxr     7392:     print $client "unknown_cmd\n";
1.212     foxr     7393: # -------------------------------------------------------------------- complete
                   7394:     Debug("process_request - returning 1");
                   7395:     return 1;
                   7396: }
1.207     foxr     7397: #
                   7398: #   Decipher encoded traffic
                   7399: #  Parameters:
                   7400: #     input      - Encoded data.
                   7401: #  Returns:
                   7402: #     Decoded data or undef if encryption key was not yet negotiated.
                   7403: #  Implicit input:
                   7404: #     cipher  - This global holds the negotiated encryption key.
                   7405: #
1.211     albertel 7406: sub decipher {
1.207     foxr     7407:     my ($input)  = @_;
                   7408:     my $output = '';
1.212     foxr     7409:     
                   7410:     
1.207     foxr     7411:     if($cipher) {
                   7412: 	my($enc, $enclength, $encinput) = split(/:/, $input);
                   7413: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
                   7414: 	    $output .= 
                   7415: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
                   7416: 	}
                   7417: 	return substr($output, 0, $enclength);
                   7418:     } else {
                   7419: 	return undef;
                   7420:     }
                   7421: }
                   7422: 
                   7423: #
                   7424: #   Register a command processor.  This function is invoked to register a sub
                   7425: #   to process a request.  Once registered, the ProcessRequest sub can automatically
                   7426: #   dispatch requests to an appropriate sub, and do the top level validity checking
                   7427: #   as well:
                   7428: #    - Is the keyword recognized.
                   7429: #    - Is the proper client type attempting the request.
                   7430: #    - Is the request encrypted if it has to be.
                   7431: #   Parameters:
                   7432: #    $request_name         - Name of the request being registered.
                   7433: #                           This is the command request that will match
                   7434: #                           against the hash keywords to lookup the information
                   7435: #                           associated with the dispatch information.
                   7436: #    $procedure           - Reference to a sub to call to process the request.
                   7437: #                           All subs get called as follows:
                   7438: #                             Procedure($cmd, $tail, $replyfd, $key)
                   7439: #                             $cmd    - the actual keyword that invoked us.
                   7440: #                             $tail   - the tail of the request that invoked us.
                   7441: #                             $replyfd- File descriptor connected to the client
                   7442: #    $must_encode          - True if the request must be encoded to be good.
                   7443: #    $client_ok            - True if it's ok for a client to request this.
                   7444: #    $manager_ok           - True if it's ok for a manager to request this.
                   7445: # Side effects:
                   7446: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
                   7447: #      - On failure, the program will die as it's a bad internal bug to try to 
                   7448: #        register a duplicate command handler.
                   7449: #
1.211     albertel 7450: sub register_handler {
1.212     foxr     7451:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
1.207     foxr     7452: 
                   7453:     #  Don't allow duplication#
                   7454:    
                   7455:     if (defined $Dispatcher{$request_name}) {
                   7456: 	die "Attempting to define a duplicate request handler for $request_name\n";
                   7457:     }
                   7458:     #   Build the client type mask:
                   7459:     
                   7460:     my $client_type_mask = 0;
                   7461:     if($client_ok) {
                   7462: 	$client_type_mask  |= $CLIENT_OK;
                   7463:     }
                   7464:     if($manager_ok) {
                   7465: 	$client_type_mask  |= $MANAGER_OK;
                   7466:     }
                   7467:    
                   7468:     #  Enter the hash:
                   7469:       
                   7470:     my @entry = ($procedure, $must_encode, $client_type_mask);
                   7471:    
                   7472:     $Dispatcher{$request_name} = \@entry;
                   7473:    
                   7474: }
                   7475: 
                   7476: 
                   7477: #------------------------------------------------------------------
                   7478: 
                   7479: 
                   7480: 
                   7481: 
1.141     foxr     7482: #
1.96      foxr     7483: #  Convert an error return code from lcpasswd to a string value.
                   7484: #
                   7485: sub lcpasswdstrerror {
                   7486:     my $ErrorCode = shift;
1.97      foxr     7487:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96      foxr     7488: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
                   7489:     } else {
1.98      foxr     7490: 	return $passwderrors[$ErrorCode];
1.96      foxr     7491:     }
                   7492: }
                   7493: 
1.23      harris41 7494: # grabs exception and records it to log before exiting
                   7495: sub catchexception {
1.27      albertel 7496:     my ($error)=@_;
1.25      www      7497:     $SIG{'QUIT'}='DEFAULT';
                   7498:     $SIG{__DIE__}='DEFAULT';
1.165     albertel 7499:     &status("Catching exception");
1.190     albertel 7500:     &logthis("<font color='red'>CRITICAL: "
1.373     albertel 7501:      ."ABNORMAL EXIT. Child $$ for server ".$perlvar{'lonHostID'}." died through "
1.27      albertel 7502:      ."a crash with this error msg->[$error]</font>");
1.57      www      7503:     &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27      albertel 7504:     if ($client) { print $client "error: $error\n"; }
1.59      www      7505:     $server->close();
1.27      albertel 7506:     die($error);
1.23      harris41 7507: }
1.63      www      7508: sub timeout {
1.165     albertel 7509:     &status("Handling Timeout");
1.190     albertel 7510:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
1.63      www      7511:     &catchexception('Timeout');
                   7512: }
1.22      harris41 7513: # -------------------------------- Set signal handlers to record abnormal exits
                   7514: 
1.226     foxr     7515: 
1.22      harris41 7516: $SIG{'QUIT'}=\&catchexception;
                   7517: $SIG{__DIE__}=\&catchexception;
                   7518: 
1.81      matthew  7519: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95      harris41 7520: &status("Read loncapa.conf and loncapa_apache.conf");
                   7521: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141     foxr     7522: %perlvar=%{$perlvarref};
1.80      harris41 7523: undef $perlvarref;
1.19      www      7524: 
1.35      harris41 7525: # ----------------------------- Make sure this process is running from user=www
                   7526: my $wwwid=getpwnam('www');
                   7527: if ($wwwid!=$<) {
1.134     albertel 7528:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   7529:    my $subj="LON: $currenthostid User ID mismatch";
1.550     raeburn  7530:    system("echo 'User ID mismatch.  lond must be run as user www.' |".
                   7531:           " mail -s '$subj' $emailto > /dev/null");
1.35      harris41 7532:    exit 1;
                   7533: }
                   7534: 
1.19      www      7535: # --------------------------------------------- Check if other instance running
                   7536: 
                   7537: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
                   7538: 
                   7539: if (-e $pidfile) {
                   7540:    my $lfh=IO::File->new("$pidfile");
                   7541:    my $pide=<$lfh>;
                   7542:    chomp($pide);
1.29      harris41 7543:    if (kill 0 => $pide) { die "already running"; }
1.19      www      7544: }
1.1       albertel 7545: 
                   7546: # ------------------------------------------------------------- Read hosts file
                   7547: 
                   7548: 
                   7549: 
                   7550: # establish SERVER socket, bind and listen.
                   7551: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
                   7552:                                 Type      => SOCK_STREAM,
                   7553:                                 Proto     => 'tcp',
1.469     foxr     7554:                                 ReuseAddr     => 1,
1.1       albertel 7555:                                 Listen    => 10 )
1.29      harris41 7556:   or die "making socket: $@\n";
1.1       albertel 7557: 
                   7558: # --------------------------------------------------------- Do global variables
                   7559: 
                   7560: # global variables
                   7561: 
1.134     albertel 7562: my %children               = ();       # keys are current child process IDs
1.1       albertel 7563: 
                   7564: sub REAPER {                        # takes care of dead children
                   7565:     $SIG{CHLD} = \&REAPER;
1.165     albertel 7566:     &status("Handling child death");
1.178     foxr     7567:     my $pid;
                   7568:     do {
                   7569: 	$pid = waitpid(-1,&WNOHANG());
                   7570: 	if (defined($children{$pid})) {
                   7571: 	    &logthis("Child $pid died");
                   7572: 	    delete($children{$pid});
1.183     albertel 7573: 	} elsif ($pid > 0) {
1.178     foxr     7574: 	    &logthis("Unknown Child $pid died");
                   7575: 	}
                   7576:     } while ( $pid > 0 );
                   7577:     foreach my $child (keys(%children)) {
                   7578: 	$pid = waitpid($child,&WNOHANG());
                   7579: 	if ($pid > 0) {
                   7580: 	    &logthis("Child $child - $pid looks like we missed it's death");
                   7581: 	    delete($children{$pid});
                   7582: 	}
1.176     albertel 7583:     }
1.165     albertel 7584:     &status("Finished Handling child death");
1.1       albertel 7585: }
                   7586: 
                   7587: sub HUNTSMAN {                      # signal handler for SIGINT
1.165     albertel 7588:     &status("Killing children (INT)");
1.1       albertel 7589:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
                   7590:     kill 'INT' => keys %children;
1.59      www      7591:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1       albertel 7592:     my $execdir=$perlvar{'lonDaemons'};
                   7593:     unlink("$execdir/logs/lond.pid");
1.190     albertel 7594:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.165     albertel 7595:     &status("Done killing children");
1.1       albertel 7596:     exit;                           # clean up with dignity
                   7597: }
                   7598: 
                   7599: sub HUPSMAN {                      # signal handler for SIGHUP
                   7600:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
1.165     albertel 7601:     &status("Killing children for restart (HUP)");
1.1       albertel 7602:     kill 'INT' => keys %children;
1.59      www      7603:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.190     albertel 7604:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.134     albertel 7605:     my $execdir=$perlvar{'lonDaemons'};
1.30      harris41 7606:     unlink("$execdir/logs/lond.pid");
1.165     albertel 7607:     &status("Restarting self (HUP)");
1.1       albertel 7608:     exec("$execdir/lond");         # here we go again
                   7609: }
                   7610: 
1.144     foxr     7611: #
1.148     foxr     7612: #  Reload the Apache daemon's state.
1.150     foxr     7613: #  This is done by invoking /home/httpd/perl/apachereload
                   7614: #  a setuid perl script that can be root for us to do this job.
1.148     foxr     7615: #
                   7616: sub ReloadApache {
1.473     raeburn  7617: # --------------------------- Handle case of another apachereload process (locking)
1.474     raeburn  7618:     if (&LONCAPA::try_to_lock('/tmp/lock_apachereload')) {
                   7619:         my $execdir = $perlvar{'lonDaemons'};
                   7620:         my $script  = $execdir."/apachereload";
                   7621:         system($script);
                   7622:         unlink('/tmp/lock_apachereload'); #  Remove the lock file.
                   7623:     }
1.148     foxr     7624: }
                   7625: 
                   7626: #
1.144     foxr     7627: #   Called in response to a USR2 signal.
                   7628: #   - Reread hosts.tab
                   7629: #   - All children connected to hosts that were removed from hosts.tab
                   7630: #     are killed via SIGINT
                   7631: #   - All children connected to previously existing hosts are sent SIGUSR1
                   7632: #   - Our internal hosts hash is updated to reflect the new contents of
                   7633: #     hosts.tab causing connections from hosts added to hosts.tab to
                   7634: #     now be honored.
                   7635: #
                   7636: sub UpdateHosts {
1.165     albertel 7637:     &status("Reload hosts.tab");
1.147     foxr     7638:     logthis('<font color="blue"> Updating connections </font>');
1.148     foxr     7639:     #
                   7640:     #  The %children hash has the set of IP's we currently have children
                   7641:     #  on.  These need to be matched against records in the hosts.tab
                   7642:     #  Any ip's no longer in the table get killed off they correspond to
                   7643:     #  either dropped or changed hosts.  Note that the re-read of the table
                   7644:     #  will take care of new and changed hosts as connections come into being.
                   7645: 
1.371     albertel 7646:     &Apache::lonnet::reset_hosts_info();
1.532     raeburn  7647:     my %active;
1.148     foxr     7648: 
1.368     albertel 7649:     foreach my $child (keys(%children)) {
1.148     foxr     7650: 	my $childip = $children{$child};
1.374     albertel 7651: 	if ($childip ne '127.0.0.1'
                   7652: 	    && !defined(&Apache::lonnet::get_hosts_from_ip($childip))) {
1.149     foxr     7653: 	    logthis('<font color="blue"> UpdateHosts killing child '
                   7654: 		    ." $child for ip $childip </font>");
1.148     foxr     7655: 	    kill('INT', $child);
1.149     foxr     7656: 	} else {
1.532     raeburn  7657:             $active{$child} = $childip;
1.149     foxr     7658: 	    logthis('<font color="green"> keeping child for ip '
                   7659: 		    ." $childip (pid=$child) </font>");
1.148     foxr     7660: 	}
                   7661:     }
1.532     raeburn  7662: 
                   7663:     my %oldconf = %secureconf;
                   7664:     my %connchange;
1.555     raeburn  7665:     if (lonssl::Read_Connect_Config(\%secureconf,\%perlvar,\%crlchecked) eq 'ok') {
1.545     raeburn  7666:         logthis('<font color="blue"> Reloaded SSL connection rules and cleared CRL checking history </font>');
1.532     raeburn  7667:     } else {
1.545     raeburn  7668:         logthis('<font color="yellow"> Failed to reload SSL connection rules and clear CRL checking history </font>');
1.532     raeburn  7669:     }
                   7670:     if ((ref($oldconf{'connfrom'}) eq 'HASH') && (ref($secureconf{'connfrom'}) eq 'HASH')) {
                   7671:         foreach my $type ('dom','intdom','other') {
                   7672:             if ((($oldconf{'connfrom'}{$type} eq 'no') && ($secureconf{'connfrom'}{$type} eq 'req')) ||
                   7673:                 (($oldconf{'connfrom'}{$type} eq 'req') && ($secureconf{'connfrom'}{$type} eq 'no'))) {
                   7674:                 $connchange{$type} = 1;
                   7675:             }
                   7676:         }
                   7677:     }
                   7678:     if (keys(%connchange)) {
                   7679:         foreach my $child (keys(%active)) {
                   7680:             my $childip = $active{$child};
                   7681:             if ($childip ne '127.0.0.1') {
                   7682:                 my $childhostname  = gethostbyaddr(Socket::inet_aton($childip),AF_INET);
                   7683:                 if ($childhostname ne '') {
                   7684:                     my $childlonhost = &Apache::lonnet::get_server_homeID($childhostname);
                   7685:                     my ($samedom,$sameinst) = &set_client_info($childlonhost);
                   7686:                     if ($samedom) {
                   7687:                         if ($connchange{'dom'}) {
                   7688:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7689:                                    ." $child for ip $childip </font>");
                   7690:                             kill('INT', $child);
                   7691:                         }
                   7692:                     } elsif ($sameinst) {
                   7693:                         if ($connchange{'intdom'}) {
                   7694:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7695:                                    ." $child for ip $childip </font>");
                   7696:                            kill('INT', $child);
                   7697:                         }
                   7698:                     } else {
                   7699:                         if ($connchange{'other'}) {
                   7700:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7701:                                    ." $child for ip $childip </font>");
                   7702:                             kill('INT', $child);
                   7703:                         }
                   7704:                     }
                   7705:                 }
                   7706:             }
                   7707:         }
                   7708:     }
1.148     foxr     7709:     ReloadApache;
1.165     albertel 7710:     &status("Finished reloading hosts.tab");
1.144     foxr     7711: }
                   7712: 
1.57      www      7713: sub checkchildren {
1.165     albertel 7714:     &status("Checking on the children (sending signals)");
1.57      www      7715:     &initnewstatus();
                   7716:     &logstatus();
                   7717:     &logthis('Going to check on the children');
1.134     albertel 7718:     my $docdir=$perlvar{'lonDocRoot'};
1.61      harris41 7719:     foreach (sort keys %children) {
1.221     albertel 7720: 	#sleep 1;
1.57      www      7721:         unless (kill 'USR1' => $_) {
                   7722: 	    &logthis ('Child '.$_.' is dead');
                   7723:             &logstatus($$.' is dead');
1.221     albertel 7724: 	    delete($children{$_});
1.57      www      7725:         } 
1.61      harris41 7726:     }
1.63      www      7727:     sleep 5;
1.212     foxr     7728:     $SIG{ALRM} = sub { Debug("timeout"); 
                   7729: 		       die "timeout";  };
1.113     albertel 7730:     $SIG{__DIE__} = 'DEFAULT';
1.165     albertel 7731:     &status("Checking on the children (waiting for reports)");
1.63      www      7732:     foreach (sort keys %children) {
                   7733:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113     albertel 7734:           eval {
                   7735:             alarm(300);
1.63      www      7736: 	    &logthis('Child '.$_.' did not respond');
1.67      albertel 7737: 	    kill 9 => $_;
1.131     albertel 7738: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   7739: 	    #$subj="LON: $currenthostid killed lond process $_";
                   7740: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
                   7741: 	    #$execdir=$perlvar{'lonDaemons'};
                   7742: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.221     albertel 7743: 	    delete($children{$_});
1.113     albertel 7744: 	    alarm(0);
                   7745: 	  }
1.63      www      7746:         }
                   7747:     }
1.113     albertel 7748:     $SIG{ALRM} = 'DEFAULT';
1.155     albertel 7749:     $SIG{__DIE__} = \&catchexception;
1.165     albertel 7750:     &status("Finished checking children");
1.221     albertel 7751:     &logthis('Finished Checking children');
1.57      www      7752: }
                   7753: 
1.1       albertel 7754: # --------------------------------------------------------------------- Logging
                   7755: 
                   7756: sub logthis {
                   7757:     my $message=shift;
                   7758:     my $execdir=$perlvar{'lonDaemons'};
                   7759:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
                   7760:     my $now=time;
                   7761:     my $local=localtime($now);
1.58      www      7762:     $lastlog=$local.': '.$message;
1.1       albertel 7763:     print $fh "$local ($$): $message\n";
                   7764: }
                   7765: 
1.77      foxr     7766: # ------------------------- Conditional log if $DEBUG true.
                   7767: sub Debug {
                   7768:     my $message = shift;
                   7769:     if($DEBUG) {
                   7770: 	&logthis($message);
                   7771:     }
                   7772: }
1.161     foxr     7773: 
                   7774: #
                   7775: #   Sub to do replies to client.. this gives a hook for some
                   7776: #   debug tracing too:
                   7777: #  Parameters:
                   7778: #     fd      - File open on client.
                   7779: #     reply   - Text to send to client.
                   7780: #     request - Original request from client.
                   7781: #
1.490     droeschl 7782: #NOTE $reply must be terminated by exactly *one* \n. If $reply is a reference
                   7783: #this is done automatically ($$reply must not contain any \n in this case). 
                   7784: #If $reply is a string the caller has to ensure this.
1.161     foxr     7785: sub Reply {
1.192     foxr     7786:     my ($fd, $reply, $request) = @_;
1.387     albertel 7787:     if (ref($reply)) {
                   7788: 	print $fd $$reply;
                   7789: 	print $fd "\n";
                   7790: 	if ($DEBUG) { Debug("Request was $request  Reply was $$reply"); }
                   7791:     } else {
                   7792: 	print $fd $reply;
                   7793: 	if ($DEBUG) { Debug("Request was $request  Reply was $reply"); }
                   7794:     }
1.212     foxr     7795:     $Transactions++;
                   7796: }
                   7797: 
                   7798: 
                   7799: #
                   7800: #    Sub to report a failure.
                   7801: #    This function:
                   7802: #     -   Increments the failure statistic counters.
                   7803: #     -   Invokes Reply to send the error message to the client.
                   7804: # Parameters:
                   7805: #    fd       - File descriptor open on the client
                   7806: #    reply    - Reply text to emit.
                   7807: #    request  - The original request message (used by Reply
                   7808: #               to debug if that's enabled.
                   7809: # Implicit outputs:
                   7810: #    $Failures- The number of failures is incremented.
                   7811: #    Reply (invoked here) sends a message to the 
                   7812: #    client:
                   7813: #
                   7814: sub Failure {
                   7815:     my $fd      = shift;
                   7816:     my $reply   = shift;
                   7817:     my $request = shift;
                   7818:    
                   7819:     $Failures++;
                   7820:     Reply($fd, $reply, $request);      # That's simple eh?
1.161     foxr     7821: }
1.57      www      7822: # ------------------------------------------------------------------ Log status
                   7823: 
                   7824: sub logstatus {
1.178     foxr     7825:     &status("Doing logging");
                   7826:     my $docdir=$perlvar{'lonDocRoot'};
                   7827:     {
                   7828: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
1.200     matthew  7829:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
1.178     foxr     7830:         $fh->close();
                   7831:     }
1.221     albertel 7832:     &status("Finished $$.txt");
                   7833:     {
                   7834: 	open(LOG,">>$docdir/lon-status/londstatus.txt");
                   7835: 	flock(LOG,LOCK_EX);
                   7836: 	print LOG $$."\t".$clientname."\t".$currenthostid."\t"
                   7837: 	    .$status."\t".$lastlog."\t $keymode\n";
1.275     albertel 7838: 	flock(LOG,LOCK_UN);
1.221     albertel 7839: 	close(LOG);
                   7840:     }
1.178     foxr     7841:     &status("Finished logging");
1.57      www      7842: }
                   7843: 
                   7844: sub initnewstatus {
                   7845:     my $docdir=$perlvar{'lonDocRoot'};
                   7846:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
1.460     foxr     7847:     my $now=time();
1.57      www      7848:     my $local=localtime($now);
                   7849:     print $fh "LOND status $local - parent $$\n\n";
1.64      www      7850:     opendir(DIR,"$docdir/lon-status/londchld");
1.134     albertel 7851:     while (my $filename=readdir(DIR)) {
1.64      www      7852:         unlink("$docdir/lon-status/londchld/$filename");
                   7853:     }
                   7854:     closedir(DIR);
1.57      www      7855: }
                   7856: 
                   7857: # -------------------------------------------------------------- Status setting
                   7858: 
                   7859: sub status {
                   7860:     my $what=shift;
                   7861:     my $now=time;
                   7862:     my $local=localtime($now);
1.178     foxr     7863:     $status=$local.': '.$what;
                   7864:     $0='lond: '.$what.' '.$local;
1.57      www      7865: }
1.11      www      7866: 
1.13      www      7867: # -------------------------------------------------------------- Talk to lonsql
                   7868: 
1.234     foxr     7869: sub sql_reply {
1.12      harris41 7870:     my ($cmd)=@_;
1.234     foxr     7871:     my $answer=&sub_sql_reply($cmd);
                   7872:     if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
1.12      harris41 7873:     return $answer;
                   7874: }
                   7875: 
1.234     foxr     7876: sub sub_sql_reply {
1.12      harris41 7877:     my ($cmd)=@_;
                   7878:     my $unixsock="mysqlsock";
                   7879:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
                   7880:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                   7881:                                       Type    => SOCK_STREAM,
                   7882:                                       Timeout => 10)
                   7883:        or return "con_lost";
1.319     www      7884:     print $sclient "$cmd:$currentdomainid\n";
1.12      harris41 7885:     my $answer=<$sclient>;
                   7886:     chomp($answer);
                   7887:     if (!$answer) { $answer="con_lost"; }
                   7888:     return $answer;
                   7889: }
                   7890: 
1.1       albertel 7891: # --------------------------------------- Is this the home server of an author?
1.11      www      7892: 
1.1       albertel 7893: sub ishome {
                   7894:     my $author=shift;
                   7895:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   7896:     my ($udom,$uname)=split(/\//,$author);
                   7897:     my $proname=propath($udom,$uname);
                   7898:     if (-e $proname) {
                   7899: 	return 'owner';
                   7900:     } else {
                   7901:         return 'not_owner';
                   7902:     }
                   7903: }
                   7904: 
                   7905: # ======================================================= Continue main program
                   7906: # ---------------------------------------------------- Fork once and dissociate
                   7907: 
1.134     albertel 7908: my $fpid=fork;
1.1       albertel 7909: exit if $fpid;
1.29      harris41 7910: die "Couldn't fork: $!" unless defined ($fpid);
1.1       albertel 7911: 
1.29      harris41 7912: POSIX::setsid() or die "Can't start new session: $!";
1.1       albertel 7913: 
                   7914: # ------------------------------------------------------- Write our PID on disk
                   7915: 
1.134     albertel 7916: my $execdir=$perlvar{'lonDaemons'};
1.1       albertel 7917: open (PIDSAVE,">$execdir/logs/lond.pid");
                   7918: print PIDSAVE "$$\n";
                   7919: close(PIDSAVE);
1.190     albertel 7920: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.57      www      7921: &status('Starting');
1.1       albertel 7922: 
1.106     foxr     7923: 
1.1       albertel 7924: 
                   7925: # ----------------------------------------------------- Install signal handlers
                   7926: 
1.57      www      7927: 
1.1       albertel 7928: $SIG{CHLD} = \&REAPER;
                   7929: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   7930: $SIG{HUP}  = \&HUPSMAN;
1.57      www      7931: $SIG{USR1} = \&checkchildren;
1.144     foxr     7932: $SIG{USR2} = \&UpdateHosts;
1.106     foxr     7933: 
1.148     foxr     7934: #  Read the host hashes:
1.368     albertel 7935: &Apache::lonnet::load_hosts_tab();
1.447     raeburn  7936: my %iphost = &Apache::lonnet::get_iphost(1);
1.106     foxr     7937: 
1.480     raeburn  7938: $dist=`$perlvar{'lonDaemons'}/distprobe`;
1.286     albertel 7939: 
1.471     raeburn  7940: my $arch = `uname -i`;
1.475     raeburn  7941: chomp($arch);
1.471     raeburn  7942: if ($arch eq 'unknown') {
                   7943:     $arch = `uname -m`;
1.475     raeburn  7944:     chomp($arch);
1.471     raeburn  7945: }
                   7946: 
1.555     raeburn  7947: unless (lonssl::Read_Connect_Config(\%secureconf,\%perlvar,\%crlchecked) eq 'ok') {
1.532     raeburn  7948:     &logthis('<font color="blue">No connectionrules table. Will fallback to loncapa.conf</font>');
                   7949: }
                   7950: 
1.106     foxr     7951: # --------------------------------------------------------------
                   7952: #   Accept connections.  When a connection comes in, it is validated
                   7953: #   and if good, a child process is created to process transactions
                   7954: #   along the connection.
                   7955: 
1.1       albertel 7956: while (1) {
1.165     albertel 7957:     &status('Starting accept');
1.106     foxr     7958:     $client = $server->accept() or next;
1.165     albertel 7959:     &status('Accepted '.$client.' off to spawn');
1.386     albertel 7960:     make_new_child($client);
1.165     albertel 7961:     &status('Finished spawning');
1.1       albertel 7962: }
                   7963: 
1.212     foxr     7964: sub make_new_child {
                   7965:     my $pid;
                   7966: #    my $cipher;     # Now global
                   7967:     my $sigset;
1.178     foxr     7968: 
1.212     foxr     7969:     $client = shift;
                   7970:     &status('Starting new child '.$client);
                   7971:     &logthis('<font color="green"> Attempting to start child ('.$client.
                   7972: 	     ")</font>");    
                   7973:     # block signal for fork
                   7974:     $sigset = POSIX::SigSet->new(SIGINT);
                   7975:     sigprocmask(SIG_BLOCK, $sigset)
                   7976:         or die "Can't block SIGINT for fork: $!\n";
1.178     foxr     7977: 
1.212     foxr     7978:     die "fork: $!" unless defined ($pid = fork);
1.178     foxr     7979: 
1.212     foxr     7980:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
                   7981: 	                               # connection liveness.
1.178     foxr     7982: 
1.212     foxr     7983:     #
                   7984:     #  Figure out who we're talking to so we can record the peer in 
                   7985:     #  the pid hash.
                   7986:     #
                   7987:     my $caller = getpeername($client);
                   7988:     my ($port,$iaddr);
                   7989:     if (defined($caller) && length($caller) > 0) {
                   7990: 	($port,$iaddr)=unpack_sockaddr_in($caller);
                   7991:     } else {
                   7992: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
                   7993:     }
                   7994:     if (defined($iaddr)) {
                   7995: 	$clientip  = inet_ntoa($iaddr);
                   7996: 	Debug("Connected with $clientip");
                   7997:     } else {
                   7998: 	&logthis("Unable to determine clientip");
                   7999: 	$clientip='Unavailable';
                   8000:     }
                   8001:     
                   8002:     if ($pid) {
                   8003:         # Parent records the child's birth and returns.
                   8004:         sigprocmask(SIG_UNBLOCK, $sigset)
                   8005:             or die "Can't unblock SIGINT for fork: $!\n";
                   8006:         $children{$pid} = $clientip;
                   8007:         &status('Started child '.$pid);
1.462     foxr     8008: 	close($client);
1.212     foxr     8009:         return;
                   8010:     } else {
                   8011:         # Child can *not* return from this subroutine.
                   8012:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
                   8013:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
                   8014:                                 #don't get intercepted
                   8015:         $SIG{USR1}= \&logstatus;
                   8016:         $SIG{ALRM}= \&timeout;
1.468     foxr     8017: 	#
                   8018: 	# Block sigpipe as it gets thrownon socket disconnect and we want to 
                   8019: 	# deal with that as a read faiure instead.
                   8020: 	#
                   8021: 	my $blockset = POSIX::SigSet->new(SIGPIPE);
                   8022: 	sigprocmask(SIG_BLOCK, $blockset);
                   8023: 
1.212     foxr     8024:         $lastlog='Forked ';
                   8025:         $status='Forked';
1.178     foxr     8026: 
1.212     foxr     8027:         # unblock signals
                   8028:         sigprocmask(SIG_UNBLOCK, $sigset)
                   8029:             or die "Can't unblock SIGINT for fork: $!\n";
1.178     foxr     8030: 
1.212     foxr     8031: #        my $tmpsnum=0;            # Now global
                   8032: #---------------------------------------------------- kerberos 5 initialization
                   8033:         &Authen::Krb5::init_context();
1.511     raeburn  8034: 
                   8035:         my $no_ets;
1.571     raeburn  8036:         if ($dist =~ /^(?:centos|rhes|scientific|oracle|rocky|alma)(\d+)/) {
1.511     raeburn  8037:             if ($1 >= 7) {
                   8038:                 $no_ets = 1;
                   8039:             }
                   8040:         } elsif ($dist =~ /^suse(\d+\.\d+)$/) {
                   8041:             if (($1 eq '9.3') || ($1 >= 12.2)) {
                   8042:                 $no_ets = 1; 
                   8043:             }
1.514     raeburn  8044:         } elsif ($dist =~ /^sles(\d+)$/) {
                   8045:             if ($1 > 11) {
                   8046:                 $no_ets = 1;
                   8047:             }
1.511     raeburn  8048:         } elsif ($dist =~ /^fedora(\d+)$/) {
                   8049:             if ($1 < 7) {
                   8050:                 $no_ets = 1;
                   8051:             }
                   8052:         }
                   8053:         unless ($no_ets) {
1.286     albertel 8054: 	    &Authen::Krb5::init_ets();
                   8055: 	}
1.209     albertel 8056: 
1.212     foxr     8057: 	&status('Accepted connection');
                   8058: # =============================================================================
                   8059:             # do something with the connection
                   8060: # -----------------------------------------------------------------------------
                   8061: 	# see if we know client and 'check' for spoof IP by ineffective challenge
1.178     foxr     8062: 
1.278     albertel 8063: 	my $outsideip=$clientip;
                   8064: 	if ($clientip eq '127.0.0.1') {
1.368     albertel 8065: 	    $outsideip=&Apache::lonnet::get_host_ip($perlvar{'lonHostID'});
1.278     albertel 8066: 	}
1.412     foxr     8067: 	&ReadManagerTable();
1.368     albertel 8068: 	my $clientrec=defined(&Apache::lonnet::get_hosts_from_ip($outsideip));
1.278     albertel 8069: 	my $ismanager=($managers{$outsideip}    ne undef);
1.432     raeburn  8070: 	$clientname  = "[unknown]";
1.212     foxr     8071: 	if($clientrec) {	# Establish client type.
                   8072: 	    $ConnectionType = "client";
1.368     albertel 8073: 	    $clientname = (&Apache::lonnet::get_hosts_from_ip($outsideip))[-1];
1.212     foxr     8074: 	    if($ismanager) {
                   8075: 		$ConnectionType = "both";
                   8076: 	    }
                   8077: 	} else {
                   8078: 	    $ConnectionType = "manager";
1.278     albertel 8079: 	    $clientname = $managers{$outsideip};
1.212     foxr     8080: 	}
1.556     raeburn  8081: 	my $clientok;
1.178     foxr     8082: 
1.212     foxr     8083: 	if ($clientrec || $ismanager) {
                   8084: 	    &status("Waiting for init from $clientip $clientname");
                   8085: 	    &logthis('<font color="yellow">INFO: Connection, '.
                   8086: 		     $clientip.
                   8087: 		  " ($clientname) connection type = $ConnectionType </font>" );
                   8088: 	    &status("Connecting $clientip  ($clientname))"); 
                   8089: 	    my $remotereq=<$client>;
                   8090: 	    chomp($remotereq);
                   8091: 	    Debug("Got init: $remotereq");
1.337     albertel 8092: 
1.212     foxr     8093: 	    if ($remotereq =~ /^init/) {
                   8094: 		&sethost("sethost:$perlvar{'lonHostID'}");
                   8095: 		#
                   8096: 		#  If the remote is attempting a local init... give that a try:
                   8097: 		#
1.432     raeburn  8098: 		(my $i, my $inittype, $clientversion) = split(/:/, $remotereq);
1.492     droeschl 8099:         # For LON-CAPA 2.9, the  client session will have sent its LON-CAPA
                   8100:         # version when initiating the connection. For LON-CAPA 2.8 and older,
                   8101:         # the version is retrieved from the global %loncaparevs in lonnet.pm.            
1.494     droeschl 8102:         # $clientversion contains path to keyfile if $inittype eq 'local'
                   8103:         # it's overridden below in this case
1.492     droeschl 8104:         $clientversion ||= $Apache::lonnet::loncaparevs{$clientname};
1.209     albertel 8105: 
1.212     foxr     8106: 		# If the connection type is ssl, but I didn't get my
                   8107: 		# certificate files yet, then I'll drop  back to 
                   8108: 		# insecure (if allowed).
1.532     raeburn  8109: 
                   8110:                 if ($inittype eq "ssl") {
                   8111:                     my $context;
                   8112:                     if ($clientsamedom) {
                   8113:                         $context = 'dom';
                   8114:                         if ($secureconf{'connfrom'}{'dom'} eq 'no') {
                   8115:                             $inittype = "";
                   8116:                         }
                   8117:                     } elsif ($clientsameinst) {
                   8118:                         $context = 'intdom';
                   8119:                         if ($secureconf{'connfrom'}{'intdom'} eq 'no') {
                   8120:                             $inittype = "";
                   8121:                         }
                   8122:                     } else {
                   8123:                         $context = 'other';
                   8124:                         if ($secureconf{'connfrom'}{'other'} eq 'no') {
                   8125:                             $inittype = "";
                   8126:                         }
                   8127:                     }
                   8128:                     if ($inittype eq '') {
                   8129:                         &logthis("<font color=\"blue\"> Domain config set "
                   8130:                                 ."to no ssl for $clientname (context: $context)"
                   8131:                                 ." -- trying insecure auth</font>");
                   8132:                     }
                   8133:                 }
                   8134: 
1.212     foxr     8135: 		if($inittype eq "ssl") {
                   8136: 		    my ($ca, $cert) = lonssl::CertificateFile;
                   8137: 		    my $kfile       = lonssl::KeyFile;
                   8138: 		    if((!$ca)   || 
                   8139: 		       (!$cert) || 
                   8140: 		       (!$kfile)) {
                   8141: 			$inittype = ""; # This forces insecure attempt.
                   8142: 			&logthis("<font color=\"blue\"> Certificates not "
                   8143: 				 ."installed -- trying insecure auth</font>");
1.224     foxr     8144: 		    } else {	# SSL certificates are in place so
1.212     foxr     8145: 		    }		# Leave the inittype alone.
                   8146: 		}
                   8147: 
                   8148: 		if($inittype eq "local") {
1.432     raeburn  8149:                     $clientversion = $perlvar{'lonVersion'};
1.212     foxr     8150: 		    my $key = LocalConnection($client, $remotereq);
                   8151: 		    if($key) {
                   8152: 			Debug("Got local key $key");
                   8153: 			$clientok     = 1;
                   8154: 			my $cipherkey = pack("H32", $key);
                   8155: 			$cipher       = new IDEA($cipherkey);
                   8156: 			print $client "ok:local\n";
1.442     www      8157: 			&logthis('<font color="green">'
1.212     foxr     8158: 				 . "Successful local authentication </font>");
                   8159: 			$keymode = "local"
1.178     foxr     8160: 		    } else {
1.212     foxr     8161: 			Debug("Failed to get local key");
                   8162: 			$clientok = 0;
                   8163: 			shutdown($client, 3);
                   8164: 			close $client;
1.178     foxr     8165: 		    }
1.212     foxr     8166: 		} elsif ($inittype eq "ssl") {
1.532     raeburn  8167: 		    my $key = SSLConnection($client,$clientname);
1.212     foxr     8168: 		    if ($key) {
                   8169: 			$clientok = 1;
                   8170: 			my $cipherkey = pack("H32", $key);
                   8171: 			$cipher       = new IDEA($cipherkey);
                   8172: 			&logthis('<font color="green">'
                   8173: 				 ."Successfull ssl authentication with $clientname </font>");
                   8174: 			$keymode = "ssl";
                   8175: 	     
1.178     foxr     8176: 		    } else {
1.212     foxr     8177: 			$clientok = 0;
                   8178: 			close $client;
1.178     foxr     8179: 		    }
1.212     foxr     8180: 	   
                   8181: 		} else {
                   8182: 		    my $ok = InsecureConnection($client);
                   8183: 		    if($ok) {
                   8184: 			$clientok = 1;
                   8185: 			&logthis('<font color="green">'
                   8186: 				 ."Successful insecure authentication with $clientname </font>");
                   8187: 			print $client "ok\n";
                   8188: 			$keymode = "insecure";
1.178     foxr     8189: 		    } else {
1.212     foxr     8190: 			&logthis('<font color="yellow">'
                   8191: 				  ."Attempted insecure connection disallowed </font>");
                   8192: 			close $client;
                   8193: 			$clientok = 0;
1.178     foxr     8194: 		    }
                   8195: 		}
1.212     foxr     8196: 	    } else {
                   8197: 		&logthis(
                   8198: 			 "<font color='blue'>WARNING: "
                   8199: 			 ."$clientip failed to initialize: >$remotereq< </font>");
                   8200: 		&status('No init '.$clientip);
                   8201: 	    }
                   8202: 	} else {
                   8203: 	    &logthis(
                   8204: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
                   8205: 	    &status('Hung up on '.$clientip);
                   8206: 	}
                   8207:  
                   8208: 	if ($clientok) {
                   8209: # ---------------- New known client connecting, could mean machine online again
1.368     albertel 8210: 	    if (&Apache::lonnet::get_host_ip($currenthostid) ne $clientip 
1.367     albertel 8211: 		&& $clientip ne '127.0.0.1') {
1.375     albertel 8212: 		&Apache::lonnet::reconlonc($clientname);
1.212     foxr     8213: 	    }
                   8214: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
                   8215: 	    &status('Will listen to '.$clientname);
                   8216: # ------------------------------------------------------------ Process requests
                   8217: 	    my $keep_going = 1;
                   8218: 	    my $user_input;
1.556     raeburn  8219: 
1.212     foxr     8220: 	    while(($user_input = get_request) && $keep_going) {
                   8221: 		alarm(120);
                   8222: 		Debug("Main: Got $user_input\n");
                   8223: 		$keep_going = &process_request($user_input);
1.178     foxr     8224: 		alarm(0);
1.569     raeburn  8225: 		&status('Listening to '.$clientname." ($keymode)");
1.161     foxr     8226: 	    }
1.212     foxr     8227: 
1.59      www      8228: # --------------------------------------------- client unknown or fishy, refuse
1.212     foxr     8229: 	}  else {
1.161     foxr     8230: 	    print $client "refused\n";
                   8231: 	    $client->close();
1.190     albertel 8232: 	    &logthis("<font color='blue'>WARNING: "
1.161     foxr     8233: 		     ."Rejected client $clientip, closing connection</font>");
                   8234: 	}
1.525     raeburn  8235:     }
1.161     foxr     8236:     
1.1       albertel 8237: # =============================================================================
1.161     foxr     8238:     
1.190     albertel 8239:     &logthis("<font color='red'>CRITICAL: "
1.161     foxr     8240: 	     ."Disconnect from $clientip ($clientname)</font>");    
1.569     raeburn  8241: 
                   8242: 
1.161     foxr     8243:     # this exit is VERY important, otherwise the child will become
                   8244:     # a producer of more and more children, forking yourself into
                   8245:     # process death.
                   8246:     exit;
1.106     foxr     8247:     
1.78      foxr     8248: }
1.532     raeburn  8249: 
                   8250: #
                   8251: #  Used to determine if a particular client is from the same domain
1.556     raeburn  8252: #  as the current server, or from the same internet domain, and
                   8253: #  also if the client can host sessions for the domain's users.
                   8254: #  A hash is populated with keys set to commands sent by the client
                   8255: #  which may not be executed for this domain.
1.532     raeburn  8256: #
                   8257: #  Optional input -- the client to check for domain and internet domain.
                   8258: #  If not specified, defaults to the package variable: $clientname
                   8259: #
                   8260: #  If called in array context will not set package variables, but will
                   8261: #  instead return an array of two values - (a) true if client is in the
1.556     raeburn  8262: #  same domain as the server, and (b) true if client is in the same 
                   8263: #  internet domain.
1.532     raeburn  8264: #
                   8265: #  If called in scalar context, sets package variables for current client:
                   8266: #
1.556     raeburn  8267: #  $clienthomedom    - LonCAPA domain of homeID for client.
                   8268: #  $clientsamedom    - LonCAPA domain same for this host and client.
                   8269: #  $clientintdom     - LonCAPA "internet domain" for client.
                   8270: #  $clientsameinst   - LonCAPA "internet domain" same for this host & client.
                   8271: #  $clientremoteok   - If current domain permits hosting on this client: 1
                   8272: #  %clientprohibited - Commands prohibited for domain's users for this client.
                   8273: #
                   8274: #  if the host and client have the same "internet domain", then the value
                   8275: #  of $clientremoteok is not used, and no commands are prohibited.
1.532     raeburn  8276: #
                   8277: #  returns 1 to indicate package variables have been set for current client.
                   8278: #
                   8279: 
                   8280: sub set_client_info {
                   8281:     my ($lonhost) = @_;
                   8282:     $lonhost ||= $clientname;
                   8283:     my $clienthost = &Apache::lonnet::hostname($lonhost);
                   8284:     my $clientserverhomeID = &Apache::lonnet::get_server_homeID($clienthost);
                   8285:     my $homedom = &Apache::lonnet::host_domain($clientserverhomeID);
                   8286:     my $samedom = 0;
1.557     raeburn  8287:     if ($perlvar{'lonDefDomain'} eq $homedom) {
1.532     raeburn  8288:         $samedom = 1;
                   8289:     }
                   8290:     my $intdom = &Apache::lonnet::internet_dom($clientserverhomeID);
                   8291:     my $sameinst = 0;
                   8292:     if ($intdom ne '') {
                   8293:         my $internet_names = &Apache::lonnet::get_internet_names($currenthostid);
                   8294:         if (ref($internet_names) eq 'ARRAY') {
                   8295:             if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   8296:                 $sameinst = 1;
                   8297:             }
                   8298:         }
                   8299:     }
                   8300:     if (wantarray) {
                   8301:         return ($samedom,$sameinst);
                   8302:     } else {
                   8303:         $clienthomedom = $homedom;
                   8304:         $clientsamedom = $samedom;
                   8305:         $clientintdom = $intdom;
                   8306:         $clientsameinst = $sameinst;
1.556     raeburn  8307:         if ($clientsameinst) {
                   8308:             undef($clientremoteok);
                   8309:             undef(%clientprohibited);
                   8310:         } else {
                   8311:             $clientremoteok = &get_remote_hostable($currentdomainid);
                   8312:             %clientprohibited = &get_prohibited($currentdomainid);
                   8313:         }
1.532     raeburn  8314:         return 1;
                   8315:     }
                   8316: }
                   8317: 
1.261     foxr     8318: #
                   8319: #   Determine if a user is an author for the indicated domain.
                   8320: #
                   8321: # Parameters:
                   8322: #    domain          - domain to check in .
                   8323: #    user            - Name of user to check.
                   8324: #
                   8325: # Return:
                   8326: #     1             - User is an author for domain.
                   8327: #     0             - User is not an author for domain.
                   8328: sub is_author {
                   8329:     my ($domain, $user) = @_;
                   8330: 
                   8331:     &Debug("is_author: $user @ $domain");
                   8332: 
                   8333:     my $hashref = &tie_user_hash($domain, $user, "roles",
                   8334: 				 &GDBM_READER());
                   8335: 
                   8336:     #  Author role should show up as a key /domain/_au
1.78      foxr     8337: 
1.321     albertel 8338:     my $value;
1.487     foxr     8339:     if ($hashref) {
1.78      foxr     8340: 
1.487     foxr     8341: 	my $key    = "/$domain/_au";
                   8342: 	if (defined($hashref)) {
                   8343: 	    $value = $hashref->{$key};
                   8344: 	    if(!untie_user_hash($hashref)) {
                   8345: 		return 'error: ' .  ($!+0)." untie (GDBM) Failed";
                   8346: 	    }
                   8347: 	}
                   8348: 	
                   8349: 	if(defined($value)) {
                   8350: 	    &Debug("$user @ $domain is an author");
                   8351: 	}
                   8352:     } else {
                   8353: 	return 'error: '.($!+0)." tie (GDBM) Failed";
1.261     foxr     8354:     }
                   8355: 
                   8356:     return defined($value);
                   8357: }
1.78      foxr     8358: #
                   8359: #   Checks to see if the input roleput request was to set
1.482     www      8360: # an author role.  If so, creates construction space 
1.78      foxr     8361: # Parameters:
                   8362: #    request   - The request sent to the rolesput subchunk.
                   8363: #                We're looking for  /domain/_au
                   8364: #    domain    - The domain in which the user is having roles doctored.
                   8365: #    user      - Name of the user for which the role is being put.
                   8366: #    authtype  - The authentication type associated with the user.
                   8367: #
1.289     albertel 8368: sub manage_permissions {
1.192     foxr     8369:     my ($request, $domain, $user, $authtype) = @_;
1.78      foxr     8370:     # See if the request is of the form /$domain/_au
1.289     albertel 8371:     if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
1.484     raeburn  8372:         my $path=$perlvar{'lonDocRoot'}."/priv/$domain";
1.482     www      8373:         unless (-e $path) {        
                   8374:            mkdir($path);
                   8375:         }
                   8376:         unless (-e $path.'/'.$user) {
                   8377:            mkdir($path.'/'.$user);
                   8378:         }
1.78      foxr     8379:     }
                   8380: }
1.222     foxr     8381: 
                   8382: 
                   8383: #
                   8384: #  Return the full path of a user password file, whether it exists or not.
                   8385: # Parameters:
                   8386: #   domain     - Domain in which the password file lives.
                   8387: #   user       - name of the user.
                   8388: # Returns:
                   8389: #    Full passwd path:
                   8390: #
                   8391: sub password_path {
                   8392:     my ($domain, $user) = @_;
1.264     albertel 8393:     return &propath($domain, $user).'/passwd';
1.222     foxr     8394: }
                   8395: 
                   8396: #   Password Filename
                   8397: #   Returns the path to a passwd file given domain and user... only if
                   8398: #  it exists.
                   8399: # Parameters:
                   8400: #   domain    - Domain in which to search.
                   8401: #   user      - username.
                   8402: # Returns:
                   8403: #   - If the password file exists returns its path.
                   8404: #   - If the password file does not exist, returns undefined.
                   8405: #
                   8406: sub password_filename {
                   8407:     my ($domain, $user) = @_;
                   8408: 
                   8409:     Debug ("PasswordFilename called: dom = $domain user = $user");
                   8410: 
                   8411:     my $path  = &password_path($domain, $user);
                   8412:     Debug("PasswordFilename got path: $path");
                   8413:     if(-e $path) {
                   8414: 	return $path;
                   8415:     } else {
                   8416: 	return undef;
                   8417:     }
                   8418: }
                   8419: 
                   8420: #
                   8421: #   Rewrite the contents of the user's passwd file.
                   8422: #  Parameters:
                   8423: #    domain    - domain of the user.
                   8424: #    name      - User's name.
                   8425: #    contents  - New contents of the file.
1.533     raeburn  8426: #    saveold   - (optional). If true save old file in a passwd.bak file.
1.222     foxr     8427: # Returns:
                   8428: #   0    - Failed.
                   8429: #   1    - Success.
                   8430: #
                   8431: sub rewrite_password_file {
1.533     raeburn  8432:     my ($domain, $user, $contents, $saveold) = @_;
1.222     foxr     8433: 
                   8434:     my $file = &password_filename($domain, $user);
                   8435:     if (defined $file) {
1.533     raeburn  8436:         if ($saveold) {
                   8437:             my $bakfile = $file.'.bak';
                   8438:             if (CopyFile($file,$bakfile)) {
                   8439:                 chmod(0400,$bakfile);
                   8440:                 &logthis("Old password saved in passwd.bak for internally authenticated user: $user:$domain");
                   8441:             } else {
                   8442:                 &logthis("Failed to save old password in passwd.bak for internally authenticated user: $user:$domain");
                   8443:             }
                   8444:         }
1.222     foxr     8445: 	my $pf = IO::File->new(">$file");
                   8446: 	if($pf) {
                   8447: 	    print $pf "$contents\n";
                   8448: 	    return 1;
                   8449: 	} else {
                   8450: 	    return 0;
                   8451: 	}
                   8452:     } else {
                   8453: 	return 0;
                   8454:     }
                   8455: 
                   8456: }
                   8457: 
1.78      foxr     8458: #
1.222     foxr     8459: #   get_auth_type - Determines the authorization type of a user in a domain.
1.78      foxr     8460: 
                   8461: #     Returns the authorization type or nouser if there is no such user.
                   8462: #
1.436     raeburn  8463: sub get_auth_type {
1.192     foxr     8464:     my ($domain, $user)  = @_;
1.78      foxr     8465: 
1.222     foxr     8466:     Debug("get_auth_type( $domain, $user ) \n");
1.78      foxr     8467:     my $proname    = &propath($domain, $user); 
                   8468:     my $passwdfile = "$proname/passwd";
                   8469:     if( -e $passwdfile ) {
                   8470: 	my $pf = IO::File->new($passwdfile);
                   8471: 	my $realpassword = <$pf>;
                   8472: 	chomp($realpassword);
1.79      foxr     8473: 	Debug("Password info = $realpassword\n");
1.78      foxr     8474: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79      foxr     8475: 	Debug("Authtype = $authtype, content = $contentpwd\n");
1.259     raeburn  8476: 	return "$authtype:$contentpwd";     
1.224     foxr     8477:     } else {
1.79      foxr     8478: 	Debug("Returning nouser");
1.78      foxr     8479: 	return "nouser";
                   8480:     }
1.1       albertel 8481: }
                   8482: 
1.220     foxr     8483: #
                   8484: #  Validate a user given their domain, name and password.  This utility
                   8485: #  function is used by both  AuthenticateHandler and ChangePasswordHandler
                   8486: #  to validate the login credentials of a user.
                   8487: # Parameters:
                   8488: #    $domain    - The domain being logged into (this is required due to
                   8489: #                 the capability for multihomed systems.
                   8490: #    $user      - The name of the user being validated.
                   8491: #    $password  - The user's propoposed password.
                   8492: #
                   8493: # Returns:
                   8494: #     1        - The domain,user,pasword triplet corresponds to a valid
                   8495: #                user.
                   8496: #     0        - The domain,user,password triplet is not a valid user.
                   8497: #
                   8498: sub validate_user {
1.396     raeburn  8499:     my ($domain, $user, $password, $checkdefauth) = @_;
1.220     foxr     8500: 
                   8501:     # Why negative ~pi you may well ask?  Well this function is about
                   8502:     # authentication, and therefore very important to get right.
                   8503:     # I've initialized the flag that determines whether or not I've 
                   8504:     # validated correctly to a value it's not supposed to get.
                   8505:     # At the end of this function. I'll ensure that it's not still that
                   8506:     # value so we don't just wind up returning some accidental value
                   8507:     # as a result of executing an unforseen code path that
1.249     foxr     8508:     # did not set $validated.  At the end of valid execution paths,
                   8509:     # validated shoule be 1 for success or 0 for failuer.
1.220     foxr     8510: 
                   8511:     my $validated = -3.14159;
                   8512: 
                   8513:     #  How we authenticate is determined by the type of authentication
                   8514:     #  the user has been assigned.  If the authentication type is
                   8515:     #  "nouser", the user does not exist so we will return 0.
                   8516: 
1.222     foxr     8517:     my $contents = &get_auth_type($domain, $user);
1.220     foxr     8518:     my ($howpwd, $contentpwd) = split(/:/, $contents);
                   8519: 
                   8520:     my $null = pack("C",0);	# Used by kerberos auth types.
                   8521: 
1.395     raeburn  8522:     if ($howpwd eq 'nouser') {
1.396     raeburn  8523:         if ($checkdefauth) {
                   8524:             my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   8525:             if ($domdefaults{'auth_def'} eq 'localauth') {
                   8526:                 $howpwd = $domdefaults{'auth_def'};
                   8527:                 $contentpwd = $domdefaults{'auth_arg_def'};
                   8528:             } elsif ((($domdefaults{'auth_def'} eq 'krb4') || 
                   8529:                       ($domdefaults{'auth_def'} eq 'krb5')) &&
                   8530:                      ($domdefaults{'auth_arg_def'} ne '')) {
1.574     raeburn  8531:                 #
                   8532:                 # Don't attempt authentication for username and password supplied
                   8533:                 # for user without an account if uername contains @ to avoid
1.575     raeburn  8534:                 # call to &Authen::Krb5::parse_name() which will result in con_lost
1.574     raeburn  8535:                 #
                   8536:                 unless ($user =~ /\@/) {
                   8537:                     $howpwd = $domdefaults{'auth_def'};
                   8538:                     $contentpwd = $domdefaults{'auth_arg_def'};
                   8539:                 }
1.396     raeburn  8540:             }
1.395     raeburn  8541:         }
1.533     raeburn  8542:     }
1.220     foxr     8543:     if ($howpwd ne 'nouser') {
                   8544: 	if($howpwd eq "internal") { # Encrypted is in local password file.
1.518     raeburn  8545:             if (length($contentpwd) == 13) {
                   8546:                 $validated = (crypt($password,$contentpwd) eq $contentpwd);
                   8547:                 if ($validated) {
1.533     raeburn  8548:                     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   8549:                     if ($domdefaults{'intauth_switch'}) {
                   8550:                         my $ncpass = &hash_passwd($domain,$password);
                   8551:                         my $saveold;
                   8552:                         if ($domdefaults{'intauth_switch'} == 2) {
                   8553:                             $saveold = 1;
                   8554:                         }
                   8555:                         if (&rewrite_password_file($domain,$user,"$howpwd:$ncpass",$saveold)) {
                   8556:                             &update_passwd_history($user,$domain,$howpwd,'conversion');
                   8557:                             &logthis("Validated password hashed with bcrypt for $user:$domain");
                   8558:                         }
1.518     raeburn  8559:                     }
                   8560:                 }
                   8561:             } else {
1.533     raeburn  8562:                 $validated = &check_internal_passwd($password,$contentpwd,$domain,$user);
1.518     raeburn  8563:             }
1.220     foxr     8564: 	}
                   8565: 	elsif ($howpwd eq "unix") { # User is a normal unix user.
                   8566: 	    $contentpwd = (getpwnam($user))[1];
                   8567: 	    if($contentpwd) {
                   8568: 		if($contentpwd eq 'x') { # Shadow password file...
                   8569: 		    my $pwauth_path = "/usr/local/sbin/pwauth";
                   8570: 		    open PWAUTH,  "|$pwauth_path" or
                   8571: 			die "Cannot invoke authentication";
                   8572: 		    print PWAUTH "$user\n$password\n";
                   8573: 		    close PWAUTH;
                   8574: 		    $validated = ! $?;
                   8575: 
                   8576: 		} else { 	         # Passwords in /etc/passwd. 
                   8577: 		    $validated = (crypt($password,
                   8578: 					$contentpwd) eq $contentpwd);
                   8579: 		}
                   8580: 	    } else {
                   8581: 		$validated = 0;
                   8582: 	    }
1.439     raeburn  8583: 	} elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
                   8584:             my $checkwithkrb5 = 0;
                   8585:             if ($dist =~/^fedora(\d+)$/) {
                   8586:                 if ($1 > 11) {
                   8587:                     $checkwithkrb5 = 1;
                   8588:                 }
                   8589:             } elsif ($dist =~ /^suse([\d.]+)$/) {
                   8590:                 if ($1 > 11.1) {
                   8591:                     $checkwithkrb5 = 1; 
                   8592:                 }
                   8593:             }
                   8594:             if ($checkwithkrb5) {
                   8595:                 $validated = &krb5_authen($password,$null,$user,$contentpwd);
                   8596:             } else {
                   8597:                 $validated = &krb4_authen($password,$null,$user,$contentpwd);
                   8598:             }
1.224     foxr     8599: 	} elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
1.439     raeburn  8600:             $validated = &krb5_authen($password,$null,$user,$contentpwd);
1.224     foxr     8601: 	} elsif ($howpwd eq "localauth") { 
1.220     foxr     8602: 	    #  Authenticate via installation specific authentcation method:
                   8603: 	    $validated = &localauth::localauth($user, 
                   8604: 					       $password, 
1.353     albertel 8605: 					       $contentpwd,
                   8606: 					       $domain);
1.358     albertel 8607: 	    if ($validated < 0) {
1.357     albertel 8608: 		&logthis("localauth for $contentpwd $user:$domain returned a $validated");
                   8609: 		$validated = 0;
                   8610: 	    }
1.224     foxr     8611: 	} else {			# Unrecognized auth is also bad.
1.220     foxr     8612: 	    $validated = 0;
                   8613: 	}
                   8614:     } else {
                   8615: 	$validated = 0;
                   8616:     }
                   8617:     #
                   8618:     #  $validated has the correct stat of the authentication:
                   8619:     #
                   8620: 
                   8621:     unless ($validated != -3.14159) {
1.249     foxr     8622: 	#  I >really really< want to know if this happens.
                   8623: 	#  since it indicates that user authentication is badly
                   8624: 	#  broken in some code path.
                   8625:         #
                   8626: 	die "ValidateUser - failed to set the value of validated $domain, $user $password";
1.220     foxr     8627:     }
                   8628:     return $validated;
                   8629: }
                   8630: 
1.518     raeburn  8631: sub check_internal_passwd {
1.533     raeburn  8632:     my ($plainpass,$stored,$domain,$user) = @_;
1.518     raeburn  8633:     my (undef,$method,@rest) = split(/!/,$stored);
1.533     raeburn  8634:     if ($method eq 'bcrypt') {
1.518     raeburn  8635:         my $result = &hash_passwd($domain,$plainpass,@rest);
                   8636:         if ($result ne $stored) {
                   8637:             return 0;
                   8638:         }
1.533     raeburn  8639:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   8640:         if ($domdefaults{'intauth_check'}) {
                   8641:             # Upgrade to a larger number of rounds if necessary
                   8642:             my $defaultcost = $domdefaults{'intauth_cost'};
                   8643:             if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
                   8644:                 $defaultcost = 10;
                   8645:             }
                   8646:             if (int($rest[0])<int($defaultcost)) {
                   8647:                 if ($domdefaults{'intauth_check'} == 1) { 
                   8648:                     my $ncpass = &hash_passwd($domain,$plainpass);
                   8649:                     if (&rewrite_password_file($domain,$user,"internal:$ncpass")) {
                   8650:                         &update_passwd_history($user,$domain,'internal','update cost');
                   8651:                         &logthis("Validated password hashed with bcrypt for $user:$domain");
                   8652:                     }
                   8653:                     return 1;
                   8654:                 } elsif ($domdefaults{'intauth_check'} == 2) {
                   8655:                     return 0;
                   8656:                 }
                   8657:             }
                   8658:         } else {
                   8659:             return 1;
1.518     raeburn  8660:         }
                   8661:     }
                   8662:     return 0;
                   8663: }
                   8664: 
                   8665: sub get_last_authchg {
                   8666:     my ($domain,$user) = @_;
                   8667:     my $lastmod;
                   8668:     my $logname = &propath($domain,$user).'/passwd.log';
                   8669:     if (-e "$logname") {
                   8670:         $lastmod = (stat("$logname"))[9];
                   8671:     }
                   8672:     return $lastmod;
                   8673: }
                   8674: 
1.439     raeburn  8675: sub krb4_authen {
                   8676:     my ($password,$null,$user,$contentpwd) = @_;
                   8677:     my $validated = 0;
                   8678:     if (!($password =~ /$null/) ) {  # Null password not allowed.
                   8679:         eval {
                   8680:             require Authen::Krb4;
                   8681:         };
                   8682:         if (!$@) {
                   8683:             my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
                   8684:                                                        "",
                   8685:                                                        $contentpwd,,
                   8686:                                                        'krbtgt',
                   8687:                                                        $contentpwd,
                   8688:                                                        1,
                   8689:                                                        $password);
                   8690:             if(!$k4error) {
                   8691:                 $validated = 1;
                   8692:             } else {
                   8693:                 $validated = 0;
                   8694:                 &logthis('krb4: '.$user.', '.$contentpwd.', '.
                   8695:                           &Authen::Krb4::get_err_txt($Authen::Krb4::error));
                   8696:             }
                   8697:         } else {
                   8698:             $validated = krb5_authen($password,$null,$user,$contentpwd);
                   8699:         }
                   8700:     }
                   8701:     return $validated;
                   8702: }
                   8703: 
                   8704: sub krb5_authen {
                   8705:     my ($password,$null,$user,$contentpwd) = @_;
                   8706:     my $validated = 0;
                   8707:     if(!($password =~ /$null/)) { # Null password not allowed.
                   8708:         my $krbclient = &Authen::Krb5::parse_name($user.'@'
                   8709:                                                   .$contentpwd);
                   8710:         my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
                   8711:         my $krbserver  = &Authen::Krb5::parse_name($krbservice);
                   8712:         my $credentials= &Authen::Krb5::cc_default();
                   8713:         $credentials->initialize(&Authen::Krb5::parse_name($user.'@'
                   8714:                                                             .$contentpwd));
                   8715:         my $krbreturn;
                   8716:         if (exists(&Authen::Krb5::get_init_creds_password)) {
                   8717:             $krbreturn =
                   8718:                 &Authen::Krb5::get_init_creds_password($krbclient,$password,
                   8719:                                                           $krbservice);
                   8720:             $validated = (ref($krbreturn) eq 'Authen::Krb5::Creds');
                   8721:         } else {
                   8722:             $krbreturn  =
                   8723:                 &Authen::Krb5::get_in_tkt_with_password($krbclient,$krbserver,
                   8724:                                                          $password,$credentials);
                   8725:             $validated = ($krbreturn == 1);
                   8726:         }
                   8727:         if (!$validated) {
                   8728:             &logthis('krb5: '.$user.', '.$contentpwd.', '.
                   8729:                      &Authen::Krb5::error());
                   8730:         }
                   8731:     }
                   8732:     return $validated;
                   8733: }
1.220     foxr     8734: 
1.84      albertel 8735: sub addline {
                   8736:     my ($fname,$hostid,$ip,$newline)=@_;
                   8737:     my $contents;
                   8738:     my $found=0;
1.355     albertel 8739:     my $expr='^'.quotemeta($hostid).':'.quotemeta($ip).':';
1.134     albertel 8740:     my $sh;
1.84      albertel 8741:     if ($sh=IO::File->new("$fname.subscription")) {
                   8742: 	while (my $subline=<$sh>) {
                   8743: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
                   8744: 	}
                   8745: 	$sh->close();
                   8746:     }
                   8747:     $sh=IO::File->new(">$fname.subscription");
                   8748:     if ($contents) { print $sh $contents; }
                   8749:     if ($newline) { print $sh $newline; }
                   8750:     $sh->close();
                   8751:     return $found;
1.86      www      8752: }
                   8753: 
1.234     foxr     8754: sub get_chat {
1.324     raeburn  8755:     my ($cdom,$cname,$udom,$uname,$group)=@_;
1.310     albertel 8756: 
1.87      www      8757:     my @entries=();
1.324     raeburn  8758:     my $namespace = 'nohist_chatroom';
                   8759:     my $namespace_inroom = 'nohist_inchatroom';
1.335     albertel 8760:     if ($group ne '') {
1.324     raeburn  8761:         $namespace .= '_'.$group;
                   8762:         $namespace_inroom .= '_'.$group;
                   8763:     }
                   8764:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 8765: 				 &GDBM_READER());
                   8766:     if ($hashref) {
                   8767: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.311     albertel 8768: 	&untie_user_hash($hashref);
1.123     www      8769:     }
1.124     www      8770:     my @participants=();
1.134     albertel 8771:     my $cutoff=time-60;
1.324     raeburn  8772:     $hashref = &tie_user_hash($cdom, $cname, $namespace_inroom,
1.310     albertel 8773: 			      &GDBM_WRCREAT());
                   8774:     if ($hashref) {
                   8775:         $hashref->{$uname.':'.$udom}=time;
                   8776:         foreach my $user (sort(keys(%$hashref))) {
                   8777: 	    if ($hashref->{$user}>$cutoff) {
                   8778: 		push(@participants, 'active_participant:'.$user);
1.123     www      8779:             }
                   8780:         }
1.311     albertel 8781:         &untie_user_hash($hashref);
1.86      www      8782:     }
1.124     www      8783:     return (@participants,@entries);
1.86      www      8784: }
                   8785: 
1.234     foxr     8786: sub chat_add {
1.324     raeburn  8787:     my ($cdom,$cname,$newchat,$group)=@_;
1.88      albertel 8788:     my @entries=();
1.142     www      8789:     my $time=time;
1.324     raeburn  8790:     my $namespace = 'nohist_chatroom';
                   8791:     my $logfile = 'chatroom.log';
1.335     albertel 8792:     if ($group ne '') {
1.324     raeburn  8793:         $namespace .= '_'.$group;
                   8794:         $logfile = 'chatroom_'.$group.'.log';
                   8795:     }
                   8796:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 8797: 				 &GDBM_WRCREAT());
                   8798:     if ($hashref) {
                   8799: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.88      albertel 8800: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
                   8801: 	my ($thentime,$idnum)=split(/\_/,$lastid);
                   8802: 	my $newid=$time.'_000000';
                   8803: 	if ($thentime==$time) {
                   8804: 	    $idnum=~s/^0+//;
                   8805: 	    $idnum++;
                   8806: 	    $idnum=substr('000000'.$idnum,-6,6);
                   8807: 	    $newid=$time.'_'.$idnum;
                   8808: 	}
1.310     albertel 8809: 	$hashref->{$newid}=$newchat;
1.88      albertel 8810: 	my $expired=$time-3600;
1.310     albertel 8811: 	foreach my $comment (keys(%$hashref)) {
                   8812: 	    my ($thistime) = ($comment=~/(\d+)\_/);
1.88      albertel 8813: 	    if ($thistime<$expired) {
1.310     albertel 8814: 		delete $hashref->{$comment};
1.88      albertel 8815: 	    }
                   8816: 	}
1.310     albertel 8817: 	{
                   8818: 	    my $proname=&propath($cdom,$cname);
1.324     raeburn  8819: 	    if (open(CHATLOG,">>$proname/$logfile")) { 
1.310     albertel 8820: 		print CHATLOG ("$time:".&unescape($newchat)."\n");
                   8821: 	    }
                   8822: 	    close(CHATLOG);
1.142     www      8823: 	}
1.311     albertel 8824: 	&untie_user_hash($hashref);
1.86      www      8825:     }
1.84      albertel 8826: }
                   8827: 
                   8828: sub unsub {
                   8829:     my ($fname,$clientip)=@_;
                   8830:     my $result;
1.188     foxr     8831:     my $unsubs = 0;		# Number of successful unsubscribes:
                   8832: 
                   8833: 
                   8834:     # An old way subscriptions were handled was to have a 
                   8835:     # subscription marker file:
                   8836: 
                   8837:     Debug("Attempting unlink of $fname.$clientname");
1.161     foxr     8838:     if (unlink("$fname.$clientname")) {
1.188     foxr     8839: 	$unsubs++;		# Successful unsub via marker file.
                   8840:     } 
                   8841: 
                   8842:     # The more modern way to do it is to have a subscription list
                   8843:     # file:
                   8844: 
1.84      albertel 8845:     if (-e "$fname.subscription") {
1.161     foxr     8846: 	my $found=&addline($fname,$clientname,$clientip,'');
1.188     foxr     8847: 	if ($found) { 
                   8848: 	    $unsubs++;
                   8849: 	}
                   8850:     } 
                   8851: 
                   8852:     #  If either or both of these mechanisms succeeded in unsubscribing a 
                   8853:     #  resource we can return ok:
                   8854: 
                   8855:     if($unsubs) {
                   8856: 	$result = "ok\n";
1.84      albertel 8857:     } else {
1.188     foxr     8858: 	$result = "not_subscribed\n";
1.84      albertel 8859:     }
1.188     foxr     8860: 
1.84      albertel 8861:     return $result;
                   8862: }
                   8863: 
1.101     www      8864: sub currentversion {
                   8865:     my $fname=shift;
                   8866:     my $version=-1;
                   8867:     my $ulsdir='';
                   8868:     if ($fname=~/^(.+)\/[^\/]+$/) {
                   8869:        $ulsdir=$1;
                   8870:     }
1.114     albertel 8871:     my ($fnamere1,$fnamere2);
                   8872:     # remove version if already specified
1.101     www      8873:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114     albertel 8874:     # get the bits that go before and after the version number
                   8875:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
                   8876: 	$fnamere1=$1;
                   8877: 	$fnamere2='.'.$2;
                   8878:     }
1.101     www      8879:     if (-e $fname) { $version=1; }
                   8880:     if (-e $ulsdir) {
1.134     albertel 8881: 	if(-d $ulsdir) {
                   8882: 	    if (opendir(LSDIR,$ulsdir)) {
1.580   ! raeburn  8883:                 if (-e $fname) {
        !          8884:                     $version=0;
        !          8885:                 }
1.134     albertel 8886: 		my $ulsfn;
                   8887: 		while ($ulsfn=readdir(LSDIR)) {
1.101     www      8888: # see if this is a regular file (ignore links produced earlier)
1.134     albertel 8889: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
                   8890: 		    unless (-l $thisfile) {
1.160     www      8891: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134     albertel 8892: 			    if ($1>$version) { $version=$1; }
                   8893: 			}
                   8894: 		    }
                   8895: 		}
                   8896: 		closedir(LSDIR);
                   8897: 		$version++;
                   8898: 	    }
                   8899: 	}
                   8900:     }
                   8901:     return $version;
1.101     www      8902: }
                   8903: 
                   8904: sub thisversion {
                   8905:     my $fname=shift;
                   8906:     my $version=-1;
                   8907:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
                   8908: 	$version=$1;
                   8909:     }
                   8910:     return $version;
                   8911: }
                   8912: 
1.84      albertel 8913: sub subscribe {
                   8914:     my ($userinput,$clientip)=@_;
                   8915:     my $result;
1.293     albertel 8916:     my ($cmd,$fname)=split(/:/,$userinput,2);
1.84      albertel 8917:     my $ownership=&ishome($fname);
                   8918:     if ($ownership eq 'owner') {
1.101     www      8919: # explitly asking for the current version?
                   8920:         unless (-e $fname) {
                   8921:             my $currentversion=&currentversion($fname);
                   8922: 	    if (&thisversion($fname)==$currentversion) {
                   8923:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
                   8924: 		    my $root=$1;
                   8925:                     my $extension=$2;
                   8926:                     symlink($root.'.'.$extension,
                   8927:                             $root.'.'.$currentversion.'.'.$extension);
1.102     www      8928:                     unless ($extension=~/\.meta$/) {
                   8929:                        symlink($root.'.'.$extension.'.meta',
                   8930:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
                   8931: 		    }
1.101     www      8932:                 }
                   8933:             }
                   8934:         }
1.84      albertel 8935: 	if (-e $fname) {
                   8936: 	    if (-d $fname) {
                   8937: 		$result="directory\n";
                   8938: 	    } else {
1.161     foxr     8939: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134     albertel 8940: 		my $now=time;
1.161     foxr     8941: 		my $found=&addline($fname,$clientname,$clientip,
                   8942: 				   "$clientname:$clientip:$now\n");
1.84      albertel 8943: 		if ($found) { $result="$fname\n"; }
                   8944: 		# if they were subscribed to only meta data, delete that
                   8945:                 # subscription, when you subscribe to a file you also get
                   8946:                 # the metadata
                   8947: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
                   8948: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
1.476     raeburn  8949:                 my $protocol = $Apache::lonnet::protocol{$perlvar{'lonHostID'}};
                   8950:                 $protocol = 'http' if ($protocol ne 'https');
                   8951: 		$fname=$protocol.'://'.&Apache::lonnet::hostname($perlvar{'lonHostID'})."/".$fname;
1.84      albertel 8952: 		$result="$fname\n";
                   8953: 	    }
                   8954: 	} else {
                   8955: 	    $result="not_found\n";
                   8956: 	}
                   8957:     } else {
                   8958: 	$result="rejected\n";
                   8959:     }
                   8960:     return $result;
                   8961: }
1.287     foxr     8962: #  Change the passwd of a unix user.  The caller must have
                   8963: #  first verified that the user is a loncapa user.
                   8964: #
                   8965: # Parameters:
                   8966: #    user      - Unix user name to change.
                   8967: #    pass      - New password for the user.
                   8968: # Returns:
                   8969: #    ok    - if success
                   8970: #    other - Some meaningfule error message string.
                   8971: # NOTE:
                   8972: #    invokes a setuid script to change the passwd.
                   8973: sub change_unix_password {
                   8974:     my ($user, $pass) = @_;
                   8975: 
                   8976:     &Debug("change_unix_password");
                   8977:     my $execdir=$perlvar{'lonDaemons'};
                   8978:     &Debug("Opening lcpasswd pipeline");
                   8979:     my $pf = IO::File->new("|$execdir/lcpasswd > "
                   8980: 			   ."$perlvar{'lonDaemons'}"
                   8981: 			   ."/logs/lcpasswd.log");
                   8982:     print $pf "$user\n$pass\n$pass\n";
                   8983:     close $pf;
                   8984:     my $err = $?;
                   8985:     return ($err < @passwderrors) ? $passwderrors[$err] : 
                   8986: 	"pwchange_falure - unknown error";
                   8987: 
                   8988:     
                   8989: }
                   8990: 
1.91      albertel 8991: 
                   8992: sub make_passwd_file {
1.518     raeburn  8993:     my ($uname,$udom,$umode,$npass,$passfilename,$action)=@_;
1.390     raeburn  8994:     my $result="ok";
1.91      albertel 8995:     if ($umode eq 'krb4' or $umode eq 'krb5') {
                   8996: 	{
                   8997: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8998: 	    if ($pf) {
                   8999: 		print $pf "$umode:$npass\n";
1.518     raeburn  9000:                 &update_passwd_history($uname,$udom,$umode,$action);
1.261     foxr     9001: 	    } else {
                   9002: 		$result = "pass_file_failed_error";
                   9003: 	    }
1.91      albertel 9004: 	}
                   9005:     } elsif ($umode eq 'internal') {
1.518     raeburn  9006:         my $ncpass = &hash_passwd($udom,$npass);
1.91      albertel 9007: 	{
                   9008: 	    &Debug("Creating internal auth");
                   9009: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     9010: 	    if($pf) {
1.518     raeburn  9011: 		print $pf "internal:$ncpass\n";
                   9012:                 &update_passwd_history($uname,$udom,$umode,$action); 
1.261     foxr     9013: 	    } else {
                   9014: 		$result = "pass_file_failed_error";
                   9015: 	    }
1.91      albertel 9016: 	}
                   9017:     } elsif ($umode eq 'localauth') {
                   9018: 	{
                   9019: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     9020: 	    if($pf) {
                   9021: 		print $pf "localauth:$npass\n";
1.524     raeburn  9022:                 &update_passwd_history($uname,$udom,$umode,$action);
1.261     foxr     9023: 	    } else {
                   9024: 		$result = "pass_file_failed_error";
                   9025: 	    }
1.91      albertel 9026: 	}
                   9027:     } elsif ($umode eq 'unix') {
1.502     raeburn  9028: 	&logthis(">>>Attempt to create unix account blocked -- unix auth not available for new users.");
                   9029: 	$result="no_new_unix_accounts";
1.91      albertel 9030:     } elsif ($umode eq 'none') {
                   9031: 	{
1.223     foxr     9032: 	    my $pf = IO::File->new("> $passfilename");
1.261     foxr     9033: 	    if($pf) {
                   9034: 		print $pf "none:\n";
                   9035: 	    } else {
                   9036: 		$result = "pass_file_failed_error";
                   9037: 	    }
1.91      albertel 9038: 	}
1.543     raeburn  9039:     } elsif ($umode eq 'lti') {
                   9040:         my $pf = IO::File->new(">$passfilename");
                   9041:         if($pf) {
                   9042:             print $pf "lti:\n";
                   9043:             &update_passwd_history($uname,$udom,$umode,$action);
                   9044:         } else {
                   9045:             $result = "pass_file_failed_error";
                   9046:         }
1.91      albertel 9047:     } else {
1.390     raeburn  9048: 	$result="auth_mode_error";
1.91      albertel 9049:     }
                   9050:     return $result;
1.121     albertel 9051: }
                   9052: 
1.265     albertel 9053: sub convert_photo {
                   9054:     my ($start,$dest)=@_;
                   9055:     system("convert $start $dest");
                   9056: }
                   9057: 
1.121     albertel 9058: sub sethost {
                   9059:     my ($remotereq) = @_;
                   9060:     my (undef,$hostid)=split(/:/,$remotereq);
1.322     albertel 9061:     # ignore sethost if we are already correct
                   9062:     if ($hostid eq $currenthostid) {
                   9063: 	return 'ok';
                   9064:     }
                   9065: 
1.121     albertel 9066:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
1.368     albertel 9067:     if (&Apache::lonnet::get_host_ip($perlvar{'lonHostID'}) 
                   9068: 	eq &Apache::lonnet::get_host_ip($hostid)) {
1.200     matthew  9069: 	$currenthostid  =$hostid;
1.369     albertel 9070: 	$currentdomainid=&Apache::lonnet::host_domain($hostid);
1.556     raeburn  9071:         &set_client_info();
1.443     www      9072: #	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
1.121     albertel 9073:     } else {
                   9074: 	&logthis("Requested host id $hostid not an alias of ".
                   9075: 		 $perlvar{'lonHostID'}." refusing connection");
                   9076: 	return 'unable_to_set';
                   9077:     }
                   9078:     return 'ok';
                   9079: }
                   9080: 
                   9081: sub version {
                   9082:     my ($userinput)=@_;
                   9083:     $remoteVERSION=(split(/:/,$userinput))[1];
                   9084:     return "version:$VERSION";
1.127     albertel 9085: }
1.178     foxr     9086: 
1.447     raeburn  9087: sub get_usersession_config {
                   9088:     my ($dom,$name) = @_;
                   9089:     my ($usersessionconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   9090:     if (defined($cached)) {
                   9091:         return $usersessionconf;
                   9092:     } else {
                   9093:         my %domconfig = &Apache::lonnet::get_dom('configuration',['usersessions'],$dom);
1.525     raeburn  9094:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'usersessions'},3600);
                   9095:         return $domconfig{'usersessions'};
1.447     raeburn  9096:     }
                   9097:     return;
                   9098: }
1.200     matthew  9099: 
1.534     raeburn  9100: sub get_usersearch_config {
                   9101:     my ($dom,$name) = @_;
                   9102:     my ($usersearchconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   9103:     if (defined($cached)) {
                   9104:         return $usersearchconf;
                   9105:     } else {
                   9106:         my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$dom);
                   9107:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'directorysrch'},600);
                   9108:         return $domconfig{'directorysrch'};
                   9109:     }
                   9110:     return;
                   9111: }
                   9112: 
1.525     raeburn  9113: sub get_prohibited {
                   9114:     my ($dom) = @_;
                   9115:     my $name = 'trust';
                   9116:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   9117:     unless (defined($cached)) {
                   9118:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$dom);
                   9119:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'trust'},3600);
                   9120:         $trustconfig = $domconfig{'trust'};
                   9121:     }
                   9122:     my %prohibited;
                   9123:     if (ref($trustconfig)) {
                   9124:         foreach my $prefix (keys(%{$trustconfig})) {
                   9125:             if (ref($trustconfig->{$prefix}) eq 'HASH') {
                   9126:                 my $reject;
                   9127:                 if (ref($trustconfig->{$prefix}->{'exc'}) eq 'ARRAY') {
                   9128:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'exc'}})) {
                   9129:                         $reject = 1;
                   9130:                     }
                   9131:                 }
                   9132:                 if (ref($trustconfig->{$prefix}->{'inc'}) eq 'ARRAY') {
                   9133:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'inc'}})) {
                   9134:                         $reject = 0;
                   9135:                     } else {
                   9136:                         $reject = 1;
                   9137:                     }
                   9138:                 }
                   9139:                 if ($reject) {
                   9140:                     $prohibited{$prefix} = 1;
                   9141:                 }
                   9142:             }
                   9143:         }
                   9144:     }
                   9145:     return %prohibited;
                   9146: }
1.450     raeburn  9147: 
1.556     raeburn  9148: sub get_remote_hostable {
                   9149:     my ($dom) = @_;
                   9150:     my $result;
                   9151:     if ($clientintdom) {
                   9152:         $result = 1;
                   9153:         my $remsessconf = &get_usersession_config($dom,'remotesession');
                   9154:         if (ref($remsessconf) eq 'HASH') {
                   9155:             if (ref($remsessconf->{'remote'}) eq 'HASH') {
                   9156:                 if (ref($remsessconf->{'remote'}->{'excludedomain'}) eq 'ARRAY') {
                   9157:                     if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'excludedomain'}})) {
                   9158:                         $result = 0;
                   9159:                     }
                   9160:                 }
                   9161:                 if (ref($remsessconf->{'remote'}->{'includedomain'}) eq 'ARRAY') {
                   9162:                     if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'includedomain'}})) {
                   9163:                         $result = 1;
                   9164:                     } else {
                   9165:                         $result = 0;
                   9166:                     }
                   9167:                 }
                   9168:             }
                   9169:         }
                   9170:     }
                   9171:     return $result;
                   9172: }
                   9173: 
1.471     raeburn  9174: sub distro_and_arch {
                   9175:     return $dist.':'.$arch;
                   9176: }
                   9177: 
1.61      harris41 9178: # ----------------------------------- POD (plain old documentation, CPAN style)
                   9179: 
                   9180: =head1 NAME
                   9181: 
                   9182: lond - "LON Daemon" Server (port "LOND" 5663)
                   9183: 
                   9184: =head1 SYNOPSIS
                   9185: 
1.74      harris41 9186: Usage: B<lond>
                   9187: 
                   9188: Should only be run as user=www.  This is a command-line script which
                   9189: is invoked by B<loncron>.  There is no expectation that a typical user
                   9190: will manually start B<lond> from the command-line.  (In other words,
                   9191: DO NOT START B<lond> YOURSELF.)
1.61      harris41 9192: 
                   9193: =head1 DESCRIPTION
                   9194: 
1.74      harris41 9195: There are two characteristics associated with the running of B<lond>,
                   9196: PROCESS MANAGEMENT (starting, stopping, handling child processes)
                   9197: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
                   9198: subscriptions, etc).  These are described in two large
                   9199: sections below.
                   9200: 
                   9201: B<PROCESS MANAGEMENT>
                   9202: 
1.61      harris41 9203: Preforker - server who forks first. Runs as a daemon. HUPs.
                   9204: Uses IDEA encryption
                   9205: 
1.74      harris41 9206: B<lond> forks off children processes that correspond to the other servers
                   9207: in the network.  Management of these processes can be done at the
                   9208: parent process level or the child process level.
                   9209: 
                   9210: B<logs/lond.log> is the location of log messages.
                   9211: 
                   9212: The process management is now explained in terms of linux shell commands,
                   9213: subroutines internal to this code, and signal assignments:
                   9214: 
                   9215: =over 4
                   9216: 
                   9217: =item *
                   9218: 
                   9219: PID is stored in B<logs/lond.pid>
                   9220: 
                   9221: This is the process id number of the parent B<lond> process.
                   9222: 
                   9223: =item *
                   9224: 
                   9225: SIGTERM and SIGINT
                   9226: 
                   9227: Parent signal assignment:
                   9228:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   9229: 
                   9230: Child signal assignment:
                   9231:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
                   9232: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
                   9233:  to restart a new child.)
                   9234: 
                   9235: Command-line invocations:
                   9236:  B<kill> B<-s> SIGTERM I<PID>
                   9237:  B<kill> B<-s> SIGINT I<PID>
                   9238: 
                   9239: Subroutine B<HUNTSMAN>:
                   9240:  This is only invoked for the B<lond> parent I<PID>.
                   9241: This kills all the children, and then the parent.
                   9242: The B<lonc.pid> file is cleared.
                   9243: 
                   9244: =item *
                   9245: 
                   9246: SIGHUP
                   9247: 
                   9248: Current bug:
                   9249:  This signal can only be processed the first time
                   9250: on the parent process.  Subsequent SIGHUP signals
                   9251: have no effect.
                   9252: 
                   9253: Parent signal assignment:
                   9254:  $SIG{HUP}  = \&HUPSMAN;
                   9255: 
                   9256: Child signal assignment:
                   9257:  none (nothing happens)
                   9258: 
                   9259: Command-line invocations:
                   9260:  B<kill> B<-s> SIGHUP I<PID>
                   9261: 
                   9262: Subroutine B<HUPSMAN>:
                   9263:  This is only invoked for the B<lond> parent I<PID>,
                   9264: This kills all the children, and then the parent.
                   9265: The B<lond.pid> file is cleared.
                   9266: 
                   9267: =item *
                   9268: 
                   9269: SIGUSR1
                   9270: 
                   9271: Parent signal assignment:
                   9272:  $SIG{USR1} = \&USRMAN;
                   9273: 
                   9274: Child signal assignment:
                   9275:  $SIG{USR1}= \&logstatus;
                   9276: 
                   9277: Command-line invocations:
                   9278:  B<kill> B<-s> SIGUSR1 I<PID>
                   9279: 
                   9280: Subroutine B<USRMAN>:
                   9281:  When invoked for the B<lond> parent I<PID>,
                   9282: SIGUSR1 is sent to all the children, and the status of
                   9283: each connection is logged.
1.144     foxr     9284: 
                   9285: =item *
                   9286: 
                   9287: SIGUSR2
                   9288: 
                   9289: Parent Signal assignment:
                   9290:     $SIG{USR2} = \&UpdateHosts
                   9291: 
                   9292: Child signal assignment:
                   9293:     NONE
                   9294: 
1.74      harris41 9295: 
                   9296: =item *
                   9297: 
                   9298: SIGCHLD
                   9299: 
                   9300: Parent signal assignment:
                   9301:  $SIG{CHLD} = \&REAPER;
                   9302: 
                   9303: Child signal assignment:
                   9304:  none
                   9305: 
                   9306: Command-line invocations:
                   9307:  B<kill> B<-s> SIGCHLD I<PID>
                   9308: 
                   9309: Subroutine B<REAPER>:
                   9310:  This is only invoked for the B<lond> parent I<PID>.
                   9311: Information pertaining to the child is removed.
                   9312: The socket port is cleaned up.
                   9313: 
                   9314: =back
                   9315: 
                   9316: B<SERVER-SIDE ACTIVITIES>
                   9317: 
                   9318: Server-side information can be accepted in an encrypted or non-encrypted
                   9319: method.
                   9320: 
                   9321: =over 4
                   9322: 
                   9323: =item ping
                   9324: 
                   9325: Query a client in the hosts.tab table; "Are you there?"
                   9326: 
                   9327: =item pong
                   9328: 
                   9329: Respond to a ping query.
                   9330: 
                   9331: =item ekey
                   9332: 
                   9333: Read in encrypted key, make cipher.  Respond with a buildkey.
                   9334: 
                   9335: =item load
                   9336: 
                   9337: Respond with CPU load based on a computation upon /proc/loadavg.
                   9338: 
                   9339: =item currentauth
                   9340: 
                   9341: Reply with current authentication information (only over an
                   9342: encrypted channel).
                   9343: 
                   9344: =item auth
                   9345: 
                   9346: Only over an encrypted channel, reply as to whether a user's
                   9347: authentication information can be validated.
                   9348: 
                   9349: =item passwd
                   9350: 
                   9351: Allow for a password to be set.
                   9352: 
                   9353: =item makeuser
                   9354: 
                   9355: Make a user.
                   9356: 
1.517     raeburn  9357: =item changeuserauth
1.74      harris41 9358: 
                   9359: Allow for authentication mechanism and password to be changed.
                   9360: 
                   9361: =item home
1.61      harris41 9362: 
1.74      harris41 9363: Respond to a question "are you the home for a given user?"
                   9364: 
                   9365: =item update
                   9366: 
                   9367: Update contents of a subscribed resource.
                   9368: 
                   9369: =item unsubscribe
                   9370: 
                   9371: The server is unsubscribing from a resource.
                   9372: 
                   9373: =item subscribe
                   9374: 
                   9375: The server is subscribing to a resource.
                   9376: 
                   9377: =item log
                   9378: 
                   9379: Place in B<logs/lond.log>
                   9380: 
                   9381: =item put
                   9382: 
                   9383: stores hash in namespace
                   9384: 
1.496     raeburn  9385: =item rolesput
1.74      harris41 9386: 
                   9387: put a role into a user's environment
                   9388: 
                   9389: =item get
                   9390: 
                   9391: returns hash with keys from array
                   9392: reference filled in from namespace
                   9393: 
                   9394: =item eget
                   9395: 
                   9396: returns hash with keys from array
                   9397: reference filled in from namesp (encrypts the return communication)
                   9398: 
                   9399: =item rolesget
                   9400: 
                   9401: get a role from a user's environment
                   9402: 
                   9403: =item del
                   9404: 
                   9405: deletes keys out of array from namespace
                   9406: 
                   9407: =item keys
                   9408: 
                   9409: returns namespace keys
                   9410: 
                   9411: =item dump
                   9412: 
                   9413: dumps the complete (or key matching regexp) namespace into a hash
                   9414: 
                   9415: =item store
                   9416: 
                   9417: stores hash permanently
                   9418: for this url; hashref needs to be given and should be a \%hashname; the
                   9419: remaining args aren't required and if they aren't passed or are '' they will
                   9420: be derived from the ENV
                   9421: 
                   9422: =item restore
                   9423: 
                   9424: returns a hash for a given url
                   9425: 
                   9426: =item querysend
                   9427: 
                   9428: Tells client about the lonsql process that has been launched in response
                   9429: to a sent query.
                   9430: 
                   9431: =item queryreply
                   9432: 
                   9433: Accept information from lonsql and make appropriate storage in temporary
                   9434: file space.
                   9435: 
                   9436: =item idput
                   9437: 
                   9438: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
                   9439: for each student, defined perhaps by the institutional Registrar.)
                   9440: 
                   9441: =item idget
                   9442: 
                   9443: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
                   9444: for each student, defined perhaps by the institutional Registrar.)
                   9445: 
1.517     raeburn  9446: =item iddel
                   9447: 
                   9448: Deletes one or more ids in a domain's id database.
                   9449: 
1.74      harris41 9450: =item tmpput
                   9451: 
                   9452: Accept and store information in temporary space.
                   9453: 
                   9454: =item tmpget
                   9455: 
                   9456: Send along temporarily stored information.
                   9457: 
                   9458: =item ls
                   9459: 
                   9460: List part of a user's directory.
                   9461: 
1.135     foxr     9462: =item pushtable
                   9463: 
                   9464: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
                   9465: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
                   9466: must be restored manually in case of a problem with the new table file.
                   9467: pushtable requires that the request be encrypted and validated via
                   9468: ValidateManager.  The form of the command is:
                   9469: enc:pushtable tablename <tablecontents> \n
                   9470: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
                   9471: cleartext newline.
                   9472: 
1.74      harris41 9473: =item Hanging up (exit or init)
                   9474: 
                   9475: What to do when a client tells the server that they (the client)
                   9476: are leaving the network.
                   9477: 
                   9478: =item unknown command
                   9479: 
                   9480: If B<lond> is sent an unknown command (not in the list above),
                   9481: it replys to the client "unknown_cmd".
1.135     foxr     9482: 
1.74      harris41 9483: 
                   9484: =item UNKNOWN CLIENT
                   9485: 
                   9486: If the anti-spoofing algorithm cannot verify the client,
                   9487: the client is rejected (with a "refused" message sent
                   9488: to the client, and the connection is closed.
                   9489: 
                   9490: =back
1.61      harris41 9491: 
                   9492: =head1 PREREQUISITES
                   9493: 
                   9494: IO::Socket
                   9495: IO::File
                   9496: Apache::File
                   9497: POSIX
                   9498: Crypt::IDEA
                   9499: GDBM_File
                   9500: Authen::Krb4
1.91      albertel 9501: Authen::Krb5
1.61      harris41 9502: 
                   9503: =head1 COREQUISITES
                   9504: 
1.490     droeschl 9505: none
                   9506: 
1.61      harris41 9507: =head1 OSNAMES
                   9508: 
                   9509: linux
                   9510: 
                   9511: =head1 SCRIPT CATEGORIES
                   9512: 
                   9513: Server/Process
                   9514: 
                   9515: =cut
1.409     foxr     9516: 
                   9517: 
                   9518: =pod
                   9519: 
                   9520: =head1 LOG MESSAGES
                   9521: 
                   9522: The messages below can be emitted in the lond log.  This log is located
                   9523: in ~httpd/perl/logs/lond.log  Many log messages have HTML encapsulation
                   9524: to provide coloring if examined from inside a web page. Some do not.
                   9525: Where color is used, the colors are; Red for sometihhng to get excited
                   9526: about and to follow up on. Yellow for something to keep an eye on to
                   9527: be sure it does not get worse, Green,and Blue for informational items.
                   9528: 
                   9529: In the discussions below, sometimes reference is made to ~httpd
                   9530: when describing file locations.  There isn't really an httpd 
                   9531: user, however there is an httpd directory that gets installed in the
                   9532: place that user home directories go.  On linux, this is usually
                   9533: (always?) /home/httpd.
                   9534: 
                   9535: 
                   9536: Some messages are colorless.  These are usually (not always)
                   9537: Green/Blue color level messages.
                   9538: 
                   9539: =over 2
                   9540: 
                   9541: =item (Red)  LocalConnection rejecting non local: <ip> ne 127.0.0.1
                   9542: 
                   9543: A local connection negotiation was attempted by
                   9544: a host whose IP address was not 127.0.0.1.
                   9545: The socket is closed and the child will exit.
                   9546: lond has three ways to establish an encyrption
                   9547: key with a client:
                   9548: 
                   9549: =over 2
                   9550: 
                   9551: =item local 
                   9552: 
                   9553: The key is written and read from a file.
                   9554: This is only valid for connections from localhost.
                   9555: 
                   9556: =item insecure 
                   9557: 
                   9558: The key is generated by the server and
                   9559: transmitted to the client.
                   9560: 
                   9561: =item  ssl (secure)
                   9562: 
                   9563: An ssl connection is negotiated with the client,
                   9564: the key is generated by the server and sent to the 
                   9565: client across this ssl connection before the
                   9566: ssl connectionis terminated and clear text
                   9567: transmission resumes.
                   9568: 
                   9569: =back
                   9570: 
                   9571: =item (Red) LocalConnection: caller is insane! init = <init> and type = <type>
                   9572: 
                   9573: The client is local but has not sent an initialization
                   9574: string that is the literal "init:local"  The connection
                   9575: is closed and the child exits.
                   9576: 
                   9577: =item Red CRITICAL Can't get key file <error>        
                   9578: 
                   9579: SSL key negotiation is being attempted but the call to
1.549     raeburn  9580: lonssl::KeyFile failed.  This usually means that the
1.409     foxr     9581: configuration file is not correctly defining or protecting
                   9582: the directories/files lonCertificateDirectory or
                   9583: lonnetPrivateKey
                   9584: <error> is a string that describes the reason that
                   9585: the key file could not be located.
                   9586: 
                   9587: =item (Red) CRITICAL  Can't get certificates <error>  
                   9588: 
                   9589: SSL key negotiation failed because we were not able to retrives our certificate
                   9590: or the CA's certificate in the call to lonssl::CertificateFile
                   9591: <error> is the textual reason this failed.  Usual reasons:
                   9592: 
                   9593: =over 2
1.490     droeschl 9594: 
1.409     foxr     9595: =item Apache config file for loncapa  incorrect:
1.490     droeschl 9596: 
1.409     foxr     9597: one of the variables 
                   9598: lonCertificateDirectory, lonnetCertificateAuthority, or lonnetCertificate
                   9599: undefined or incorrect
                   9600: 
                   9601: =item Permission error:
                   9602: 
                   9603: The directory pointed to by lonCertificateDirectory is not readable by lond
                   9604: 
                   9605: =item Permission error:
                   9606: 
                   9607: Files in the directory pointed to by lonCertificateDirectory are not readable by lond.
                   9608: 
                   9609: =item Installation error:                         
                   9610: 
                   9611: Either the certificate authority file or the certificate have not
                   9612: been installed in lonCertificateDirectory.
                   9613: 
                   9614: =item (Red) CRITICAL SSL Socket promotion failed:  <err> 
                   9615: 
                   9616: The promotion of the connection from plaintext to SSL failed
                   9617: <err> is the reason for the failure.  There are two
                   9618: system calls involved in the promotion (one of which failed), 
                   9619: a dup to produce
                   9620: a second fd on the raw socket over which the encrypted data
                   9621: will flow and IO::SOcket::SSL->new_from_fd which creates
                   9622: the SSL connection on the duped fd.
                   9623: 
                   9624: =item (Blue)   WARNING client did not respond to challenge 
                   9625: 
                   9626: This occurs on an insecure (non SSL) connection negotiation request.
                   9627: lond generates some number from the time, the PID and sends it to
                   9628: the client.  The client must respond by echoing this information back.
                   9629: If the client does not do so, that's a violation of the challenge
                   9630: protocols and the connection will be failed.
                   9631: 
                   9632: =item (Red) No manager table. Nobody can manage!!    
                   9633: 
                   9634: lond has the concept of privileged hosts that
                   9635: can perform remote management function such
                   9636: as update the hosts.tab.   The manager hosts
                   9637: are described in the 
                   9638: ~httpd/lonTabs/managers.tab file.
                   9639: this message is logged if this file is missing.
                   9640: 
                   9641: 
                   9642: =item (Green) Registering manager <dnsname> as <cluster_name> with <ipaddress>
                   9643: 
                   9644: Reports the successful parse and registration
                   9645: of a specific manager. 
                   9646: 
                   9647: =item Green existing host <clustername:dnsname>  
                   9648: 
                   9649: The manager host is already defined in the hosts.tab
                   9650: the information in that table, rather than the info in the
                   9651: manager table will be used to determine the manager's ip.
                   9652: 
                   9653: =item (Red) Unable to craete <filename>                 
                   9654: 
                   9655: lond has been asked to create new versions of an administrative
                   9656: file (by a manager).  When this is done, the new file is created
                   9657: in a temp file and then renamed into place so that there are always
                   9658: usable administrative files, even if the update fails.  This failure
                   9659: message means that the temp file could not be created.
                   9660: The update is abandoned, and the old file is available for use.
                   9661: 
                   9662: =item (Green) CopyFile from <oldname> to <newname> failed
                   9663: 
                   9664: In an update of administrative files, the copy of the existing file to a
                   9665: backup file failed.  The installation of the new file may still succeed,
                   9666: but there will not be a back up file to rever to (this should probably
                   9667: be yellow).
                   9668: 
                   9669: =item (Green) Pushfile: backed up <oldname> to <newname>
                   9670: 
                   9671: See above, the backup of the old administrative file succeeded.
                   9672: 
                   9673: =item (Red)  Pushfile: Unable to install <filename> <reason>
                   9674: 
                   9675: The new administrative file could not be installed.  In this case,
                   9676: the old administrative file is still in use.
                   9677: 
                   9678: =item (Green) Installed new < filename>.                      
                   9679: 
                   9680: The new administrative file was successfullly installed.                                               
                   9681: 
                   9682: =item (Red) Reinitializing lond pid=<pid>                    
                   9683: 
                   9684: The lonc child process <pid> will be sent a USR2 
                   9685: signal.
                   9686: 
                   9687: =item (Red) Reinitializing self                                    
                   9688: 
                   9689: We've been asked to re-read our administrative files,and
                   9690: are doing so.
                   9691: 
                   9692: =item (Yellow) error:Invalid process identifier <ident>  
                   9693: 
                   9694: A reinit command was received, but the target part of the 
                   9695: command was not valid.  It must be either
                   9696: 'lond' or 'lonc' but was <ident>
                   9697: 
                   9698: =item (Green) isValideditCommand checking: Command = <command> Key = <key> newline = <newline>
                   9699: 
                   9700: Checking to see if lond has been handed a valid edit
                   9701: command.  It is possible the edit command is not valid
                   9702: in that case there are no log messages to indicate that.
                   9703: 
                   9704: =item Result of password change for  <username> pwchange_success
                   9705: 
                   9706: The password for <username> was
                   9707: successfully changed.
                   9708: 
                   9709: =item Unable to open <user> passwd to change password
                   9710: 
                   9711: Could not rewrite the 
                   9712: internal password file for a user
                   9713: 
                   9714: =item Result of password change for <user> : <result>
1.490     droeschl 9715: 
1.409     foxr     9716: A unix password change for <user> was attempted 
                   9717: and the pipe returned <result>  
                   9718: 
                   9719: =item LWP GET: <message> for <fname> (<remoteurl>)
                   9720: 
                   9721: The lightweight process fetch for a resource failed
                   9722: with <message> the local filename that should
                   9723: have existed/been created was  <fname> the
                   9724: corresponding URI: <remoteurl>  This is emitted in several
                   9725: places.
                   9726: 
                   9727: =item Unable to move <transname> to <destname>     
                   9728: 
                   9729: From fetch_user_file_handler - the user file was replicated but could not
                   9730: be mv'd to its final location.
                   9731: 
                   9732: =item Looking for <domain> <username>              
                   9733: 
                   9734: From user_has_session_handler - This should be a Debug call instead
                   9735: it indicates lond is about to check whether the specified user has a 
                   9736: session active on the specified domain on the local host.
                   9737: 
                   9738: =item Client <ip> (<name>) hanging up: <input>     
                   9739: 
                   9740: lond has been asked to exit by its client.  The <ip> and <name> identify the
                   9741: client systemand <input> is the full exit command sent to the server.
                   9742: 
                   9743: =item Red CRITICAL: ABNORMAL EXIT. child <pid> for server <hostname> died through a crass with this error->[<message>].
1.490     droeschl 9744: 
1.409     foxr     9745: A lond child terminated.  NOte that this termination can also occur when the
                   9746: child receives the QUIT or DIE signals.  <pid> is the process id of the child,
                   9747: <hostname> the host lond is working for, and <message> the reason the child died
                   9748: to the best of our ability to get it (I would guess that any numeric value
                   9749: represents and errno value).  This is immediately followed by
                   9750: 
                   9751: =item  Famous last words: Catching exception - <log> 
                   9752: 
                   9753: Where log is some recent information about the state of the child.
                   9754: 
                   9755: =item Red CRITICAL: TIME OUT <pid>                     
                   9756: 
                   9757: Some timeout occured for server <pid>.  THis is normally a timeout on an LWP
                   9758: doing an HTTP::GET.
                   9759: 
                   9760: =item child <pid> died                              
                   9761: 
                   9762: The reaper caught a SIGCHILD for the lond child process <pid>
                   9763: This should be modified to also display the IP of the dying child
                   9764: $children{$pid}
                   9765: 
                   9766: =item Unknown child 0 died                           
                   9767: A child died but the wait for it returned a pid of zero which really should not
                   9768: ever happen. 
                   9769: 
                   9770: =item Child <which> - <pid> looks like we missed it's death 
                   9771: 
                   9772: When a sigchild is received, the reaper process checks all children to see if they are
                   9773: alive.  If children are dying quite quickly, the lack of signal queuing can mean
                   9774: that a signal hearalds the death of more than one child.  If so this message indicates
                   9775: which other one died. <which> is the ip of a dead child
                   9776: 
                   9777: =item Free socket: <shutdownretval>                
                   9778: 
                   9779: The HUNTSMAN sub was called due to a SIGINT in a child process.  The socket is being shutdown.
                   9780: for whatever reason, <shutdownretval> is printed but in fact shutdown() is not documented
                   9781: to return anything. This is followed by: 
                   9782: 
                   9783: =item Red CRITICAL: Shutting down                       
                   9784: 
                   9785: Just prior to exit.
                   9786: 
                   9787: =item Free socket: <shutdownretval>                 
                   9788: 
                   9789: The HUPSMAN sub was called due to a SIGHUP.  all children get killsed, and lond execs itself.
                   9790: This is followed by:
                   9791: 
                   9792: =item (Red) CRITICAL: Restarting                         
                   9793: 
                   9794: lond is about to exec itself to restart.
                   9795: 
                   9796: =item (Blue) Updating connections                        
                   9797: 
                   9798: (In response to a USR2).  All the children (except the one for localhost)
                   9799: are about to be killed, the hosts tab reread, and Apache reloaded via apachereload.
                   9800: 
                   9801: =item (Blue) UpdateHosts killing child <pid> for ip <ip>   
                   9802: 
                   9803: Due to USR2 as above.
                   9804: 
                   9805: =item (Green) keeping child for ip <ip> (pid = <pid>)    
                   9806: 
                   9807: In response to USR2 as above, the child indicated is not being restarted because
                   9808: it's assumed that we'll always need a child for the localhost.
                   9809: 
                   9810: 
                   9811: =item Going to check on the children                
                   9812: 
                   9813: Parent is about to check on the health of the child processes.
                   9814: Note that this is in response to a USR1 sent to the parent lond.
                   9815: there may be one or more of the next two messages:
                   9816: 
                   9817: =item <pid> is dead                                 
                   9818: 
                   9819: A child that we have in our child hash as alive has evidently died.
                   9820: 
                   9821: =item  Child <pid> did not respond                   
                   9822: 
                   9823: In the health check the child <pid> did not update/produce a pid_.txt
                   9824: file when sent it's USR1 signal.  That process is killed with a 9 signal, as it's
                   9825: assumed to be hung in some un-fixable way.
                   9826: 
                   9827: =item Finished checking children                   
1.490     droeschl 9828: 
1.409     foxr     9829: Master processs's USR1 processing is cojmplete.
                   9830: 
                   9831: =item (Red) CRITICAL: ------- Starting ------            
                   9832: 
                   9833: (There are more '-'s on either side).  Lond has forked itself off to 
                   9834: form a new session and is about to start actual initialization.
                   9835: 
                   9836: =item (Green) Attempting to start child (<client>)       
                   9837: 
                   9838: Started a new child process for <client>.  Client is IO::Socket object
                   9839: connected to the child.  This was as a result of a TCP/IP connection from a client.
                   9840: 
                   9841: =item Unable to determine who caller was, getpeername returned nothing
1.490     droeschl 9842: 
1.409     foxr     9843: In child process initialization.  either getpeername returned undef or
                   9844: a zero sized object was returned.  Processing continues, but in my opinion,
                   9845: this should be cause for the child to exit.
                   9846: 
                   9847: =item Unable to determine clientip                  
                   9848: 
                   9849: In child process initialization.  The peer address from getpeername was not defined.
                   9850: The client address is stored as "Unavailable" and processing continues.
                   9851: 
                   9852: =item (Yellow) INFO: Connection <ip> <name> connection type = <type>
1.490     droeschl 9853: 
1.409     foxr     9854: In child initialization.  A good connectionw as received from <ip>.
                   9855: 
                   9856: =over 2
                   9857: 
                   9858: =item <name> 
                   9859: 
                   9860: is the name of the client from hosts.tab.
                   9861: 
                   9862: =item <type> 
                   9863: 
                   9864: Is the connection type which is either 
                   9865: 
                   9866: =over 2
                   9867: 
                   9868: =item manager 
                   9869: 
                   9870: The connection is from a manager node, not in hosts.tab
                   9871: 
                   9872: =item client  
                   9873: 
                   9874: the connection is from a non-manager in the hosts.tab
                   9875: 
                   9876: =item both
                   9877: 
                   9878: The connection is from a manager in the hosts.tab.
                   9879: 
                   9880: =back
                   9881: 
                   9882: =back
                   9883: 
                   9884: =item (Blue) Certificates not installed -- trying insecure auth
                   9885: 
                   9886: One of the certificate file, key file or
                   9887: certificate authority file could not be found for a client attempting
                   9888: SSL connection intiation.  COnnection will be attemptied in in-secure mode.
                   9889: (this would be a system with an up to date lond that has not gotten a 
                   9890: certificate from us).
                   9891: 
                   9892: =item (Green)  Successful local authentication            
                   9893: 
                   9894: A local connection successfully negotiated the encryption key. 
                   9895: In this case the IDEA key is in a file (that is hopefully well protected).
                   9896: 
                   9897: =item (Green) Successful ssl authentication with <client>  
                   9898: 
                   9899: The client (<client> is the peer's name in hosts.tab), has successfully
                   9900: negotiated an SSL connection with this child process.
                   9901: 
                   9902: =item (Green) Successful insecure authentication with <client>
1.490     droeschl 9903: 
1.409     foxr     9904: 
                   9905: The client has successfully negotiated an  insecure connection withthe child process.
                   9906: 
                   9907: =item (Yellow) Attempted insecure connection disallowed    
                   9908: 
                   9909: The client attempted and failed to successfully negotiate a successful insecure
                   9910: connection.  This can happen either because the variable londAllowInsecure is false
                   9911: or undefined, or becuse the child did not successfully echo back the challenge
                   9912: string.
                   9913: 
                   9914: 
                   9915: =back
                   9916: 
1.441     raeburn  9917: =back
                   9918: 
1.409     foxr     9919: 
                   9920: =cut

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