Annotation of loncom/lond, revision 1.577

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

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