Annotation of loncom/lond, revision 1.582

1.1       albertel    1: #!/usr/bin/perl
                      2: # The LearningOnline Network
                      3: # lond "LON Daemon" Server (port "LOND" 5663)
1.60      www         4: #
1.582   ! raeburn     5: # $Id: lond,v 1.581 2024/06/22 14:29:36 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.582   ! raeburn    68: my $VERSION='$Revision: 1.581 $'; #' stupid emacs
1.121     albertel   69: my $remoteVERSION;
1.214     foxr       70: my $currenthostid="default";
1.115     albertel   71: my $currentdomainid;
1.134     albertel   72: 
                     73: my $client;
1.200     matthew    74: my $clientip;			# IP address of client.
                     75: my $clientname;			# LonCAPA name of client.
1.448     raeburn    76: my $clientversion;              # LonCAPA version running on client.
                     77: my $clienthomedom;              # LonCAPA domain of homeID for client. 
1.525     raeburn    78: my $clientintdom;               # LonCAPA "internet domain" for client.
1.532     raeburn    79: my $clientsamedom;              # LonCAPA domain same for this host 
                     80:                                 # and client.
1.525     raeburn    81: my $clientsameinst;             # LonCAPA "internet domain" same for 
                     82:                                 # this host and client.
1.556     raeburn    83: my $clientremoteok;             # Current domain permits hosting on client
                     84:                                 # (not set if host and client share "internet domain").
                     85:                                 # Values are 0 or 1; 1 if allowed.
                     86: my %clientprohibited;           # Commands from client prohibited for domain's
                     87:                                 # users.
                     88: 
1.134     albertel   89: my $server;
1.200     matthew    90: 
                     91: my $keymode;
1.198     foxr       92: 
1.207     foxr       93: my $cipher;			# Cipher key negotiated with client
                     94: my $tmpsnum = 0;		# Id of tmpputs.
                     95: 
1.178     foxr       96: # 
                     97: #   Connection type is:
                     98: #      client                   - All client actions are allowed
                     99: #      manager                  - only management functions allowed.
                    100: #      both                     - Both management and client actions are allowed
                    101: #
1.161     foxr      102: 
1.178     foxr      103: my $ConnectionType;
1.161     foxr      104: 
1.178     foxr      105: my %managers;			# Ip -> manager names
1.161     foxr      106: 
1.178     foxr      107: my %perlvar;			# Will have the apache conf defined perl vars.
1.134     albertel  108: 
1.532     raeburn   109: my %secureconf;                 # Will have requirements for security 
                    110:                                 # of lond connections
                    111: 
1.545     raeburn   112: my %crlchecked;                 # Will contain clients for which the client's SSL
                    113:                                 # has been checked against the cluster's Certificate
                    114:                                 # Revocation List.
                    115: 
1.480     raeburn   116: my $dist;
                    117: 
1.178     foxr      118: #
1.207     foxr      119: #   The hash below is used for command dispatching, and is therefore keyed on the request keyword.
                    120: #    Each element of the hash contains a reference to an array that contains:
                    121: #          A reference to a sub that executes the request corresponding to the keyword.
                    122: #          A flag that is true if the request must be encoded to be acceptable.
                    123: #          A mask with bits as follows:
                    124: #                      CLIENT_OK    - Set when the function is allowed by ordinary clients
                    125: #                      MANAGER_OK   - Set when the function is allowed to manager clients.
                    126: #
                    127: my $CLIENT_OK  = 1;
                    128: my $MANAGER_OK = 2;
                    129: my %Dispatcher;
                    130: 
                    131: 
                    132: #
1.178     foxr      133: #  The array below are password error strings."
                    134: #
                    135: my $lastpwderror    = 13;		# Largest error number from lcpasswd.
                    136: my @passwderrors = ("ok",
1.287     foxr      137: 		   "pwchange_failure - lcpasswd must be run as user 'www'",
                    138: 		   "pwchange_failure - lcpasswd got incorrect number of arguments",
                    139: 		   "pwchange_failure - lcpasswd did not get the right nubmer of input text lines",
                    140: 		   "pwchange_failure - lcpasswd too many simultaneous pwd changes in progress",
                    141: 		   "pwchange_failure - lcpasswd User does not exist.",
                    142: 		   "pwchange_failure - lcpasswd Incorrect current passwd",
                    143: 		   "pwchange_failure - lcpasswd Unable to su to root.",
                    144: 		   "pwchange_failure - lcpasswd Cannot set new passwd.",
                    145: 		   "pwchange_failure - lcpasswd Username has invalid characters",
                    146: 		   "pwchange_failure - lcpasswd Invalid characters in password",
                    147: 		   "pwchange_failure - lcpasswd User already exists", 
                    148:                    "pwchange_failure - lcpasswd Something went wrong with user addition.",
                    149: 		   "pwchange_failure - lcpasswd Password mismatch",
                    150: 		   "pwchange_failure - lcpasswd Error filename is invalid");
1.97      foxr      151: 
                    152: 
1.412     foxr      153: # This array are the errors from lcinstallfile:
                    154: 
                    155: my @installerrors = ("ok",
                    156: 		     "Initial user id of client not that of www",
                    157: 		     "Usage error, not enough command line arguments",
1.500     bisitz    158: 		     "Source filename does not exist",
                    159: 		     "Destination filename does not exist",
1.412     foxr      160: 		     "Some file operation failed",
                    161: 		     "Invalid table filename."
                    162: 		     );
1.207     foxr      163: 
                    164: #
1.525     raeburn   165: # The %trust hash classifies commands according to type of trust 
                    166: # required for execution of the command.
                    167: #
                    168: # When clients from a different institution request execution of a
                    169: # particular command, the trust settings for that institution set
                    170: # for this domain (or default domain for a multi-domain server) will
                    171: # be checked to see if running the command is allowed.
                    172: #
                    173: # Trust types which depend on the "Trust" domain configuration
                    174: # for the machine's default domain are:
                    175: #
                    176: # content   ("Access to this domain's content by others")
                    177: # shared    ("Access to other domain's content by this domain")
                    178: # enroll    ("Enrollment in this domain's courses by others")
                    179: # coaurem   ("Co-author roles for this domain's users elsewhere")
1.552     raeburn   180: # othcoau   ("Co-author roles in this domain for others")
1.525     raeburn   181: # domroles  ("Domain roles in this domain assignable to others")
                    182: # catalog   ("Course Catalog for this domain displayed elsewhere")
                    183: # reqcrs    ("Requests for creation of courses in this domain by others")
                    184: # msg       ("Users in other domains can send messages to this domain")
                    185: # 
                    186: # Trust type which depends on the User Session Hosting (remote) 
                    187: # domain configuration for machine's default domain is: "remote".
                    188: #
                    189: # Trust types which depend on contents of manager.tab in 
                    190: # /home/httpd/lonTabs is: "manageronly".
                    191: # 
                    192: # Trust type which requires client to share the same LON-CAPA
                    193: # "internet domain" (i.e., same institution as this server) is:
                    194: # "institutiononly".
                    195: #
                    196: 
                    197: my %trust = (
                    198:                auth => {remote => 1},
                    199:                autocreatepassword => {remote => 1},
                    200:                autocrsreqchecks => {remote => 1, reqcrs => 1},
                    201:                autocrsrequpdate => {remote => 1},
                    202:                autocrsreqvalidation => {remote => 1},
                    203:                autogetsections => {remote => 1},
                    204:                autoinstcodedefaults => {remote => 1, catalog => 1},
                    205:                autoinstcodeformat => {remote => 1, catalog => 1},
                    206:                autonewcourse => {remote => 1, reqcrs => 1},
                    207:                autophotocheck => {remote => 1, enroll => 1},
                    208:                autophotochoice => {remote => 1},
                    209:                autophotopermission => {remote => 1, enroll => 1},
                    210:                autopossibleinstcodes => {remote => 1, reqcrs => 1},
                    211:                autoretrieve => {remote => 1, enroll => 1, catalog => 1},
                    212:                autorun => {remote => 1, enroll => 1, reqcrs => 1},
                    213:                autovalidateclass_sec => {catalog => 1},
                    214:                autovalidatecourse => {remote => 1, enroll => 1},
                    215:                autovalidateinstcode => {domroles => 1, remote => 1, enroll => 1},
1.566     raeburn   216:                autovalidateinstcrosslist => {remote => 1, enroll => 1},
1.567     raeburn   217:                autoinstsecreformat => {remote => 1, enroll => 1},
1.525     raeburn   218:                changeuserauth => {remote => 1, domroles => 1},
                    219:                chatretr => {remote => 1, enroll => 1},
                    220:                chatsend => {remote => 1, enroll => 1},
                    221:                courseiddump => {remote => 1, domroles => 1, enroll => 1},
                    222:                courseidput => {remote => 1, domroles => 1, enroll => 1},
                    223:                courseidputhash => {remote => 1, domroles => 1, enroll => 1},
                    224:                courselastaccess => {remote => 1, domroles => 1, enroll => 1},
1.561     raeburn   225:                coursesessions => {institutiononly => 1},
1.525     raeburn   226:                currentauth => {remote => 1, domroles => 1, enroll => 1},
                    227:                currentdump => {remote => 1, enroll => 1},
                    228:                currentversion => {remote=> 1, content => 1},
                    229:                dcmaildump => {remote => 1, domroles => 1},
                    230:                dcmailput => {remote => 1, domroles => 1},
                    231:                del => {remote => 1, domroles => 1, enroll => 1, content => 1},
1.551     raeburn   232:                delbalcookie => {institutiononly => 1},
1.560     raeburn   233:                delusersession => {institutiononly => 1},
1.525     raeburn   234:                deldom => {remote => 1, domroles => 1}, # not currently used
                    235:                devalidatecache => {institutiononly => 1},
                    236:                domroleput => {remote => 1, enroll => 1},
                    237:                domrolesdump => {remote => 1, catalog => 1},
                    238:                du => {remote => 1, enroll => 1},
                    239:                du2 => {remote => 1, enroll => 1},
                    240:                dump => {remote => 1, enroll => 1, domroles => 1},
                    241:                edit => {institutiononly => 1},  #not used currently
1.568     raeburn   242:                edump => {remote => 1, enroll => 1, domroles => 1},
1.525     raeburn   243:                eget => {remote => 1, domroles => 1, enroll => 1}, #not used currently
1.536     raeburn   244:                egetdom => {remote => 1, domroles => 1, enroll => 1, },
1.553     raeburn   245:                ekey => {anywhere => 1},
1.525     raeburn   246:                exit => {anywhere => 1},
                    247:                fetchuserfile => {remote => 1, enroll => 1},
                    248:                get => {remote => 1, domroles => 1, enroll => 1},
                    249:                getdom => {anywhere => 1},
                    250:                home => {anywhere => 1},
                    251:                iddel => {remote => 1, enroll => 1},
                    252:                idget => {remote => 1, enroll => 1},
                    253:                idput => {remote => 1, domroles => 1, enroll => 1},
                    254:                inc => {remote => 1, enroll => 1},
                    255:                init => {anywhere => 1},
                    256:                inst_usertypes => {remote => 1, domroles => 1, enroll => 1},
                    257:                instemailrules => {remote => 1, domroles => 1},
                    258:                instidrulecheck => {remote => 1, domroles => 1,},
                    259:                instidrules => {remote => 1, domroles => 1,},
                    260:                instrulecheck => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1},
                    261:                instselfcreatecheck => {institutiononly => 1},
1.575     raeburn   262:                instunamemapcheck => {remote => 1,},  
1.525     raeburn   263:                instuserrules => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1},
                    264:                keys => {remote => 1,},
                    265:                load => {anywhere => 1},
                    266:                log => {anywhere => 1},
                    267:                ls => {remote => 1, enroll => 1, content => 1,},
                    268:                ls2 => {remote => 1, enroll => 1, content => 1,},
                    269:                ls3 => {remote => 1, enroll => 1, content => 1,},
1.572     raeburn   270:                lti => {institutiononly => 1},
1.525     raeburn   271:                makeuser => {remote => 1, enroll => 1, domroles => 1,},
                    272:                mkdiruserfile => {remote => 1, enroll => 1,},
                    273:                newput => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1,},
                    274:                passwd => {remote => 1},
                    275:                ping => {anywhere => 1},
                    276:                pong => {anywhere => 1},
                    277:                pushfile => {manageronly => 1},
                    278:                put => {remote => 1, enroll => 1, domroles => 1, msg => 1, content => 1, shared => 1},
                    279:                putdom => {remote => 1, domroles => 1,},
                    280:                putstore => {remote => 1, enroll => 1},
                    281:                queryreply => {anywhere => 1},
                    282:                querysend => {anywhere => 1},
1.535     raeburn   283:                querysend_activitylog => {remote => 1},
                    284:                querysend_allusers => {remote => 1, domroles => 1},
                    285:                querysend_courselog => {remote => 1},
                    286:                querysend_fetchenrollment => {remote => 1},
                    287:                querysend_getinstuser => {remote => 1},
                    288:                querysend_getmultinstusers => {remote => 1},
                    289:                querysend_instdirsearch => {remote => 1, domroles => 1, coaurem => 1},
                    290:                querysend_institutionalphotos => {remote => 1},
                    291:                querysend_portfolio_metadata => {remote => 1, content => 1},
                    292:                querysend_userlog => {remote => 1, domroles => 1},
                    293:                querysend_usersearch => {remote => 1, enroll => 1, coaurem => 1},
1.525     raeburn   294:                quit => {anywhere => 1},
                    295:                readlonnetglobal => {institutiononly => 1},
                    296:                reinit => {manageronly => 1}, #not used currently
                    297:                removeuserfile => {remote => 1, enroll => 1},
                    298:                renameuserfile => {remote => 1,},
                    299:                restore => {remote => 1, enroll => 1, reqcrs => 1,},
                    300:                rolesdel => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
                    301:                rolesput => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
1.527     raeburn   302:                servercerts => {institutiononly => 1},
1.528     raeburn   303:                serverdistarch => {anywhere => 1},
1.525     raeburn   304:                serverhomeID => {anywhere => 1},
                    305:                serverloncaparev => {anywhere => 1},
                    306:                servertimezone => {remote => 1, enroll => 1},
                    307:                setannounce => {remote => 1, domroles => 1},
                    308:                sethost => {anywhere => 1},
1.577     raeburn   309:                signlti => {remote => 1},
1.525     raeburn   310:                store => {remote => 1, enroll => 1, reqcrs => 1,},
                    311:                studentphoto => {remote => 1, enroll => 1},
                    312:                sub => {content => 1,},
1.552     raeburn   313:                tmpdel => {institutiononly => 1},
                    314:                tmpget => {institutiononly => 1},
                    315:                tmpput => {remote => 1, othcoau => 1},
1.525     raeburn   316:                tokenauthuserfile => {anywhere => 1},
1.575     raeburn   317:                unamemaprules => {remote => 1,},
1.525     raeburn   318:                unsub => {content => 1,},
                    319:                update => {shared => 1},
1.564     raeburn   320:                updatebalcookie => {institutiononly => 1},
1.525     raeburn   321:                updateclickers => {remote => 1},
                    322:                userhassession => {anywhere => 1},
                    323:                userload => {anywhere => 1},
                    324:                version => {anywhere => 1}, #not used
                    325:             );
                    326: 
                    327: #
1.207     foxr      328: #   Statistics that are maintained and dislayed in the status line.
                    329: #
1.212     foxr      330: my $Transactions = 0;		# Number of attempted transactions.
                    331: my $Failures     = 0;		# Number of transcations failed.
1.207     foxr      332: 
                    333: #   ResetStatistics: 
                    334: #      Resets the statistics counters:
                    335: #
                    336: sub ResetStatistics {
                    337:     $Transactions = 0;
                    338:     $Failures     = 0;
                    339: }
                    340: 
1.200     matthew   341: #------------------------------------------------------------------------
                    342: #
                    343: #   LocalConnection
                    344: #     Completes the formation of a locally authenticated connection.
                    345: #     This function will ensure that the 'remote' client is really the
                    346: #     local host.  If not, the connection is closed, and the function fails.
                    347: #     If so, initcmd is parsed for the name of a file containing the
                    348: #     IDEA session key.  The fie is opened, read, deleted and the session
                    349: #     key returned to the caller.
                    350: #
                    351: # Parameters:
                    352: #   $Socket      - Socket open on client.
                    353: #   $initcmd     - The full text of the init command.
                    354: #
                    355: # Returns:
                    356: #     IDEA session key on success.
                    357: #     undef on failure.
                    358: #
                    359: sub LocalConnection {
                    360:     my ($Socket, $initcmd) = @_;
1.373     albertel  361:     Debug("Attempting local connection: $initcmd client: $clientip");
1.277     albertel  362:     if($clientip ne "127.0.0.1") {
1.200     matthew   363: 	&logthis('<font color="red"> LocalConnection rejecting non local: '
1.373     albertel  364: 		 ."$clientip ne 127.0.0.1 </font>");
1.200     matthew   365: 	close $Socket;
                    366: 	return undef;
1.224     foxr      367:     }  else {
1.200     matthew   368: 	chomp($initcmd);	# Get rid of \n in filename.
                    369: 	my ($init, $type, $name) = split(/:/, $initcmd);
                    370: 	Debug(" Init command: $init $type $name ");
                    371: 
                    372: 	# Require that $init = init, and $type = local:  Otherwise
                    373: 	# the caller is insane:
                    374: 
                    375: 	if(($init ne "init") && ($type ne "local")) {
                    376: 	    &logthis('<font color = "red"> LocalConnection: caller is insane! '
                    377: 		     ."init = $init, and type = $type </font>");
                    378: 	    close($Socket);;
                    379: 	    return undef;
                    380: 		
                    381: 	}
                    382: 	#  Now get the key filename:
                    383: 
                    384: 	my $IDEAKey = lonlocal::ReadKeyFile($name);
                    385: 	return $IDEAKey;
                    386:     }
                    387: }
                    388: #------------------------------------------------------------------------------
                    389: #
                    390: #  SSLConnection
                    391: #   Completes the formation of an ssh authenticated connection. The
                    392: #   socket is promoted to an ssl socket.  If this promotion and the associated
                    393: #   certificate exchange are successful, the IDEA key is generated and sent
                    394: #   to the remote peer via the SSL tunnel. The IDEA key is also returned to
                    395: #   the caller after the SSL tunnel is torn down.
                    396: #
                    397: # Parameters:
                    398: #   Name              Type             Purpose
                    399: #   $Socket          IO::Socket::INET  Plaintext socket.
                    400: #
                    401: # Returns:
                    402: #    IDEA key on success.
                    403: #    undef on failure.
                    404: #
                    405: sub SSLConnection {
                    406:     my $Socket   = shift;
                    407: 
                    408:     Debug("SSLConnection: ");
                    409:     my $KeyFile         = lonssl::KeyFile();
                    410:     if(!$KeyFile) {
                    411: 	my $err = lonssl::LastError();
                    412: 	&logthis("<font color=\"red\"> CRITICAL"
                    413: 		 ."Can't get key file $err </font>");
                    414: 	return undef;
                    415:     }
                    416:     my ($CACertificate,
                    417: 	$Certificate) = lonssl::CertificateFile();
                    418: 
                    419: 
                    420:     # If any of the key, certificate or certificate authority 
                    421:     # certificate filenames are not defined, this can't work.
                    422: 
                    423:     if((!$Certificate) || (!$CACertificate)) {
                    424: 	my $err = lonssl::LastError();
                    425: 	&logthis("<font color=\"red\"> CRITICAL"
                    426: 		 ."Can't get certificates: $err </font>");
                    427: 
                    428: 	return undef;
                    429:     }
                    430:     Debug("Key: $KeyFile CA: $CACertificate Cert: $Certificate");
                    431: 
                    432:     # Indicate to our peer that we can procede with
                    433:     # a transition to ssl authentication:
                    434: 
                    435:     print $Socket "ok:ssl\n";
                    436: 
                    437:     Debug("Approving promotion -> ssl");
                    438:     #  And do so:
                    439: 
1.545     raeburn   440:     my $CRLFile;
                    441:     unless ($crlchecked{$clientname}) {
                    442:         $CRLFile = lonssl::CRLFile();
                    443:         $crlchecked{$clientname} = 1;
                    444:     }
                    445: 
1.200     matthew   446:     my $SSLSocket = lonssl::PromoteServerSocket($Socket,
                    447: 						$CACertificate,
                    448: 						$Certificate,
1.544     raeburn   449: 						$KeyFile,
1.545     raeburn   450: 						$clientname,
1.546     raeburn   451:                                                 $CRLFile,
                    452:                                                 $clientversion);
1.200     matthew   453:     if(! ($SSLSocket) ) {	# SSL socket promotion failed.
                    454: 	my $err = lonssl::LastError();
                    455: 	&logthis("<font color=\"red\"> CRITICAL "
                    456: 		 ."SSL Socket promotion failed: $err </font>");
                    457: 	return undef;
                    458:     }
                    459:     Debug("SSL Promotion successful");
                    460: 
                    461:     # 
                    462:     #  The only thing we'll use the socket for is to send the IDEA key
                    463:     #  to the peer:
                    464: 
                    465:     my $Key = lonlocal::CreateCipherKey();
                    466:     print $SSLSocket "$Key\n";
                    467: 
                    468:     lonssl::Close($SSLSocket); 
                    469: 
                    470:     Debug("Key exchange complete: $Key");
                    471: 
                    472:     return $Key;
                    473: }
                    474: #
                    475: #     InsecureConnection: 
                    476: #        If insecure connections are allowd,
                    477: #        exchange a challenge with the client to 'validate' the
                    478: #        client (not really, but that's the protocol):
                    479: #        We produce a challenge string that's sent to the client.
                    480: #        The client must then echo the challenge verbatim to us.
                    481: #
                    482: #  Parameter:
                    483: #      Socket      - Socket open on the client.
                    484: #  Returns:
                    485: #      1           - success.
                    486: #      0           - failure (e.g.mismatch or insecure not allowed).
                    487: #
                    488: sub InsecureConnection {
                    489:     my $Socket  =  shift;
                    490: 
                    491:     #   Don't even start if insecure connections are not allowed.
1.532     raeburn   492:     #   return 0 if Insecure connections not allowed.
                    493:     #
                    494:     if (ref($secureconf{'connfrom'}) eq 'HASH') {
                    495:         if ($clientsamedom) {
                    496:             if ($secureconf{'connfrom'}{'dom'} eq 'req') {
                    497:                 return 0;
                    498:             } 
                    499:         } elsif ($clientsameinst) {
                    500:             if ($secureconf{'connfrom'}{'intdom'} eq 'req') {
                    501:                 return 0;
                    502:             }
                    503:         } else {
                    504:             if ($secureconf{'connfrom'}{'other'} eq 'req') {
                    505:                 return 0;
                    506:             }
                    507:         }
                    508:     } elsif (!$perlvar{londAllowInsecure}) {
1.200     matthew   509: 	return 0;
                    510:     }
                    511: 
                    512:     #   Fabricate a challenge string and send it..
                    513: 
                    514:     my $challenge = "$$".time;	# pid + time.
                    515:     print $Socket "$challenge\n";
                    516:     &status("Waiting for challenge reply");
                    517: 
                    518:     my $answer = <$Socket>;
                    519:     $answer    =~s/\W//g;
                    520:     if($challenge eq $answer) {
                    521: 	return 1;
1.224     foxr      522:     } else {
1.200     matthew   523: 	logthis("<font color='blue'>WARNING client did not respond to challenge</font>");
                    524: 	&status("No challenge reqply");
                    525: 	return 0;
                    526:     }
                    527:     
                    528: 
                    529: }
1.251     foxr      530: #
                    531: #   Safely execute a command (as long as it's not a shel command and doesn
                    532: #   not require/rely on shell escapes.   The function operates by doing a
                    533: #   a pipe based fork and capturing stdout and stderr  from the pipe.
                    534: #
                    535: # Formal Parameters:
                    536: #     $line                    - A line of text to be executed as a command.
                    537: # Returns:
                    538: #     The output from that command.  If the output is multiline the caller
                    539: #     must know how to split up the output.
                    540: #
                    541: #
                    542: sub execute_command {
                    543:     my ($line)    = @_;
                    544:     my @words     = split(/\s/, $line);	# Bust the command up into words.
                    545:     my $output    = "";
                    546: 
                    547:     my $pid = open(CHILD, "-|");
                    548:     
                    549:     if($pid) {			# Parent process
                    550: 	Debug("In parent process for execute_command");
                    551: 	my @data = <CHILD>;	# Read the child's outupt...
                    552: 	close CHILD;
                    553: 	foreach my $output_line (@data) {
                    554: 	    Debug("Adding $output_line");
                    555: 	    $output .= $output_line; # Presumably has a \n on it.
                    556: 	}
                    557: 
                    558:     } else {			# Child process
                    559: 	close (STDERR);
                    560: 	open  (STDERR, ">&STDOUT");# Combine stderr, and stdout...
                    561: 	exec(@words);		# won't return.
                    562:     }
                    563:     return $output;
                    564: }
                    565: 
1.200     matthew   566: 
1.140     foxr      567: #   GetCertificate: Given a transaction that requires a certificate,
                    568: #   this function will extract the certificate from the transaction
                    569: #   request.  Note that at this point, the only concept of a certificate
                    570: #   is the hostname to which we are connected.
                    571: #
                    572: #   Parameter:
                    573: #      request   - The request sent by our client (this parameterization may
                    574: #                  need to change when we really use a certificate granting
                    575: #                  authority.
                    576: #
                    577: sub GetCertificate {
                    578:     my $request = shift;
                    579: 
                    580:     return $clientip;
                    581: }
1.161     foxr      582: 
1.178     foxr      583: #
                    584: #   Return true if client is a manager.
                    585: #
                    586: sub isManager {
                    587:     return (($ConnectionType eq "manager") || ($ConnectionType eq "both"));
                    588: }
                    589: #
                    590: #   Return tru if client can do client functions
                    591: #
                    592: sub isClient {
                    593:     return (($ConnectionType eq "client") || ($ConnectionType eq "both"));
                    594: }
1.161     foxr      595: 
                    596: 
1.156     foxr      597: #
                    598: #   ReadManagerTable: Reads in the current manager table. For now this is
                    599: #                     done on each manager authentication because:
                    600: #                     - These authentications are not frequent
                    601: #                     - This allows dynamic changes to the manager table
                    602: #                       without the need to signal to the lond.
                    603: #
                    604: sub ReadManagerTable {
                    605: 
1.412     foxr      606:     &Debug("Reading manager table");
1.156     foxr      607:     #   Clean out the old table first..
                    608: 
1.166     foxr      609:    foreach my $key (keys %managers) {
                    610:       delete $managers{$key};
                    611:    }
                    612: 
                    613:    my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
                    614:    if (!open (MANAGERS, $tablename)) {
1.473     raeburn   615:        my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
                    616:        if (&Apache::lonnet::is_LC_dns($hostname)) {
1.472     raeburn   617:            &logthis('<font color="red">No manager table.  Nobody can manage!!</font>');
                    618:        }
                    619:        return;
1.166     foxr      620:    }
                    621:    while(my $host = <MANAGERS>) {
                    622:       chomp($host);
                    623:       if ($host =~ "^#") {                  # Comment line.
                    624:          next;
                    625:       }
1.368     albertel  626:       if (!defined &Apache::lonnet::get_host_ip($host)) { # This is a non cluster member
1.161     foxr      627: 	    #  The entry is of the form:
                    628: 	    #    cluname:hostname
                    629: 	    #  cluname - A 'cluster hostname' is needed in order to negotiate
                    630: 	    #            the host key.
                    631: 	    #  hostname- The dns name of the host.
                    632: 	    #
1.166     foxr      633:           my($cluname, $dnsname) = split(/:/, $host);
                    634:           
                    635:           my $ip = gethostbyname($dnsname);
                    636:           if(defined($ip)) {                 # bad names don't deserve entry.
                    637:             my $hostip = inet_ntoa($ip);
                    638:             $managers{$hostip} = $cluname;
                    639:             logthis('<font color="green"> registering manager '.
                    640:                     "$dnsname as $cluname with $hostip </font>\n");
                    641:          }
                    642:       } else {
                    643:          logthis('<font color="green"> existing host'." $host</font>\n");
1.472     raeburn   644:          $managers{&Apache::lonnet::get_host_ip($host)} = $host;  # Use info from cluster tab if cluster memeber
1.166     foxr      645:       }
                    646:    }
1.156     foxr      647: }
1.140     foxr      648: 
                    649: #
                    650: #  ValidManager: Determines if a given certificate represents a valid manager.
                    651: #                in this primitive implementation, the 'certificate' is
                    652: #                just the connecting loncapa client name.  This is checked
                    653: #                against a valid client list in the configuration.
                    654: #
                    655: #                  
                    656: sub ValidManager {
                    657:     my $certificate = shift; 
                    658: 
1.163     foxr      659:     return isManager;
1.140     foxr      660: }
                    661: #
1.143     foxr      662: #  CopyFile:  Called as part of the process of installing a 
                    663: #             new configuration file.  This function copies an existing
                    664: #             file to a backup file.
                    665: # Parameters:
                    666: #     oldfile  - Name of the file to backup.
                    667: #     newfile  - Name of the backup file.
                    668: # Return:
                    669: #     0   - Failure (errno has failure reason).
                    670: #     1   - Success.
                    671: #
                    672: sub CopyFile {
1.192     foxr      673: 
                    674:     my ($oldfile, $newfile) = @_;
1.143     foxr      675: 
1.281     matthew   676:     if (! copy($oldfile,$newfile)) {
                    677:         return 0;
1.143     foxr      678:     }
1.281     matthew   679:     chmod(0660, $newfile);
                    680:     return 1;
1.143     foxr      681: }
1.157     foxr      682: #
                    683: #  Host files are passed out with externally visible host IPs.
                    684: #  If, for example, we are behind a fire-wall or NAT host, our 
                    685: #  internally visible IP may be different than the externally
                    686: #  visible IP.  Therefore, we always adjust the contents of the
                    687: #  host file so that the entry for ME is the IP that we believe
                    688: #  we have.  At present, this is defined as the entry that
                    689: #  DNS has for us.  If by some chance we are not able to get a
                    690: #  DNS translation for us, then we assume that the host.tab file
                    691: #  is correct.  
                    692: #    BUGBUGBUG - in the future, we really should see if we can
                    693: #       easily query the interface(s) instead.
                    694: # Parameter(s):
                    695: #     contents    - The contents of the host.tab to check.
                    696: # Returns:
                    697: #     newcontents - The adjusted contents.
                    698: #
                    699: #
                    700: sub AdjustHostContents {
                    701:     my $contents  = shift;
                    702:     my $adjusted;
                    703:     my $me        = $perlvar{'lonHostID'};
                    704: 
1.354     albertel  705:     foreach my $line (split(/\n/,$contents)) {
1.472     raeburn   706: 	if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/) ||
                    707:              ($line =~ /^\s*\^/))) {
1.157     foxr      708: 	    chomp($line);
                    709: 	    my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
                    710: 	    if ($id eq $me) {
1.354     albertel  711: 		my $ip = gethostbyname($name);
                    712: 		my $ipnew = inet_ntoa($ip);
                    713: 		$ip = $ipnew;
1.157     foxr      714: 		#  Reconstruct the host line and append to adjusted:
                    715: 		
1.354     albertel  716: 		my $newline = "$id:$domain:$role:$name:$ip";
                    717: 		if($maxcon ne "") { # Not all hosts have loncnew tuning params
                    718: 		    $newline .= ":$maxcon:$idleto:$mincon";
                    719: 		}
                    720: 		$adjusted .= $newline."\n";
1.157     foxr      721: 		
1.354     albertel  722: 	    } else {		# Not me, pass unmodified.
                    723: 		$adjusted .= $line."\n";
                    724: 	    }
1.157     foxr      725: 	} else {                  # Blank or comment never re-written.
                    726: 	    $adjusted .= $line."\n";	# Pass blanks and comments as is.
                    727: 	}
1.354     albertel  728:     }
                    729:     return $adjusted;
1.157     foxr      730: }
1.143     foxr      731: #
                    732: #   InstallFile: Called to install an administrative file:
1.412     foxr      733: #       - The file is created int a temp directory called <name>.tmp
                    734: #       - lcinstall file is called to install the file.
                    735: #         since the web app has no direct write access to the table directory
1.143     foxr      736: #
                    737: #  Parameters:
                    738: #       Name of the file
                    739: #       File Contents.
                    740: #  Return:
                    741: #      nonzero - success.
                    742: #      0       - failure and $! has an errno.
1.412     foxr      743: # Assumptions:
                    744: #    File installtion is a relatively infrequent
1.143     foxr      745: #
                    746: sub InstallFile {
1.192     foxr      747: 
                    748:     my ($Filename, $Contents) = @_;
1.412     foxr      749: #     my $TempFile = $Filename.".tmp";
                    750:     my $exedir = $perlvar{'lonDaemons'};
                    751:     my $tmpdir = $exedir.'/tmp/';
                    752:     my $TempFile = $tmpdir."TempTableFile.tmp";
1.143     foxr      753: 
                    754:     #  Open the file for write:
                    755: 
                    756:     my $fh = IO::File->new("> $TempFile"); # Write to temp.
                    757:     if(!(defined $fh)) {
                    758: 	&logthis('<font color="red"> Unable to create '.$TempFile."</font>");
                    759: 	return 0;
                    760:     }
                    761:     #  write the contents of the file:
                    762: 
                    763:     print $fh ($Contents); 
                    764:     $fh->close;			# In case we ever have a filesystem w. locking
                    765: 
1.412     foxr      766:     chmod(0664, $TempFile);	# Everyone can write it.
                    767: 
                    768:     # Use lcinstall file to put the file in the table directory...
                    769: 
                    770:     &Debug("Opening pipe to $exedir/lcinstallfile $TempFile $Filename");
                    771:     my $pf = IO::File->new("| $exedir/lcinstallfile   $TempFile $Filename > $exedir/logs/lcinstallfile.log");
                    772:     close $pf;
                    773:     my $err = $?;
                    774:     &Debug("Status is $err");
                    775:     if ($err != 0) {
                    776: 	my $msg = $err;
                    777: 	if ($err < @installerrors) {
                    778: 	    $msg = $installerrors[$err];
                    779: 	}
                    780: 	&logthis("Install failed for table file $Filename : $msg");
                    781: 	return 0;
                    782:     }
                    783: 
                    784:     # Remove the temp file:
1.143     foxr      785: 
1.412     foxr      786:     unlink($TempFile);
1.143     foxr      787: 
                    788:     return 1;
                    789: }
1.200     matthew   790: 
                    791: 
1.169     foxr      792: #
                    793: #   ConfigFileFromSelector: converts a configuration file selector
1.411     foxr      794: #                 into a configuration file pathname.
1.472     raeburn   795: #                 Supports the following file selectors: 
                    796: #                 hosts, domain, dns_hosts, dns_domain  
1.411     foxr      797: #
1.169     foxr      798: #
                    799: #  Parameters:
                    800: #      selector  - Configuration file selector.
                    801: #  Returns:
                    802: #      Full path to the file or undef if the selector is invalid.
                    803: #
                    804: sub ConfigFileFromSelector {
                    805:     my $selector   = shift;
                    806:     my $tablefile;
                    807: 
1.549     raeburn   808:     if ($selector eq 'loncapaCAcrl') {
                    809:         my $tabledir = $perlvar{'lonCertificateDirectory'};
                    810:         if (-d $tabledir) {
                    811:             $tablefile =  $tabledir.'/'.$selector.'.pem';
                    812:         }
                    813:     } else {
                    814:         my $tabledir = $perlvar{'lonTabDir'}.'/';
                    815:         if (($selector eq "hosts") || ($selector eq "domain") || 
                    816:             ($selector eq "dns_hosts") || ($selector eq "dns_domain")) {
                    817: 	    $tablefile =  $tabledir.$selector.'.tab';
                    818:         }
1.169     foxr      819:     }
                    820:     return $tablefile;
                    821: }
1.143     foxr      822: #
1.141     foxr      823: #   PushFile:  Called to do an administrative push of a file.
                    824: #              - Ensure the file being pushed is one we support.
                    825: #              - Backup the old file to <filename.saved>
                    826: #              - Separate the contents of the new file out from the
                    827: #                rest of the request.
                    828: #              - Write the new file.
                    829: #  Parameter:
                    830: #     Request - The entire user request.  This consists of a : separated
                    831: #               string pushfile:tablename:contents.
                    832: #     NOTE:  The contents may have :'s in it as well making things a bit
                    833: #            more interesting... but not much.
                    834: #  Returns:
                    835: #     String to send to client ("ok" or "refused" if bad file).
                    836: #
                    837: sub PushFile {
1.510     raeburn   838:     my $request = shift;
1.141     foxr      839:     my ($command, $filename, $contents) = split(":", $request, 3);
1.412     foxr      840:     &Debug("PushFile");
1.141     foxr      841:     
1.549     raeburn   842:     #  At this point in time, pushes for only the following tables and
                    843:     #  CRL file are supported:
1.141     foxr      844:     #   hosts.tab  ($filename eq host).
                    845:     #   domain.tab ($filename eq domain).
1.472     raeburn   846:     #   dns_hosts.tab ($filename eq dns_host).
1.554     raeburn   847:     #   dns_domain.tab ($filename eq dns_domain).
                    848:     #   loncapaCAcrl.pem ($filename eq loncapaCAcrl).
1.141     foxr      849:     # Construct the destination filename or reject the request.
                    850:     #
                    851:     # lonManage is supposed to ensure this, however this session could be
                    852:     # part of some elaborate spoof that managed somehow to authenticate.
                    853:     #
                    854: 
1.169     foxr      855: 
                    856:     my $tablefile = ConfigFileFromSelector($filename);
                    857:     if(! (defined $tablefile)) {
1.141     foxr      858: 	return "refused";
                    859:     }
1.412     foxr      860: 
1.157     foxr      861:     #  If the file being pushed is the host file, we adjust the entry for ourself so that the
                    862:     #  IP will be our current IP as looked up in dns.  Note this is only 99% good as it's possible
                    863:     #  to conceive of conditions where we don't have a DNS entry locally.  This is possible in a 
                    864:     #  network sense but it doesn't make much sense in a LonCAPA sense so we ignore (for now)
                    865:     #  that possibilty.
                    866: 
                    867:     if($filename eq "host") {
                    868: 	$contents = AdjustHostContents($contents);
1.576     raeburn   869:     } elsif (($filename eq 'dns_hosts') || ($filename eq 'dns_domain') ||
1.549     raeburn   870:              ($filename eq 'loncapaCAcrl')) {
1.510     raeburn   871:         if ($contents eq '') {
                    872:             &logthis('<font color="red"> Pushfile: unable to install '
                    873:                     .$tablefile." - no data received from push. </font>");
                    874:             return 'error: push had no data';
                    875:         }
                    876:         if (&Apache::lonnet::get_host_ip($clientname)) {
                    877:             my $clienthost = &Apache::lonnet::hostname($clientname);
                    878:             if ($managers{$clientip} eq $clientname) {
                    879:                 my $clientprotocol = $Apache::lonnet::protocol{$clientname};
                    880:                 $clientprotocol = 'http' if ($clientprotocol ne 'https');
1.549     raeburn   881:                 my $url;
                    882:                 if ($filename eq 'loncapaCAcrl') {
                    883:                     $url = '/adm/dns/loncapaCRL';
                    884:                 } else {
                    885:                     $url = '/adm/'.$filename;
                    886:                     $url =~ s{_}{/};
                    887:                 }
1.510     raeburn   888:                 my $request=new HTTP::Request('GET',"$clientprotocol://$clienthost$url");
1.523     raeburn   889:                 my $response = LONCAPA::LWPReq::makerequest($clientname,$request,'',\%perlvar,60,0);
1.510     raeburn   890:                 if ($response->is_error()) {
                    891:                     &logthis('<font color="red"> Pushfile: unable to install '
                    892:                             .$tablefile." - error attempting to pull data. </font>");
                    893:                     return 'error: pull failed';
                    894:                 } else {
                    895:                     my $result = $response->content;
                    896:                     chomp($result);
                    897:                     unless ($result eq $contents) {
                    898:                         &logthis('<font color="red"> Pushfile: unable to install '
                    899:                                 .$tablefile." - pushed data and pulled data differ. </font>");
                    900:                         my $pushleng = length($contents);
                    901:                         my $pullleng = length($result);
                    902:                         if ($pushleng != $pullleng) {
                    903:                             return "error: $pushleng vs $pullleng bytes";
                    904:                         } else {
                    905:                             return "error: mismatch push and pull";
                    906:                         }
                    907:                     }
                    908:                 }
                    909:             }
                    910:         }
1.157     foxr      911:     }
                    912: 
1.141     foxr      913:     #  Install the new file:
                    914: 
1.412     foxr      915:     &logthis("Installing new $tablefile contents:\n$contents");
1.143     foxr      916:     if(!InstallFile($tablefile, $contents)) {
                    917: 	&logthis('<font color="red"> Pushfile: unable to install '
1.145     foxr      918: 	 .$tablefile." $! </font>");
1.143     foxr      919: 	return "error:$!";
1.224     foxr      920:     } else {
1.143     foxr      921: 	&logthis('<font color="green"> Installed new '.$tablefile
1.473     raeburn   922: 		 ." - transaction by: $clientname ($clientip)</font>");
1.472     raeburn   923:         my $adminmail = $perlvar{'lonAdmEMail'};
                    924:         my $admindom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                    925:         if ($admindom ne '') {
                    926:             my %domconfig =
                    927:                 &Apache::lonnet::get_dom('configuration',['contacts'],$admindom);
                    928:             if (ref($domconfig{'contacts'}) eq 'HASH') {
                    929:                 if ($domconfig{'contacts'}{'adminemail'} ne '') {
                    930:                     $adminmail = $domconfig{'contacts'}{'adminemail'};
                    931:                 }
                    932:             }
                    933:         }
                    934:         if ($adminmail =~ /^[^\@]+\@[^\@]+$/) {
                    935:             my $msg = new Mail::Send;
                    936:             $msg->to($adminmail);
                    937:             $msg->subject('LON-CAPA DNS update on '.$perlvar{'lonHostID'});
                    938:             $msg->add('Content-type','text/plain; charset=UTF-8');
                    939:             if (my $fh = $msg->open()) {
                    940:                 print $fh 'Update to '.$tablefile.' from Cluster Manager '.
1.473     raeburn   941:                           "$clientname ($clientip)\n";
1.472     raeburn   942:                 $fh->close;
                    943:             }
                    944:         }
1.143     foxr      945:     }
                    946: 
1.141     foxr      947:     #  Indicate success:
                    948:  
                    949:     return "ok";
                    950: 
                    951: }
1.145     foxr      952: 
                    953: #
                    954: #  Called to re-init either lonc or lond.
                    955: #
                    956: #  Parameters:
                    957: #    request   - The full request by the client.  This is of the form
                    958: #                reinit:<process>  
                    959: #                where <process> is allowed to be either of 
                    960: #                lonc or lond
                    961: #
                    962: #  Returns:
                    963: #     The string to be sent back to the client either:
                    964: #   ok         - Everything worked just fine.
                    965: #   error:why  - There was a failure and why describes the reason.
                    966: #
                    967: #
                    968: sub ReinitProcess {
                    969:     my $request = shift;
                    970: 
1.146     foxr      971: 
                    972:     # separate the request (reinit) from the process identifier and
                    973:     # validate it producing the name of the .pid file for the process.
                    974:     #
                    975:     #
                    976:     my ($junk, $process) = split(":", $request);
1.147     foxr      977:     my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
1.146     foxr      978:     if($process eq 'lonc') {
                    979: 	$processpidfile = $processpidfile."lonc.pid";
1.147     foxr      980: 	if (!open(PIDFILE, "< $processpidfile")) {
                    981: 	    return "error:Open failed for $processpidfile";
                    982: 	}
                    983: 	my $loncpid = <PIDFILE>;
                    984: 	close(PIDFILE);
                    985: 	logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
                    986: 		."</font>");
                    987: 	kill("USR2", $loncpid);
1.146     foxr      988:     } elsif ($process eq 'lond') {
1.147     foxr      989: 	logthis('<font color="red"> Reinitializing self (lond) </font>');
                    990: 	&UpdateHosts;			# Lond is us!!
1.146     foxr      991:     } else {
                    992: 	&logthis('<font color="yellow" Invalid reinit request for '.$process
                    993: 		 ."</font>");
                    994: 	return "error:Invalid process identifier $process";
                    995:     }
1.145     foxr      996:     return 'ok';
                    997: }
1.168     foxr      998: #   Validate a line in a configuration file edit script:
                    999: #   Validation includes:
                   1000: #     - Ensuring the command is valid.
                   1001: #     - Ensuring the command has sufficient parameters
                   1002: #   Parameters:
                   1003: #     scriptline - A line to validate (\n has been stripped for what it's worth).
1.167     foxr     1004: #
1.168     foxr     1005: #   Return:
                   1006: #      0     - Invalid scriptline.
                   1007: #      1     - Valid scriptline
                   1008: #  NOTE:
                   1009: #     Only the command syntax is checked, not the executability of the
                   1010: #     command.
                   1011: #
                   1012: sub isValidEditCommand {
                   1013:     my $scriptline = shift;
                   1014: 
                   1015:     #   Line elements are pipe separated:
                   1016: 
                   1017:     my ($command, $key, $newline)  = split(/\|/, $scriptline);
                   1018:     &logthis('<font color="green"> isValideditCommand checking: '.
                   1019: 	     "Command = '$command', Key = '$key', Newline = '$newline' </font>\n");
                   1020:     
                   1021:     if ($command eq "delete") {
                   1022: 	#
                   1023: 	#   key with no newline.
                   1024: 	#
                   1025: 	if( ($key eq "") || ($newline ne "")) {
                   1026: 	    return 0;		# Must have key but no newline.
                   1027: 	} else {
                   1028: 	    return 1;		# Valid syntax.
                   1029: 	}
1.169     foxr     1030:     } elsif ($command eq "replace") {
1.168     foxr     1031: 	#
                   1032: 	#   key and newline:
                   1033: 	#
                   1034: 	if (($key eq "") || ($newline eq "")) {
                   1035: 	    return 0;
                   1036: 	} else {
                   1037: 	    return 1;
                   1038: 	}
1.169     foxr     1039:     } elsif ($command eq "append") {
                   1040: 	if (($key ne "") && ($newline eq "")) {
                   1041: 	    return 1;
                   1042: 	} else {
                   1043: 	    return 0;
                   1044: 	}
1.168     foxr     1045:     } else {
                   1046: 	return 0;		# Invalid command.
                   1047:     }
                   1048:     return 0;			# Should not get here!!!
                   1049: }
1.169     foxr     1050: #
                   1051: #   ApplyEdit - Applies an edit command to a line in a configuration 
                   1052: #               file.  It is the caller's responsiblity to validate the
                   1053: #               edit line.
                   1054: #   Parameters:
                   1055: #      $directive - A single edit directive to apply.  
                   1056: #                   Edit directives are of the form:
                   1057: #                  append|newline      - Appends a new line to the file.
                   1058: #                  replace|key|newline - Replaces the line with key value 'key'
                   1059: #                  delete|key          - Deletes the line with key value 'key'.
                   1060: #      $editor   - A config file editor object that contains the
                   1061: #                  file being edited.
                   1062: #
                   1063: sub ApplyEdit {
1.192     foxr     1064: 
                   1065:     my ($directive, $editor) = @_;
1.169     foxr     1066: 
                   1067:     # Break the directive down into its command and its parameters
                   1068:     # (at most two at this point.  The meaning of the parameters, if in fact
                   1069:     #  they exist depends on the command).
                   1070: 
                   1071:     my ($command, $p1, $p2) = split(/\|/, $directive);
                   1072: 
                   1073:     if($command eq "append") {
                   1074: 	$editor->Append($p1);	          # p1 - key p2 null.
                   1075:     } elsif ($command eq "replace") {
                   1076: 	$editor->ReplaceLine($p1, $p2);   # p1 - key p2 = newline.
                   1077:     } elsif ($command eq "delete") {
                   1078: 	$editor->DeleteLine($p1);         # p1 - key p2 null.
                   1079:     } else {			          # Should not get here!!!
                   1080: 	die "Invalid command given to ApplyEdit $command"
                   1081:     }
                   1082: }
                   1083: #
                   1084: # AdjustOurHost:
                   1085: #           Adjusts a host file stored in a configuration file editor object
                   1086: #           for the true IP address of this host. This is necessary for hosts
                   1087: #           that live behind a firewall.
                   1088: #           Those hosts have a publicly distributed IP of the firewall, but
                   1089: #           internally must use their actual IP.  We assume that a given
                   1090: #           host only has a single IP interface for now.
                   1091: # Formal Parameters:
                   1092: #     editor   - The configuration file editor to adjust.  This
                   1093: #                editor is assumed to contain a hosts.tab file.
                   1094: # Strategy:
                   1095: #    - Figure out our hostname.
                   1096: #    - Lookup the entry for this host.
                   1097: #    - Modify the line to contain our IP
                   1098: #    - Do a replace for this host.
                   1099: sub AdjustOurHost {
                   1100:     my $editor        = shift;
                   1101: 
                   1102:     # figure out who I am.
                   1103: 
                   1104:     my $myHostName    = $perlvar{'lonHostID'}; # LonCAPA hostname.
                   1105: 
                   1106:     #  Get my host file entry.
                   1107: 
                   1108:     my $ConfigLine    = $editor->Find($myHostName);
                   1109:     if(! (defined $ConfigLine)) {
                   1110: 	die "AdjustOurHost - no entry for me in hosts file $myHostName";
                   1111:     }
                   1112:     # figure out my IP:
                   1113:     #   Use the config line to get my hostname.
                   1114:     #   Use gethostbyname to translate that into an IP address.
                   1115:     #
1.338     albertel 1116:     my ($id,$domain,$role,$name,$maxcon,$idleto,$mincon) = split(/:/,$ConfigLine);
1.169     foxr     1117:     #
                   1118:     #  Reassemble the config line from the elements in the list.
                   1119:     #  Note that if the loncnew items were not present before, they will
                   1120:     #  be now even if they would be empty
                   1121:     #
                   1122:     my $newConfigLine = $id;
1.338     albertel 1123:     foreach my $item ($domain, $role, $name, $maxcon, $idleto, $mincon) {
1.169     foxr     1124: 	$newConfigLine .= ":".$item;
                   1125:     }
                   1126:     #  Replace the line:
                   1127: 
                   1128:     $editor->ReplaceLine($id, $newConfigLine);
                   1129:     
                   1130: }
                   1131: #
                   1132: #   ReplaceConfigFile:
                   1133: #              Replaces a configuration file with the contents of a
                   1134: #              configuration file editor object.
                   1135: #              This is done by:
                   1136: #              - Copying the target file to <filename>.old
                   1137: #              - Writing the new file to <filename>.tmp
                   1138: #              - Moving <filename.tmp>  -> <filename>
                   1139: #              This laborious process ensures that the system is never without
                   1140: #              a configuration file that's at least valid (even if the contents
                   1141: #              may be dated).
                   1142: #   Parameters:
                   1143: #        filename   - Name of the file to modify... this is a full path.
                   1144: #        editor     - Editor containing the file.
                   1145: #
                   1146: sub ReplaceConfigFile {
1.192     foxr     1147:     
                   1148:     my ($filename, $editor) = @_;
1.168     foxr     1149: 
1.169     foxr     1150:     CopyFile ($filename, $filename.".old");
                   1151: 
                   1152:     my $contents  = $editor->Get(); # Get the contents of the file.
                   1153: 
                   1154:     InstallFile($filename, $contents);
                   1155: }
1.168     foxr     1156: #   
                   1157: #
                   1158: #   Called to edit a configuration table  file
1.167     foxr     1159: #   Parameters:
                   1160: #      request           - The entire command/request sent by lonc or lonManage
                   1161: #   Return:
                   1162: #      The reply to send to the client.
1.168     foxr     1163: #
1.167     foxr     1164: sub EditFile {
                   1165:     my $request = shift;
                   1166: 
                   1167:     #  Split the command into it's pieces:  edit:filetype:script
                   1168: 
1.339     albertel 1169:     my ($cmd, $filetype, $script) = split(/:/, $request,3);	# : in script
1.167     foxr     1170: 
                   1171:     #  Check the pre-coditions for success:
                   1172: 
1.339     albertel 1173:     if($cmd != "edit") {	# Something is amiss afoot alack.
1.167     foxr     1174: 	return "error:edit request detected, but request != 'edit'\n";
                   1175:     }
                   1176:     if( ($filetype ne "hosts")  &&
                   1177: 	($filetype ne "domain")) {
                   1178: 	return "error:edit requested with invalid file specifier: $filetype \n";
                   1179:     }
                   1180: 
                   1181:     #   Split the edit script and check it's validity.
1.168     foxr     1182: 
                   1183:     my @scriptlines = split(/\n/, $script);  # one line per element.
                   1184:     my $linecount   = scalar(@scriptlines);
                   1185:     for(my $i = 0; $i < $linecount; $i++) {
                   1186: 	chomp($scriptlines[$i]);
                   1187: 	if(!isValidEditCommand($scriptlines[$i])) {
                   1188: 	    return "error:edit with bad script line: '$scriptlines[$i]' \n";
                   1189: 	}
                   1190:     }
1.145     foxr     1191: 
1.167     foxr     1192:     #   Execute the edit operation.
1.169     foxr     1193:     #   - Create a config file editor for the appropriate file and 
                   1194:     #   - execute each command in the script:
                   1195:     #
                   1196:     my $configfile = ConfigFileFromSelector($filetype);
                   1197:     if (!(defined $configfile)) {
                   1198: 	return "refused\n";
                   1199:     }
                   1200:     my $editor = ConfigFileEdit->new($configfile);
1.167     foxr     1201: 
1.169     foxr     1202:     for (my $i = 0; $i < $linecount; $i++) {
                   1203: 	ApplyEdit($scriptlines[$i], $editor);
                   1204:     }
                   1205:     # If the file is the host file, ensure that our host is
                   1206:     # adjusted to have our ip:
                   1207:     #
                   1208:     if($filetype eq "host") {
                   1209: 	AdjustOurHost($editor);
                   1210:     }
                   1211:     #  Finally replace the current file with our file.
                   1212:     #
                   1213:     ReplaceConfigFile($configfile, $editor);
1.167     foxr     1214: 
                   1215:     return "ok\n";
                   1216: }
1.207     foxr     1217: 
1.255     foxr     1218: #   read_profile
                   1219: #
                   1220: #   Returns a set of specific entries from a user's profile file.
                   1221: #   this is a utility function that is used by both get_profile_entry and
                   1222: #   get_profile_entry_encrypted.
                   1223: #
                   1224: # Parameters:
                   1225: #    udom       - Domain in which the user exists.
                   1226: #    uname      - User's account name (loncapa account)
                   1227: #    namespace  - The profile namespace to open.
                   1228: #    what       - A set of & separated queries.
                   1229: # Returns:
                   1230: #    If all ok: - The string that needs to be shipped back to the user.
                   1231: #    If failure - A string that starts with error: followed by the failure
                   1232: #                 reason.. note that this probabyl gets shipped back to the
                   1233: #                 user as well.
                   1234: #
                   1235: sub read_profile {
                   1236:     my ($udom, $uname, $namespace, $what) = @_;
                   1237:     
                   1238:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   1239: 				 &GDBM_READER());
                   1240:     if ($hashref) {
                   1241:         my @queries=split(/\&/,$what);
1.440     raeburn  1242:         if ($namespace eq 'roles') {
                   1243:             @queries = map { &unescape($_); } @queries; 
                   1244:         }
1.255     foxr     1245:         my $qresult='';
                   1246: 	
                   1247: 	for (my $i=0;$i<=$#queries;$i++) {
                   1248: 	    $qresult.="$hashref->{$queries[$i]}&";    # Presumably failure gives empty string.
                   1249: 	}
                   1250: 	$qresult=~s/\&$//;              # Remove trailing & from last lookup.
1.311     albertel 1251: 	if (&untie_user_hash($hashref)) {
1.255     foxr     1252: 	    return $qresult;
                   1253: 	} else {
                   1254: 	    return "error: ".($!+0)." untie (GDBM) Failed";
                   1255: 	}
                   1256:     } else {
                   1257: 	if ($!+0 == 2) {
                   1258: 	    return "error:No such file or GDBM reported bad block error";
                   1259: 	} else {
                   1260: 	    return "error: ".($!+0)." tie (GDBM) Failed";
                   1261: 	}
                   1262:     }
                   1263: 
                   1264: }
1.214     foxr     1265: #--------------------- Request Handlers --------------------------------------------
                   1266: #
1.215     foxr     1267: #   By convention each request handler registers itself prior to the sub 
                   1268: #   declaration:
1.214     foxr     1269: #
                   1270: 
1.216     foxr     1271: #++
                   1272: #
1.214     foxr     1273: #  Handles ping requests.
                   1274: #  Parameters:
                   1275: #      $cmd    - the actual keyword that invoked us.
                   1276: #      $tail   - the tail of the request that invoked us.
                   1277: #      $replyfd- File descriptor connected to the client
                   1278: #  Implicit Inputs:
                   1279: #      $currenthostid - Global variable that carries the name of the host we are
                   1280: #                       known as.
                   1281: #  Returns:
                   1282: #      1       - Ok to continue processing.
                   1283: #      0       - Program should exit.
                   1284: #  Side effects:
                   1285: #      Reply information is sent to the client.
                   1286: sub ping_handler {
                   1287:     my ($cmd, $tail, $client) = @_;
                   1288:     Debug("$cmd $tail $client .. $currenthostid:");
                   1289:    
1.387     albertel 1290:     Reply( $client,\$currenthostid,"$cmd:$tail");
1.214     foxr     1291:    
                   1292:     return 1;
                   1293: }
                   1294: &register_handler("ping", \&ping_handler, 0, 1, 1);       # Ping unencoded, client or manager.
                   1295: 
1.216     foxr     1296: #++
1.215     foxr     1297: #
                   1298: # Handles pong requests.  Pong replies with our current host id, and
                   1299: #                         the results of a ping sent to us via our lonc.
                   1300: #
                   1301: # Parameters:
                   1302: #      $cmd    - the actual keyword that invoked us.
                   1303: #      $tail   - the tail of the request that invoked us.
                   1304: #      $replyfd- File descriptor connected to the client
                   1305: #  Implicit Inputs:
                   1306: #      $currenthostid - Global variable that carries the name of the host we are
                   1307: #                       connected to.
                   1308: #  Returns:
                   1309: #      1       - Ok to continue processing.
                   1310: #      0       - Program should exit.
                   1311: #  Side effects:
                   1312: #      Reply information is sent to the client.
                   1313: sub pong_handler {
                   1314:     my ($cmd, $tail, $replyfd) = @_;
                   1315: 
1.365     albertel 1316:     my $reply=&Apache::lonnet::reply("ping",$clientname);
1.215     foxr     1317:     &Reply( $replyfd, "$currenthostid:$reply\n", "$cmd:$tail"); 
                   1318:     return 1;
                   1319: }
                   1320: &register_handler("pong", \&pong_handler, 0, 1, 1);       # Pong unencoded, client or manager
                   1321: 
1.216     foxr     1322: #++
                   1323: #      Called to establish an encrypted session key with the remote client.
                   1324: #      Note that with secure lond, in most cases this function is never
                   1325: #      invoked.  Instead, the secure session key is established either
                   1326: #      via a local file that's locked down tight and only lives for a short
                   1327: #      time, or via an ssl tunnel...and is generated from a bunch-o-random
                   1328: #      bits from /dev/urandom, rather than the predictable pattern used by
                   1329: #      by this sub.  This sub is only used in the old-style insecure
                   1330: #      key negotiation.
                   1331: # Parameters:
                   1332: #      $cmd    - the actual keyword that invoked us.
                   1333: #      $tail   - the tail of the request that invoked us.
                   1334: #      $replyfd- File descriptor connected to the client
                   1335: #  Implicit Inputs:
                   1336: #      $currenthostid - Global variable that carries the name of the host
                   1337: #                       known as.
1.448     raeburn  1338: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.216     foxr     1339: #  Returns:
                   1340: #      1       - Ok to continue processing.
                   1341: #      0       - Program should exit.
                   1342: #  Implicit Outputs:
                   1343: #      Reply information is sent to the client.
                   1344: #      $cipher is set with a reference to a new IDEA encryption object.
                   1345: #
                   1346: sub establish_key_handler {
                   1347:     my ($cmd, $tail, $replyfd) = @_;
                   1348: 
                   1349:     my $buildkey=time.$$.int(rand 100000);
                   1350:     $buildkey=~tr/1-6/A-F/;
                   1351:     $buildkey=int(rand 100000).$buildkey.int(rand 100000);
                   1352:     my $key=$currenthostid.$clientname;
                   1353:     $key=~tr/a-z/A-Z/;
                   1354:     $key=~tr/G-P/0-9/;
                   1355:     $key=~tr/Q-Z/0-9/;
                   1356:     $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
                   1357:     $key=substr($key,0,32);
                   1358:     my $cipherkey=pack("H32",$key);
                   1359:     $cipher=new IDEA $cipherkey;
1.387     albertel 1360:     &Reply($replyfd, \$buildkey, "$cmd:$tail"); 
1.216     foxr     1361:    
                   1362:     return 1;
                   1363: 
                   1364: }
                   1365: &register_handler("ekey", \&establish_key_handler, 0, 1,1);
                   1366: 
1.217     foxr     1367: #     Handler for the load command.  Returns the current system load average
                   1368: #     to the requestor.
                   1369: #
                   1370: # Parameters:
                   1371: #      $cmd    - the actual keyword that invoked us.
                   1372: #      $tail   - the tail of the request that invoked us.
                   1373: #      $replyfd- File descriptor connected to the client
                   1374: #  Implicit Inputs:
                   1375: #      $currenthostid - Global variable that carries the name of the host
                   1376: #                       known as.
1.448     raeburn  1377: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.217     foxr     1378: #  Returns:
                   1379: #      1       - Ok to continue processing.
                   1380: #      0       - Program should exit.
                   1381: #  Side effects:
                   1382: #      Reply information is sent to the client.
                   1383: sub load_handler {
                   1384:     my ($cmd, $tail, $replyfd) = @_;
                   1385: 
1.463     foxr     1386: 
                   1387: 
1.217     foxr     1388:    # Get the load average from /proc/loadavg and calculate it as a percentage of
                   1389:    # the allowed load limit as set by the perl global variable lonLoadLim
                   1390: 
                   1391:     my $loadavg;
                   1392:     my $loadfile=IO::File->new('/proc/loadavg');
                   1393:    
                   1394:     $loadavg=<$loadfile>;
                   1395:     $loadavg =~ s/\s.*//g;                      # Extract the first field only.
                   1396:    
                   1397:     my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
                   1398: 
1.387     albertel 1399:     &Reply( $replyfd, \$loadpercent, "$cmd:$tail");
1.217     foxr     1400:    
                   1401:     return 1;
                   1402: }
1.263     albertel 1403: &register_handler("load", \&load_handler, 0, 1, 0);
1.217     foxr     1404: 
                   1405: #
                   1406: #   Process the userload request.  This sub returns to the client the current
                   1407: #  user load average.  It can be invoked either by clients or managers.
                   1408: #
                   1409: # Parameters:
                   1410: #      $cmd    - the actual keyword that invoked us.
                   1411: #      $tail   - the tail of the request that invoked us.
                   1412: #      $replyfd- File descriptor connected to the client
                   1413: #  Implicit Inputs:
                   1414: #      $currenthostid - Global variable that carries the name of the host
                   1415: #                       known as.
1.448     raeburn  1416: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.217     foxr     1417: #  Returns:
                   1418: #      1       - Ok to continue processing.
                   1419: #      0       - Program should exit
                   1420: # Implicit inputs:
                   1421: #     whatever the userload() function requires.
                   1422: #  Implicit outputs:
                   1423: #     the reply is written to the client.
                   1424: #
                   1425: sub user_load_handler {
                   1426:     my ($cmd, $tail, $replyfd) = @_;
                   1427: 
1.365     albertel 1428:     my $userloadpercent=&Apache::lonnet::userload();
1.387     albertel 1429:     &Reply($replyfd, \$userloadpercent, "$cmd:$tail");
1.217     foxr     1430:     
                   1431:     return 1;
                   1432: }
1.263     albertel 1433: &register_handler("userload", \&user_load_handler, 0, 1, 0);
1.217     foxr     1434: 
1.218     foxr     1435: #   Process a request for the authorization type of a user:
                   1436: #   (userauth).
                   1437: #
                   1438: # Parameters:
                   1439: #      $cmd    - the actual keyword that invoked us.
                   1440: #      $tail   - the tail of the request that invoked us.
                   1441: #      $replyfd- File descriptor connected to the client
                   1442: #  Returns:
                   1443: #      1       - Ok to continue processing.
                   1444: #      0       - Program should exit
                   1445: # Implicit outputs:
                   1446: #    The user authorization type is written to the client.
                   1447: #
                   1448: sub user_authorization_type {
                   1449:     my ($cmd, $tail, $replyfd) = @_;
                   1450:    
                   1451:     my $userinput = "$cmd:$tail";
                   1452:    
                   1453:     #  Pull the domain and username out of the command tail.
1.222     foxr     1454:     # and call get_auth_type to determine the authentication type.
1.218     foxr     1455:    
                   1456:     my ($udom,$uname)=split(/:/,$tail);
1.222     foxr     1457:     my $result = &get_auth_type($udom, $uname);
1.218     foxr     1458:     if($result eq "nouser") {
                   1459: 	&Failure( $replyfd, "unknown_user\n", $userinput);
                   1460:     } else {
                   1461: 	#
1.222     foxr     1462: 	# We only want to pass the second field from get_auth_type
1.218     foxr     1463: 	# for ^krb.. otherwise we'll be handing out the encrypted
                   1464: 	# password for internals e.g.
                   1465: 	#
                   1466: 	my ($type,$otherinfo) = split(/:/,$result);
                   1467: 	if($type =~ /^krb/) {
                   1468: 	    $type = $result;
1.269     raeburn  1469: 	} else {
                   1470:             $type .= ':';
                   1471:         }
1.387     albertel 1472: 	&Reply( $replyfd, \$type, $userinput);
1.218     foxr     1473:     }
                   1474:   
                   1475:     return 1;
                   1476: }
                   1477: &register_handler("currentauth", \&user_authorization_type, 1, 1, 0);
                   1478: 
                   1479: #   Process a request by a manager to push a hosts or domain table 
                   1480: #   to us.  We pick apart the command and pass it on to the subs
                   1481: #   that already exist to do this.
                   1482: #
                   1483: # Parameters:
                   1484: #      $cmd    - the actual keyword that invoked us.
                   1485: #      $tail   - the tail of the request that invoked us.
                   1486: #      $client - File descriptor connected to the client
                   1487: #  Returns:
                   1488: #      1       - Ok to continue processing.
                   1489: #      0       - Program should exit
                   1490: # Implicit Output:
                   1491: #    a reply is written to the client.
                   1492: sub push_file_handler {
                   1493:     my ($cmd, $tail, $client) = @_;
1.412     foxr     1494:     &Debug("In push file handler");
1.218     foxr     1495:     my $userinput = "$cmd:$tail";
                   1496: 
                   1497:     # At this time we only know that the IP of our partner is a valid manager
                   1498:     # the code below is a hook to do further authentication (e.g. to resolve
                   1499:     # spoofing).
                   1500: 
                   1501:     my $cert = &GetCertificate($userinput);
1.412     foxr     1502:     if(&ValidManager($cert)) {
                   1503: 	&Debug("Valid manager: $client");
1.218     foxr     1504: 
                   1505: 	# Now presumably we have the bona fides of both the peer host and the
                   1506: 	# process making the request.
                   1507:       
                   1508: 	my $reply = &PushFile($userinput);
1.387     albertel 1509: 	&Reply($client, \$reply, $userinput);
1.218     foxr     1510: 
                   1511:     } else {
1.412     foxr     1512: 	&logthis("push_file_handler $client is not valid");
1.218     foxr     1513: 	&Failure( $client, "refused\n", $userinput);
                   1514:     } 
1.219     foxr     1515:     return 1;
1.218     foxr     1516: }
                   1517: &register_handler("pushfile", \&push_file_handler, 1, 0, 1);
                   1518: 
1.399     raeburn  1519: # The du_handler routine should be considered obsolete and is retained
                   1520: # for communication with legacy servers.  Please see the du2_handler.
1.243     banghart 1521: #
1.399     raeburn  1522: #   du  - list the disk usage of a directory recursively. 
1.243     banghart 1523: #    
                   1524: #   note: stolen code from the ls file handler
                   1525: #   under construction by Rick Banghart 
                   1526: #    .
                   1527: # Parameters:
                   1528: #    $cmd        - The command that dispatched us (du).
                   1529: #    $ududir     - The directory path to list... I'm not sure what this
                   1530: #                  is relative as things like ls:. return e.g.
                   1531: #                  no_such_dir.
                   1532: #    $client     - Socket open on the client.
                   1533: # Returns:
                   1534: #     1 - indicating that the daemon should not disconnect.
                   1535: # Side Effects:
                   1536: #   The reply is written to  $client.
                   1537: #
                   1538: sub du_handler {
                   1539:     my ($cmd, $ududir, $client) = @_;
1.339     albertel 1540:     ($ududir) = split(/:/,$ududir); # Make 'telnet' testing easier.
1.251     foxr     1541:     my $userinput = "$cmd:$ududir";
                   1542: 
1.245     albertel 1543:     if ($ududir=~/\.\./ || $ududir!~m|^/home/httpd/|) {
                   1544: 	&Failure($client,"refused\n","$cmd:$ududir");
                   1545: 	return 1;
                   1546:     }
1.249     foxr     1547:     #  Since $ududir could have some nasties in it,
                   1548:     #  we will require that ududir is a valid
                   1549:     #  directory.  Just in case someone tries to
                   1550:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
                   1551:     #  etc.
                   1552:     #
                   1553:     if (-d $ududir) {
1.292     albertel 1554: 	my $total_size=0;
                   1555: 	my $code=sub { 
                   1556: 	    if ($_=~/\.\d+\./) { return;} 
                   1557: 	    if ($_=~/\.meta$/) { return;}
1.362     albertel 1558: 	    if (-d $_)         { return;}
1.292     albertel 1559: 	    $total_size+=(stat($_))[7];
                   1560: 	};
1.295     raeburn  1561: 	chdir($ududir);
1.292     albertel 1562: 	find($code,$ududir);
                   1563: 	$total_size=int($total_size/1024);
1.387     albertel 1564: 	&Reply($client,\$total_size,"$cmd:$ududir");
1.249     foxr     1565:     } else {
1.251     foxr     1566: 	&Failure($client, "bad_directory:$ududir\n","$cmd:$ududir"); 
1.249     foxr     1567:     }
1.243     banghart 1568:     return 1;
                   1569: }
                   1570: &register_handler("du", \&du_handler, 0, 1, 0);
1.218     foxr     1571: 
1.399     raeburn  1572: # Please also see the du_handler, which is obsoleted by du2. 
                   1573: # du2_handler differs from du_handler in that required path to directory
                   1574: # provided by &propath() is prepended in the handler instead of on the 
                   1575: # client side.
1.239     foxr     1576: #
1.399     raeburn  1577: #   du2  - list the disk usage of a directory recursively.
                   1578: #
                   1579: # Parameters:
                   1580: #    $cmd        - The command that dispatched us (du).
                   1581: #    $tail       - The tail of the request that invoked us.
                   1582: #                  $tail is a : separated list of the following:
                   1583: #                   - $ududir - directory path to list (before prepending)
                   1584: #                   - $getpropath = 1 if &propath() should prepend
                   1585: #                   - $uname - username to use for &propath or user dir
                   1586: #                   - $udom - domain to use for &propath or user dir
                   1587: #                   All are escaped.
                   1588: #    $client     - Socket open on the client.
                   1589: # Returns:
                   1590: #     1 - indicating that the daemon should not disconnect.
                   1591: # Side Effects:
                   1592: #   The reply is written to $client.
                   1593: #
                   1594: 
                   1595: sub du2_handler {
                   1596:     my ($cmd, $tail, $client) = @_;
                   1597:     my ($ududir,$getpropath,$uname,$udom) = map { &unescape($_) } (split(/:/, $tail));
                   1598:     my $userinput = "$cmd:$tail";
                   1599:     if (($ududir=~/\.\./) || (($ududir!~m|^/home/httpd/|) && (!$getpropath))) {
                   1600:         &Failure($client,"refused\n","$cmd:$tail");
                   1601:         return 1;
                   1602:     }
                   1603:     if ($getpropath) {
                   1604:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
                   1605:             $ududir = &propath($udom,$uname).'/'.$ududir;
                   1606:         } else {
                   1607:             &Failure($client,"refused\n","$cmd:$tail");
                   1608:             return 1;
                   1609:         }
                   1610:     }
                   1611:     #  Since $ududir could have some nasties in it,
                   1612:     #  we will require that ududir is a valid
                   1613:     #  directory.  Just in case someone tries to
                   1614:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
                   1615:     #  etc.
                   1616:     #
                   1617:     if (-d $ududir) {
                   1618:         my $total_size=0;
                   1619:         my $code=sub {
                   1620:             if ($_=~/\.\d+\./) { return;}
                   1621:             if ($_=~/\.meta$/) { return;}
                   1622:             if (-d $_)         { return;}
                   1623:             $total_size+=(stat($_))[7];
                   1624:         };
                   1625:         chdir($ududir);
                   1626:         find($code,$ududir);
                   1627:         $total_size=int($total_size/1024);
                   1628:         &Reply($client,\$total_size,"$cmd:$ududir");
                   1629:     } else {
                   1630:         &Failure($client, "bad_directory:$ududir\n","$cmd:$tail");
                   1631:     }
                   1632:     return 1;
                   1633: }
                   1634: &register_handler("du2", \&du2_handler, 0, 1, 0);
                   1635: 
                   1636: #
                   1637: # The ls_handler routine should be considered obsolete and is retained
                   1638: # for communication with legacy servers.  Please see the ls3_handler.
1.280     matthew  1639: #
1.239     foxr     1640: #   ls  - list the contents of a directory.  For each file in the
                   1641: #    selected directory the filename followed by the full output of
                   1642: #    the stat function is returned.  The returned info for each
                   1643: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1644: #
                   1645: #    If the requested path contains /../ or is:
                   1646: #
                   1647: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1648: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1649: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1650: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
                   1651: #    or is:
                   1652: #
1.538     raeburn  1653: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1654: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1655: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1656: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
1.529     raeburn  1657: #
                   1658: #    the response will be "refused".
                   1659: #
1.239     foxr     1660: # Parameters:
                   1661: #    $cmd        - The command that dispatched us (ls).
                   1662: #    $ulsdir     - The directory path to list... I'm not sure what this
                   1663: #                  is relative as things like ls:. return e.g.
                   1664: #                  no_such_dir.
                   1665: #    $client     - Socket open on the client.
                   1666: # Returns:
                   1667: #     1 - indicating that the daemon should not disconnect.
                   1668: # Side Effects:
                   1669: #   The reply is written to  $client.
                   1670: #
                   1671: sub ls_handler {
1.280     matthew  1672:     # obsoleted by ls2_handler
1.239     foxr     1673:     my ($cmd, $ulsdir, $client) = @_;
                   1674: 
                   1675:     my $userinput = "$cmd:$ulsdir";
                   1676: 
                   1677:     my $obs;
                   1678:     my $rights;
                   1679:     my $ulsout='';
                   1680:     my $ulsfn;
1.529     raeburn  1681:     if ($ulsdir =~m{/\.\./}) {
                   1682:         &Failure($client,"refused\n",$userinput);
                   1683:         return 1;
                   1684:     }
1.239     foxr     1685:     if (-e $ulsdir) {
                   1686: 	if(-d $ulsdir) {
1.539     raeburn  1687:             unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1688:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
1.529     raeburn  1689:                 &Failure($client,"refused\n",$userinput);
                   1690:                 return 1;
                   1691:             }
1.239     foxr     1692: 	    if (opendir(LSDIR,$ulsdir)) {
                   1693: 		while ($ulsfn=readdir(LSDIR)) {
1.291     albertel 1694: 		    undef($obs);
                   1695: 		    undef($rights); 
1.239     foxr     1696: 		    my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1697: 		    #We do some obsolete checking here
                   1698: 		    if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   1699: 			open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1700: 			my @obsolete=<FILE>;
                   1701: 			foreach my $obsolete (@obsolete) {
1.301     www      1702: 			    if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
1.239     foxr     1703: 			    if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
                   1704: 			}
                   1705: 		    }
                   1706: 		    $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
                   1707: 		    if($obs eq '1') { $ulsout.="&1"; }
                   1708: 		    else { $ulsout.="&0"; }
                   1709: 		    if($rights eq '1') { $ulsout.="&1:"; }
                   1710: 		    else { $ulsout.="&0:"; }
                   1711: 		}
                   1712: 		closedir(LSDIR);
                   1713: 	    }
                   1714: 	} else {
1.539     raeburn  1715:             unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1716:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
1.529     raeburn  1717:                 &Failure($client,"refused\n",$userinput);
                   1718:                 return 1;
                   1719:             }
1.239     foxr     1720: 	    my @ulsstats=stat($ulsdir);
                   1721: 	    $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1722: 	}
                   1723:     } else {
                   1724: 	$ulsout='no_such_dir';
                   1725:     }
                   1726:     if ($ulsout eq '') { $ulsout='empty'; }
1.387     albertel 1727:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1.239     foxr     1728:     
                   1729:     return 1;
                   1730: 
                   1731: }
                   1732: &register_handler("ls", \&ls_handler, 0, 1, 0);
                   1733: 
1.399     raeburn  1734: # The ls2_handler routine should be considered obsolete and is retained
                   1735: # for communication with legacy servers.  Please see the ls3_handler.
                   1736: # Please also see the ls_handler, which was itself obsoleted by ls2.
1.280     matthew  1737: # ls2_handler differs from ls_handler in that it escapes its return 
                   1738: # values before concatenating them together with ':'s.
                   1739: #
                   1740: #   ls2  - list the contents of a directory.  For each file in the
                   1741: #    selected directory the filename followed by the full output of
                   1742: #    the stat function is returned.  The returned info for each
                   1743: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1744: #
                   1745: #    If the requested path contains /../ or is:
                   1746: #
                   1747: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1748: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1749: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1750: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
                   1751: #    or is:
                   1752: #
1.538     raeburn  1753: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1754: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1755: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1756: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
1.529     raeburn  1757: #
                   1758: #    the response will be "refused".
                   1759: #
1.280     matthew  1760: # Parameters:
                   1761: #    $cmd        - The command that dispatched us (ls).
                   1762: #    $ulsdir     - The directory path to list... I'm not sure what this
                   1763: #                  is relative as things like ls:. return e.g.
                   1764: #                  no_such_dir.
                   1765: #    $client     - Socket open on the client.
                   1766: # Returns:
                   1767: #     1 - indicating that the daemon should not disconnect.
                   1768: # Side Effects:
                   1769: #   The reply is written to  $client.
                   1770: #
                   1771: sub ls2_handler {
                   1772:     my ($cmd, $ulsdir, $client) = @_;
                   1773: 
                   1774:     my $userinput = "$cmd:$ulsdir";
                   1775: 
                   1776:     my $obs;
                   1777:     my $rights;
                   1778:     my $ulsout='';
                   1779:     my $ulsfn;
1.529     raeburn  1780:     if ($ulsdir =~m{/\.\./}) {
                   1781:         &Failure($client,"refused\n",$userinput);
                   1782:         return 1;
                   1783:     }
1.280     matthew  1784:     if (-e $ulsdir) {
                   1785:         if(-d $ulsdir) {
1.539     raeburn  1786:             unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1787:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
1.529     raeburn  1788:                 &Failure($client,"refused\n","$userinput");
                   1789:                 return 1;
                   1790:             }
1.280     matthew  1791:             if (opendir(LSDIR,$ulsdir)) {
                   1792:                 while ($ulsfn=readdir(LSDIR)) {
1.291     albertel 1793:                     undef($obs);
                   1794: 		    undef($rights); 
1.280     matthew  1795:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1796:                     #We do some obsolete checking here
                   1797:                     if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   1798:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1799:                         my @obsolete=<FILE>;
                   1800:                         foreach my $obsolete (@obsolete) {
1.301     www      1801:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
1.280     matthew  1802:                             if($obsolete =~ m|(<copyright>)(default)|) {
                   1803:                                 $rights = 1;
                   1804:                             }
                   1805:                         }
                   1806:                     }
                   1807:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
                   1808:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1809:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1810:                     $ulsout.= &escape($tmp).':';
                   1811:                 }
                   1812:                 closedir(LSDIR);
                   1813:             }
                   1814:         } else {
1.539     raeburn  1815:             unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1816:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
1.529     raeburn  1817:                 &Failure($client,"refused\n",$userinput);
                   1818:                 return 1;
                   1819:             }
1.280     matthew  1820:             my @ulsstats=stat($ulsdir);
                   1821:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1822:         }
                   1823:     } else {
                   1824:         $ulsout='no_such_dir';
                   1825:    }
                   1826:    if ($ulsout eq '') { $ulsout='empty'; }
1.387     albertel 1827:    &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1.280     matthew  1828:    return 1;
                   1829: }
                   1830: &register_handler("ls2", \&ls2_handler, 0, 1, 0);
1.399     raeburn  1831: #
                   1832: #   ls3  - list the contents of a directory.  For each file in the
                   1833: #    selected directory the filename followed by the full output of
                   1834: #    the stat function is returned.  The returned info for each
                   1835: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1836: #
                   1837: #    If the requested path (after prepending) contains /../ or is:
                   1838: #
                   1839: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1840: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1841: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1842: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
1.539     raeburn  1843: #        (d) /home/httpd/html/priv/<domain> and client is the homeserver
1.529     raeburn  1844: #
1.530     raeburn  1845: #    or is:
1.529     raeburn  1846: #
1.538     raeburn  1847: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1848: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1849: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1850: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
                   1851: #        (d) /home/httpd/html/priv/<domain>/<username>/ and client is the homeserver
1.529     raeburn  1852: #
                   1853: #    the response will be "refused".
                   1854: #
1.399     raeburn  1855: # Parameters:
                   1856: #    $cmd        - The command that dispatched us (ls).
                   1857: #    $tail       - The tail of the request that invoked us.
                   1858: #                  $tail is a : separated list of the following:
                   1859: #                   - $ulsdir - directory path to list (before prepending)
                   1860: #                   - $getpropath = 1 if &propath() should prepend
                   1861: #                   - $getuserdir = 1 if path to user dir in lonUsers should
                   1862: #                                     prepend
                   1863: #                   - $alternate_root - path to prepend
                   1864: #                   - $uname - username to use for &propath or user dir
                   1865: #                   - $udom - domain to use for &propath or user dir
                   1866: #            All of these except $getpropath and &getuserdir are escaped.    
                   1867: #                  no_such_dir.
                   1868: #    $client     - Socket open on the client.
                   1869: # Returns:
                   1870: #     1 - indicating that the daemon should not disconnect.
                   1871: # Side Effects:
                   1872: #   The reply is written to $client.
                   1873: #
                   1874: 
                   1875: sub ls3_handler {
                   1876:     my ($cmd, $tail, $client) = @_;
                   1877:     my $userinput = "$cmd:$tail";
                   1878:     my ($ulsdir,$getpropath,$getuserdir,$alternate_root,$uname,$udom) =
                   1879:         split(/:/,$tail);
                   1880:     if (defined($ulsdir)) {
                   1881:         $ulsdir = &unescape($ulsdir);
                   1882:     }
                   1883:     if (defined($alternate_root)) {
                   1884:         $alternate_root = &unescape($alternate_root);
                   1885:     }
                   1886:     if (defined($uname)) {
                   1887:         $uname = &unescape($uname);
                   1888:     }
                   1889:     if (defined($udom)) {
                   1890:         $udom = &unescape($udom);
                   1891:     }
                   1892: 
                   1893:     my $dir_root = $perlvar{'lonDocRoot'};
1.529     raeburn  1894:     if (($getpropath) || ($getuserdir)) {
1.399     raeburn  1895:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
                   1896:             $dir_root = &propath($udom,$uname);
                   1897:             $dir_root =~ s/\/$//;
                   1898:         } else {
1.529     raeburn  1899:             &Failure($client,"refused\n",$userinput);
1.399     raeburn  1900:             return 1;
                   1901:         }
1.400     raeburn  1902:     } elsif ($alternate_root ne '') {
1.399     raeburn  1903:         $dir_root = $alternate_root;
                   1904:     }
1.408     raeburn  1905:     if (($dir_root ne '') && ($dir_root ne '/')) {
1.400     raeburn  1906:         if ($ulsdir =~ /^\//) {
                   1907:             $ulsdir = $dir_root.$ulsdir;
                   1908:         } else {
                   1909:             $ulsdir = $dir_root.'/'.$ulsdir;
                   1910:         }
1.399     raeburn  1911:     }
1.529     raeburn  1912:     if ($ulsdir =~m{/\.\./}) {
                   1913:         &Failure($client,"refused\n",$userinput);
                   1914:         return 1;
                   1915:     }
                   1916:     my $islocal;
                   1917:     my @machine_ids = &Apache::lonnet::current_machine_ids();
                   1918:     if (grep(/^\Q$clientname\E$/,@machine_ids)) {
                   1919:         $islocal = 1;
                   1920:     }
1.399     raeburn  1921:     my $obs;
                   1922:     my $rights;
                   1923:     my $ulsout='';
                   1924:     my $ulsfn;
1.547     raeburn  1925: 
                   1926:     my ($crscheck,$toplevel,$currdom,$currnum,$skip);
                   1927:     unless ($islocal) {
                   1928:         my ($major,$minor) = split(/\./,$clientversion);
                   1929:         if (($major < 2) || ($major == 2 && $minor < 12)) {
                   1930:             $crscheck = 1;
                   1931:         }
                   1932:     }
1.399     raeburn  1933:     if (-e $ulsdir) {
                   1934:         if(-d $ulsdir) {
1.529     raeburn  1935:             unless (($getpropath) || ($getuserdir) ||
1.539     raeburn  1936:                     ($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1937:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles}) ||
                   1938:                     (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain}) && ($islocal))) {
1.529     raeburn  1939:                 &Failure($client,"refused\n",$userinput);
                   1940:                 return 1;
                   1941:             }
1.547     raeburn  1942:             if (($crscheck) &&
                   1943:                 ($ulsdir =~ m{^/home/httpd/html/res/($LONCAPA::match_domain)(/?$|/$LONCAPA::match_courseid)})) {
                   1944:                 ($currdom,my $posscnum) = ($1,$2);
                   1945:                 if (($posscnum eq '') || ($posscnum eq '/')) {
                   1946:                     $toplevel = 1;
                   1947:                 } else {
                   1948:                     $posscnum =~ s{^/+}{};
                   1949:                     if (&LONCAPA::Lond::is_course($currdom,$posscnum)) {
                   1950:                         $skip = 1;
                   1951:                     }
                   1952:                 }
                   1953:             }
                   1954:             if ((!$skip) && (opendir(LSDIR,$ulsdir))) {
1.399     raeburn  1955:                 while ($ulsfn=readdir(LSDIR)) {
1.547     raeburn  1956:                     if (($crscheck) && ($toplevel) && ($currdom ne '') &&
                   1957:                         ($ulsfn =~ /^$LONCAPA::match_courseid$/) && (-d "$ulsdir/$ulsfn")) {
                   1958:                         if (&LONCAPA::Lond::is_course($currdom,$ulsfn)) {
                   1959:                             next;
                   1960:                         }
                   1961:                     }
1.399     raeburn  1962:                     undef($obs);
                   1963:                     undef($rights);
                   1964:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1965:                     #We do some obsolete checking here
                   1966:                     if(-e $ulsdir.'/'.$ulsfn.".meta") {
                   1967:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1968:                         my @obsolete=<FILE>;
                   1969:                         foreach my $obsolete (@obsolete) {
                   1970:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; }
                   1971:                             if($obsolete =~ m|(<copyright>)(default)|) {
                   1972:                                 $rights = 1;
                   1973:                             }
                   1974:                         }
                   1975:                     }
                   1976:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
                   1977:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1978:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1979:                     $ulsout.= &escape($tmp).':';
                   1980:                 }
                   1981:                 closedir(LSDIR);
                   1982:             }
                   1983:         } else {
1.529     raeburn  1984:             unless (($getpropath) || ($getuserdir) ||
1.539     raeburn  1985:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1986:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/}) ||
                   1987:                     (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain/$LONCAPA::match_name/}) && ($islocal))) {
1.529     raeburn  1988:                 &Failure($client,"refused\n",$userinput);
                   1989:                 return 1;
                   1990:             }
1.399     raeburn  1991:             my @ulsstats=stat($ulsdir);
                   1992:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1993:         }
                   1994:     } else {
                   1995:         $ulsout='no_such_dir';
1.400     raeburn  1996:     }
                   1997:     if ($ulsout eq '') { $ulsout='empty'; }
                   1998:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
                   1999:     return 1;
1.399     raeburn  2000: }
                   2001: &register_handler("ls3", \&ls3_handler, 0, 1, 0);
1.280     matthew  2002: 
1.477     raeburn  2003: sub read_lonnet_global {
                   2004:     my ($cmd,$tail,$client) = @_;
                   2005:     my $userinput = "$cmd:$tail";
                   2006:     my $requested = &Apache::lonnet::thaw_unescape($tail);
                   2007:     my $result;
1.480     raeburn  2008:     my %packagevars = (
                   2009:                         spareid => \%Apache::lonnet::spareid,
                   2010:                         perlvar => \%Apache::lonnet::perlvar,
                   2011:                       );
                   2012:     my %limit_to = (
                   2013:                     perlvar => {
1.531     raeburn  2014:                                  lonOtherAuthen  => 1,
                   2015:                                  lonBalancer     => 1,
                   2016:                                  lonVersion      => 1,
                   2017:                                  lonAdmEMail     => 1,
                   2018:                                  lonSupportEMail => 1,  
                   2019:                                  lonSysEMail     => 1,
                   2020:                                  lonHostID       => 1,
                   2021:                                  lonRole         => 1,
                   2022:                                  lonDefDomain    => 1,
                   2023:                                  lonLoadLim      => 1,
                   2024:                                  lonUserLoadLim  => 1,
1.480     raeburn  2025:                                }
                   2026:                   );
1.477     raeburn  2027:     if (ref($requested) eq 'HASH') {
                   2028:         foreach my $what (keys(%{$requested})) {
                   2029:             my $response;
1.480     raeburn  2030:             my $items = {};
                   2031:             if (exists($packagevars{$what})) {
                   2032:                 if (ref($limit_to{$what}) eq 'HASH') {
                   2033:                     foreach my $varname (keys(%{$packagevars{$what}})) {
                   2034:                         if ($limit_to{$what}{$varname}) {
                   2035:                             $items->{$varname} = $packagevars{$what}{$varname};
                   2036:                         }
                   2037:                     }
                   2038:                 } else {
                   2039:                     $items = $packagevars{$what};
1.477     raeburn  2040:                 }
1.480     raeburn  2041:                 if ($what eq 'perlvar') {
                   2042:                     if (!exists($packagevars{$what}{'lonBalancer'})) {
1.570     raeburn  2043:                         if ($dist =~ /^(centos|rhes|fedora|scientific|oracle|rocky|alma)/) {
1.480     raeburn  2044:                             my $othervarref=LONCAPA::Configuration::read_conf('httpd.conf');
                   2045:                             if (ref($othervarref) eq 'HASH') {
                   2046:                                 $items->{'lonBalancer'} = $othervarref->{'lonBalancer'};
                   2047:                             }
                   2048:                         }
                   2049:                     }
1.477     raeburn  2050:                 }
1.480     raeburn  2051:                 $response = &Apache::lonnet::freeze_escape($items);
1.477     raeburn  2052:             }
1.478     raeburn  2053:             $result .= &escape($what).'='.$response.'&';
1.477     raeburn  2054:         }
                   2055:     }
                   2056:     $result =~ s/\&$//;
                   2057:     &Reply($client,\$result,$userinput);
                   2058:     return 1;
                   2059: }
                   2060: &register_handler("readlonnetglobal", \&read_lonnet_global, 0, 1, 0);
                   2061: 
1.479     raeburn  2062: sub server_devalidatecache_handler {
                   2063:     my ($cmd,$tail,$client) = @_;
                   2064:     my $userinput = "$cmd:$tail";
1.503     raeburn  2065:     my $items = &unescape($tail);
                   2066:     my @cached = split(/\&/,$items);
                   2067:     foreach my $key (@cached) {
                   2068:         if ($key =~ /:/) {
                   2069:             my ($name,$id) = map { &unescape($_); } split(/:/,$key);
                   2070:             &Apache::lonnet::devalidate_cache_new($name,$id);
                   2071:         }
                   2072:     }
1.479     raeburn  2073:     my $result = 'ok';
                   2074:     &Reply($client,\$result,$userinput);
                   2075:     return 1;
                   2076: }
1.481     raeburn  2077: &register_handler("devalidatecache", \&server_devalidatecache_handler, 0, 1, 0);
1.479     raeburn  2078: 
1.410     raeburn  2079: sub server_timezone_handler {
                   2080:     my ($cmd,$tail,$client) = @_;
                   2081:     my $userinput = "$cmd:$tail";
                   2082:     my $timezone;
                   2083:     my $clockfile = '/etc/sysconfig/clock'; # Fedora/CentOS/SuSE
                   2084:     my $tzfile = '/etc/timezone'; # Debian/Ubuntu
                   2085:     if (-e $clockfile) {
                   2086:         if (open(my $fh,"<$clockfile")) {
                   2087:             while (<$fh>) {
                   2088:                 next if (/^[\#\s]/);
                   2089:                 if (/^(?:TIME)?ZONE\s*=\s*['"]?\s*([\w\/]+)/) {
                   2090:                     $timezone = $1;
                   2091:                     last;
                   2092:                 }
                   2093:             }
                   2094:             close($fh);
                   2095:         }
                   2096:     } elsif (-e $tzfile) {
                   2097:         if (open(my $fh,"<$tzfile")) {
                   2098:             $timezone = <$fh>;
                   2099:             close($fh);
                   2100:             chomp($timezone);
                   2101:             if ($timezone =~ m{^Etc/(\w+)$}) {
                   2102:                 $timezone = $1;
                   2103:             }
                   2104:         }
                   2105:     }
                   2106:     &Reply($client,\$timezone,$userinput); # This supports debug logging.
                   2107:     return 1;
                   2108: }
                   2109: &register_handler("servertimezone", \&server_timezone_handler, 0, 1, 0);
                   2110: 
1.413     raeburn  2111: sub server_loncaparev_handler {
                   2112:     my ($cmd,$tail,$client) = @_;
                   2113:     my $userinput = "$cmd:$tail";
                   2114:     &Reply($client,\$perlvar{'lonVersion'},$userinput);
                   2115:     return 1;
                   2116: }
                   2117: &register_handler("serverloncaparev", \&server_loncaparev_handler, 0, 1, 0);
                   2118: 
1.448     raeburn  2119: sub server_homeID_handler {
                   2120:     my ($cmd,$tail,$client) = @_;
                   2121:     my $userinput = "$cmd:$tail";
                   2122:     &Reply($client,\$perlvar{'lonHostID'},$userinput);
                   2123:     return 1;
                   2124: }
                   2125: &register_handler("serverhomeID", \&server_homeID_handler, 0, 1, 0);
                   2126: 
1.471     raeburn  2127: sub server_distarch_handler {
                   2128:     my ($cmd,$tail,$client) = @_;
                   2129:     my $userinput = "$cmd:$tail";
                   2130:     my $reply = &distro_and_arch();
                   2131:     &Reply($client,\$reply,$userinput);
                   2132:     return 1;
                   2133: }
                   2134: &register_handler("serverdistarch", \&server_distarch_handler, 0, 1, 0);
                   2135: 
1.523     raeburn  2136: sub server_certs_handler {
                   2137:     my ($cmd,$tail,$client) = @_;
                   2138:     my $userinput = "$cmd:$tail";
1.548     raeburn  2139:     my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
                   2140:     my $result = &LONCAPA::Lond::server_certs(\%perlvar,$perlvar{'lonHostID'},$hostname);
1.523     raeburn  2141:     &Reply($client,\$result,$userinput);
                   2142:     return;
                   2143: }
                   2144: &register_handler("servercerts", \&server_certs_handler, 0, 1, 0);
                   2145: 
1.218     foxr     2146: #   Process a reinit request.  Reinit requests that either
                   2147: #   lonc or lond be reinitialized so that an updated 
                   2148: #   host.tab or domain.tab can be processed.
                   2149: #
                   2150: # Parameters:
                   2151: #      $cmd    - the actual keyword that invoked us.
                   2152: #      $tail   - the tail of the request that invoked us.
                   2153: #      $client - File descriptor connected to the client
                   2154: #  Returns:
                   2155: #      1       - Ok to continue processing.
                   2156: #      0       - Program should exit
                   2157: #  Implicit output:
                   2158: #     a reply is sent to the client.
                   2159: #
                   2160: sub reinit_process_handler {
                   2161:     my ($cmd, $tail, $client) = @_;
                   2162:    
                   2163:     my $userinput = "$cmd:$tail";
                   2164:    
                   2165:     my $cert = &GetCertificate($userinput);
                   2166:     if(&ValidManager($cert)) {
                   2167: 	chomp($userinput);
                   2168: 	my $reply = &ReinitProcess($userinput);
1.387     albertel 2169: 	&Reply( $client,  \$reply, $userinput);
1.218     foxr     2170:     } else {
                   2171: 	&Failure( $client, "refused\n", $userinput);
                   2172:     }
                   2173:     return 1;
                   2174: }
                   2175: &register_handler("reinit", \&reinit_process_handler, 1, 0, 1);
                   2176: 
                   2177: #  Process the editing script for a table edit operation.
                   2178: #  the editing operation must be encrypted and requested by
                   2179: #  a manager host.
                   2180: #
                   2181: # Parameters:
                   2182: #      $cmd    - the actual keyword that invoked us.
                   2183: #      $tail   - the tail of the request that invoked us.
                   2184: #      $client - File descriptor connected to the client
                   2185: #  Returns:
                   2186: #      1       - Ok to continue processing.
                   2187: #      0       - Program should exit
                   2188: #  Implicit output:
                   2189: #     a reply is sent to the client.
                   2190: #
                   2191: sub edit_table_handler {
                   2192:     my ($command, $tail, $client) = @_;
                   2193:    
                   2194:     my $userinput = "$command:$tail";
                   2195: 
                   2196:     my $cert = &GetCertificate($userinput);
                   2197:     if(&ValidManager($cert)) {
                   2198: 	my($filetype, $script) = split(/:/, $tail);
                   2199: 	if (($filetype eq "hosts") || 
                   2200: 	    ($filetype eq "domain")) {
                   2201: 	    if($script ne "") {
                   2202: 		&Reply($client,              # BUGBUG - EditFile
                   2203: 		      &EditFile($userinput), #   could fail.
                   2204: 		      $userinput);
                   2205: 	    } else {
                   2206: 		&Failure($client,"refused\n",$userinput);
                   2207: 	    }
                   2208: 	} else {
                   2209: 	    &Failure($client,"refused\n",$userinput);
                   2210: 	}
                   2211:     } else {
                   2212: 	&Failure($client,"refused\n",$userinput);
                   2213:     }
                   2214:     return 1;
                   2215: }
1.263     albertel 2216: &register_handler("edit", \&edit_table_handler, 1, 0, 1);
1.218     foxr     2217: 
1.220     foxr     2218: #
                   2219: #   Authenticate a user against the LonCAPA authentication
                   2220: #   database.  Note that there are several authentication
                   2221: #   possibilities:
                   2222: #   - unix     - The user can be authenticated against the unix
                   2223: #                password file.
                   2224: #   - internal - The user can be authenticated against a purely 
                   2225: #                internal per user password file.
                   2226: #   - kerberos - The user can be authenticated against either a kerb4 or kerb5
                   2227: #                ticket granting authority.
                   2228: #   - user     - The person tailoring LonCAPA can supply a user authentication
                   2229: #                mechanism that is per system.
                   2230: #
                   2231: # Parameters:
                   2232: #    $cmd      - The command that got us here.
                   2233: #    $tail     - Tail of the command (remaining parameters).
                   2234: #    $client   - File descriptor connected to client.
                   2235: # Returns
                   2236: #     0        - Requested to exit, caller should shut down.
                   2237: #     1        - Continue processing.
                   2238: # Implicit inputs:
                   2239: #    The authentication systems describe above have their own forms of implicit
                   2240: #    input into the authentication process that are described above.
                   2241: #
                   2242: sub authenticate_handler {
                   2243:     my ($cmd, $tail, $client) = @_;
                   2244: 
                   2245:     
                   2246:     #  Regenerate the full input line 
                   2247:     
                   2248:     my $userinput  = $cmd.":".$tail;
                   2249:     
                   2250:     #  udom    - User's domain.
                   2251:     #  uname   - Username.
                   2252:     #  upass   - User's password.
1.396     raeburn  2253:     #  checkdefauth - Pass to validate_user() to try authentication
                   2254:     #                 with default auth type(s) if no user account.
1.447     raeburn  2255:     #  clientcancheckhost - Passed by clients with functionality in lonauth.pm
                   2256:     #                       to check if session can be hosted.
1.220     foxr     2257:     
1.447     raeburn  2258:     my ($udom, $uname, $upass, $checkdefauth, $clientcancheckhost)=split(/:/,$tail);
1.399     raeburn  2259:     &Debug(" Authenticate domain = $udom, user = $uname, password = $upass,  checkdefauth = $checkdefauth");
1.220     foxr     2260:     chomp($upass);
                   2261:     $upass=&unescape($upass);
                   2262: 
1.396     raeburn  2263:     my $pwdcorrect = &validate_user($udom,$uname,$upass,$checkdefauth);
1.220     foxr     2264:     if($pwdcorrect) {
1.447     raeburn  2265:         my $canhost = 1;
                   2266:         unless ($clientcancheckhost) {
1.448     raeburn  2267:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   2268:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.452     raeburn  2269:             my @intdoms;
                   2270:             my $internet_names = &Apache::lonnet::get_internet_names($clientname);
                   2271:             if (ref($internet_names) eq 'ARRAY') {
                   2272:                 @intdoms = @{$internet_names};
                   2273:             }
1.448     raeburn  2274:             unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
1.447     raeburn  2275:                 my ($remote,$hosted);
                   2276:                 my $remotesession = &get_usersession_config($udom,'remotesession');
                   2277:                 if (ref($remotesession) eq 'HASH') {
1.525     raeburn  2278:                     $remote = $remotesession->{'remote'};
1.447     raeburn  2279:                 }
1.448     raeburn  2280:                 my $hostedsession = &get_usersession_config($clienthomedom,'hostedsession');
1.447     raeburn  2281:                 if (ref($hostedsession) eq 'HASH') {
                   2282:                     $hosted = $hostedsession->{'hosted'};
                   2283:                 }
1.448     raeburn  2284:                 $canhost = &Apache::lonnet::can_host_session($udom,$clientname,
1.492     droeschl 2285:                                                              $clientversion,
1.447     raeburn  2286:                                                              $remote,$hosted);
                   2287:             }
                   2288:         }
                   2289:         if ($canhost) {               
                   2290:             &Reply( $client, "authorized\n", $userinput);
                   2291:         } else {
                   2292:             &Reply( $client, "not_allowed_to_host\n", $userinput);
                   2293:         }
1.220     foxr     2294: 	#
                   2295: 	#  Bad credentials: Failed to authorize
                   2296: 	#
                   2297:     } else {
                   2298: 	&Failure( $client, "non_authorized\n", $userinput);
                   2299:     }
                   2300: 
                   2301:     return 1;
                   2302: }
1.263     albertel 2303: &register_handler("auth", \&authenticate_handler, 1, 1, 0);
1.214     foxr     2304: 
1.222     foxr     2305: #
                   2306: #   Change a user's password.  Note that this function is complicated by
                   2307: #   the fact that a user may be authenticated in more than one way:
                   2308: #   At present, we are not able to change the password for all types of
                   2309: #   authentication methods.  Only for:
                   2310: #      unix    - unix password or shadow passoword style authentication.
                   2311: #      local   - Locally written authentication mechanism.
                   2312: #   For now, kerb4 and kerb5 password changes are not supported and result
                   2313: #   in an error.
                   2314: # FUTURE WORK:
                   2315: #    Support kerberos passwd changes?
                   2316: # Parameters:
                   2317: #    $cmd      - The command that got us here.
                   2318: #    $tail     - Tail of the command (remaining parameters).
                   2319: #    $client   - File descriptor connected to client.
                   2320: # Returns
                   2321: #     0        - Requested to exit, caller should shut down.
                   2322: #     1        - Continue processing.
                   2323: # Implicit inputs:
                   2324: #    The authentication systems describe above have their own forms of implicit
                   2325: #    input into the authentication process that are described above.
                   2326: sub change_password_handler {
                   2327:     my ($cmd, $tail, $client) = @_;
                   2328: 
                   2329:     my $userinput = $cmd.":".$tail;           # Reconstruct client's string.
                   2330: 
                   2331:     #
                   2332:     #  udom  - user's domain.
                   2333:     #  uname - Username.
                   2334:     #  upass - Current password.
                   2335:     #  npass - New password.
1.346     raeburn  2336:     #  context - Context in which this was called 
                   2337:     #            (preferences or reset_by_email).
1.428     raeburn  2338:     #  lonhost - HostID of server where request originated 
1.222     foxr     2339:    
1.428     raeburn  2340:     my ($udom,$uname,$upass,$npass,$context,$lonhost)=split(/:/,$tail);
1.222     foxr     2341: 
                   2342:     $upass=&unescape($upass);
                   2343:     $npass=&unescape($npass);
                   2344:     &Debug("Trying to change password for $uname");
                   2345: 
                   2346:     # First require that the user can be authenticated with their
1.346     raeburn  2347:     # old password unless context was 'reset_by_email':
                   2348:     
1.428     raeburn  2349:     my ($validated,$failure);
1.346     raeburn  2350:     if ($context eq 'reset_by_email') {
1.428     raeburn  2351:         if ($lonhost eq '') {
                   2352:             $failure = 'invalid_client';
                   2353:         } else {
                   2354:             $validated = 1;
                   2355:         }
1.346     raeburn  2356:     } else {
                   2357:         $validated = &validate_user($udom, $uname, $upass);
                   2358:     }
1.222     foxr     2359:     if($validated) {
                   2360: 	my $realpasswd  = &get_auth_type($udom, $uname); # Defined since authd.
                   2361: 	my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
1.558     raeburn  2362:         my $notunique;
1.222     foxr     2363: 	if ($howpwd eq 'internal') {
                   2364: 	    &Debug("internal auth");
1.518     raeburn  2365:             my $ncpass = &hash_passwd($udom,$npass);
1.558     raeburn  2366:             my (undef,$method,@rest) = split(/!/,$contentpwd);
                   2367:             if ($method eq 'bcrypt') {
                   2368:                 my %passwdconf = &Apache::lonnet::get_passwdconf($udom);
                   2369:                 if (($passwdconf{'numsaved'}) && ($passwdconf{'numsaved'} =~ /^\d+$/)) {
                   2370:                     my @oldpasswds;
                   2371:                     my $userpath = &propath($udom,$uname);
                   2372:                     my $fullpath = $userpath.'/oldpasswds';
                   2373:                     if (-d $userpath) {
                   2374:                         my @oldfiles;
                   2375:                         if (-e $fullpath) {
                   2376:                             if (opendir(my $dir,$fullpath)) {
                   2377:                                 (@oldfiles) = grep(/^\d+$/,readdir($dir));
                   2378:                                 closedir($dir);
                   2379:                             }
                   2380:                             if (@oldfiles) {
                   2381:                                 @oldfiles = sort { $b <=> $a } (@oldfiles);
                   2382:                                 my $numremoved = 0;
                   2383:                                 for (my $i=0; $i<@oldfiles; $i++) {
                   2384:                                     if ($i>=$passwdconf{'numsaved'}) {
                   2385:                                         if (-f "$fullpath/$oldfiles[$i]") {
                   2386:                                             if (unlink("$fullpath/$oldfiles[$i]")) {
                   2387:                                                 $numremoved ++;
                   2388:                                             }
                   2389:                                         }
                   2390:                                     } elsif (open(my $fh,'<',"$fullpath/$oldfiles[$i]")) {
                   2391:                                         while (my $line = <$fh>) {
                   2392:                                             push(@oldpasswds,$line);
                   2393:                                         }
                   2394:                                         close($fh);
                   2395:                                     }
                   2396:                                 }
                   2397:                                 if ($numremoved) {
                   2398:                                     &logthis("unlinked $numremoved old password files for $uname:$udom");
                   2399:                                 }
                   2400:                             }
                   2401:                         }
                   2402:                         push(@oldpasswds,$contentpwd);
                   2403:                         foreach my $item (@oldpasswds) {
                   2404:                             my (undef,$method,@rest) = split(/!/,$item);
                   2405:                             if ($method eq 'bcrypt') {
                   2406:                                 my $result = &hash_passwd($udom,$npass,@rest);
                   2407:                                 if ($result eq $item) {
                   2408:                                     $notunique = 1;
                   2409:                                     last;
                   2410:                                 }
                   2411:                             }
                   2412:                         }
                   2413:                         unless ($notunique) {
                   2414:                             unless (-e $fullpath) {
                   2415:                                 if (&mkpath("$fullpath/")) {
                   2416:                                     chmod(0700,$fullpath);
                   2417:                                 }
                   2418:                             }
                   2419:                             if (-d $fullpath) {
                   2420:                                 my $now = time;
                   2421:                                 if (open(my $fh,'>',"$fullpath/$now")) {
                   2422:                                     print $fh $contentpwd;
                   2423:                                     close($fh);
                   2424:                                     chmod(0400,"$fullpath/$now");
                   2425:                                 }
                   2426:                             }
                   2427:                         }
                   2428:                     }
                   2429:                 }
                   2430:             }
                   2431:             if ($notunique) {
                   2432:                 my $msg="Result of password change for $uname:$udom - password matches one used before";
                   2433:                 if ($lonhost) {
                   2434:                     $msg .= " - request originated from: $lonhost";
                   2435:                 }
                   2436:                 &logthis($msg);
                   2437:                 &Reply($client, "prioruse\n", $userinput);
                   2438: 	    } elsif (&rewrite_password_file($udom, $uname, "internal:$ncpass")) {
1.428     raeburn  2439: 		my $msg="Result of password change for $uname: pwchange_success";
                   2440:                 if ($lonhost) {
                   2441:                     $msg .= " - request originated from: $lonhost";
                   2442:                 }
                   2443:                 &logthis($msg);
1.518     raeburn  2444:                 &update_passwd_history($uname,$udom,$howpwd,$context);
1.222     foxr     2445: 		&Reply($client, "ok\n", $userinput);
                   2446: 	    } else {
                   2447: 		&logthis("Unable to open $uname passwd "               
                   2448: 			 ."to change password");
                   2449: 		&Failure( $client, "non_authorized\n",$userinput);
                   2450: 	    }
1.346     raeburn  2451: 	} elsif ($howpwd eq 'unix' && $context ne 'reset_by_email') {
1.287     foxr     2452: 	    my $result = &change_unix_password($uname, $npass);
1.518     raeburn  2453:             if ($result eq 'ok') {
                   2454:                 &update_passwd_history($uname,$udom,$howpwd,$context);
1.561     raeburn  2455:             }
1.222     foxr     2456: 	    &logthis("Result of password change for $uname: ".
1.287     foxr     2457: 		     $result);
1.387     albertel 2458: 	    &Reply($client, \$result, $userinput);
1.222     foxr     2459: 	} else {
                   2460: 	    # this just means that the current password mode is not
                   2461: 	    # one we know how to change (e.g the kerberos auth modes or
                   2462: 	    # locally written auth handler).
                   2463: 	    #
                   2464: 	    &Failure( $client, "auth_mode_error\n", $userinput);
                   2465: 	}  
1.224     foxr     2466:     } else {
1.428     raeburn  2467: 	if ($failure eq '') {
                   2468: 	    $failure = 'non_authorized';
                   2469: 	}
                   2470: 	&Failure( $client, "$failure\n", $userinput);
1.222     foxr     2471:     }
                   2472: 
                   2473:     return 1;
                   2474: }
1.263     albertel 2475: &register_handler("passwd", \&change_password_handler, 1, 1, 0);
1.222     foxr     2476: 
1.518     raeburn  2477: sub hash_passwd {
                   2478:     my ($domain,$plainpass,@rest) = @_;
                   2479:     my ($salt,$cost);
                   2480:     if (@rest) {
                   2481:         $cost = $rest[0];
                   2482:         # salt is first 22 characters, base-64 encoded by bcrypt
                   2483:         my $plainsalt = substr($rest[1],0,22);
                   2484:         $salt = Crypt::Eksblowfish::Bcrypt::de_base64($plainsalt);
                   2485:     } else {
1.533     raeburn  2486:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   2487:         my $defaultcost = $domdefaults{'intauth_cost'};
1.518     raeburn  2488:         if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
                   2489:             $cost = 10;
                   2490:         } else {
                   2491:             $cost = $defaultcost;
                   2492:         }
                   2493:         # Generate random 16-octet base64 salt
                   2494:         $salt = "";
                   2495:         $salt .= pack("C", int rand(256)) for 1..16;
                   2496:     }
                   2497:     my $hash = &Crypt::Eksblowfish::Bcrypt::bcrypt_hash({
                   2498:         key_nul => 1,
                   2499:         cost    => $cost,
                   2500:         salt    => $salt,
                   2501:     }, Digest::SHA::sha512(Encode::encode('UTF-8',$plainpass)));
                   2502: 
                   2503:     my $result = join("!", "", "bcrypt", sprintf("%02d",$cost),
                   2504:                 &Crypt::Eksblowfish::Bcrypt::en_base64($salt).
                   2505:                 &Crypt::Eksblowfish::Bcrypt::en_base64($hash));
                   2506:     return $result;
                   2507: }
                   2508: 
1.225     foxr     2509: #
                   2510: #   Create a new user.  User in this case means a lon-capa user.
                   2511: #   The user must either already exist in some authentication realm
                   2512: #   like kerberos or the /etc/passwd.  If not, a user completely local to
                   2513: #   this loncapa system is created.
                   2514: #
                   2515: # Parameters:
                   2516: #    $cmd      - The command that got us here.
                   2517: #    $tail     - Tail of the command (remaining parameters).
                   2518: #    $client   - File descriptor connected to client.
                   2519: # Returns
                   2520: #     0        - Requested to exit, caller should shut down.
                   2521: #     1        - Continue processing.
                   2522: # Implicit inputs:
                   2523: #    The authentication systems describe above have their own forms of implicit
                   2524: #    input into the authentication process that are described above.
                   2525: sub add_user_handler {
                   2526: 
                   2527:     my ($cmd, $tail, $client) = @_;
                   2528: 
                   2529: 
                   2530:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   2531:     my $userinput = $cmd.":".$tail; # Reconstruct the full request line.
                   2532: 
                   2533:     &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
                   2534: 
                   2535: 
                   2536:     if($udom eq $currentdomainid) { # Reject new users for other domains...
                   2537: 	
                   2538: 	my $oldumask=umask(0077);
                   2539: 	chomp($npass);
                   2540: 	$npass=&unescape($npass);
                   2541: 	my $passfilename  = &password_path($udom, $uname);
                   2542: 	&Debug("Password file created will be:".$passfilename);
                   2543: 	if (-e $passfilename) {
                   2544: 	    &Failure( $client, "already_exists\n", $userinput);
                   2545: 	} else {
                   2546: 	    my $fperror='';
1.264     albertel 2547: 	    if (!&mkpath($passfilename)) {
                   2548: 		$fperror="error: ".($!+0)." mkdir failed while attempting "
                   2549: 		    ."makeuser";
1.225     foxr     2550: 	    }
                   2551: 	    unless ($fperror) {
1.518     raeburn  2552: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
                   2553:                                              $passfilename,'makeuser');
1.390     raeburn  2554: 		&Reply($client,\$result, $userinput);     #BUGBUG - could be fail
1.225     foxr     2555: 	    } else {
1.387     albertel 2556: 		&Failure($client, \$fperror, $userinput);
1.225     foxr     2557: 	    }
                   2558: 	}
                   2559: 	umask($oldumask);
                   2560:     }  else {
                   2561: 	&Failure($client, "not_right_domain\n",
                   2562: 		$userinput);	# Even if we are multihomed.
                   2563:     
                   2564:     }
                   2565:     return 1;
                   2566: 
                   2567: }
                   2568: &register_handler("makeuser", \&add_user_handler, 1, 1, 0);
                   2569: 
                   2570: #
                   2571: #   Change the authentication method of a user.  Note that this may
                   2572: #   also implicitly change the user's password if, for example, the user is
                   2573: #   joining an existing authentication realm.  Known authentication realms at
                   2574: #   this time are:
                   2575: #    internal   - Purely internal password file (only loncapa knows this user)
                   2576: #    local      - Institutionally written authentication module.
                   2577: #    unix       - Unix user (/etc/passwd with or without /etc/shadow).
                   2578: #    kerb4      - kerberos version 4
                   2579: #    kerb5      - kerberos version 5
                   2580: #
                   2581: # Parameters:
                   2582: #    $cmd      - The command that got us here.
                   2583: #    $tail     - Tail of the command (remaining parameters).
                   2584: #    $client   - File descriptor connected to client.
                   2585: # Returns
                   2586: #     0        - Requested to exit, caller should shut down.
                   2587: #     1        - Continue processing.
                   2588: # Implicit inputs:
                   2589: #    The authentication systems describe above have their own forms of implicit
                   2590: #    input into the authentication process that are described above.
1.287     foxr     2591: # NOTE:
                   2592: #   This is also used to change the authentication credential values (e.g. passwd).
                   2593: #   
1.225     foxr     2594: #
                   2595: sub change_authentication_handler {
                   2596: 
                   2597:     my ($cmd, $tail, $client) = @_;
                   2598:    
                   2599:     my $userinput  = "$cmd:$tail";              # Reconstruct user input.
                   2600: 
                   2601:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   2602:     &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
                   2603:     if ($udom ne $currentdomainid) {
                   2604: 	&Failure( $client, "not_right_domain\n", $client);
                   2605:     } else {
                   2606: 	
                   2607: 	chomp($npass);
                   2608: 	
                   2609: 	$npass=&unescape($npass);
1.261     foxr     2610: 	my $oldauth = &get_auth_type($udom, $uname); # Get old auth info.
1.225     foxr     2611: 	my $passfilename = &password_path($udom, $uname);
                   2612: 	if ($passfilename) {	# Not allowed to create a new user!!
1.287     foxr     2613: 	    # If just changing the unix passwd. need to arrange to run
1.502     raeburn  2614: 	    # passwd since otherwise make_passwd_file will fail as 
                   2615: 	    # creation of unix authenticated users is no longer supported
                   2616:             # except from the command line, when running make_domain_coordinator.pl
1.287     foxr     2617: 
                   2618: 	    if(($oldauth =~/^unix/) && ($umode eq "unix")) {
                   2619: 		my $result = &change_unix_password($uname, $npass);
                   2620: 		&logthis("Result of password change for $uname: ".$result);
                   2621: 		if ($result eq "ok") {
1.518     raeburn  2622:                     &update_passwd_history($uname,$udom,$umode,'changeuserauth'); 
1.390     raeburn  2623: 		    &Reply($client, \$result);
1.288     albertel 2624: 		} else {
1.387     albertel 2625: 		    &Failure($client, \$result);
1.287     foxr     2626: 		}
1.288     albertel 2627: 	    } else {
1.518     raeburn  2628: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
                   2629:                                              $passfilename,'changeuserauth');
1.287     foxr     2630: 		#
                   2631: 		#  If the current auth mode is internal, and the old auth mode was
                   2632: 		#  unix, or krb*,  and the user is an author for this domain,
                   2633: 		#  re-run manage_permissions for that role in order to be able
                   2634: 		#  to take ownership of the construction space back to www:www
                   2635: 		#
1.502     raeburn  2636: 
                   2637: 
1.387     albertel 2638: 		&Reply($client, \$result, $userinput);
1.261     foxr     2639: 	    }
                   2640: 	       
                   2641: 
1.225     foxr     2642: 	} else {	       
1.251     foxr     2643: 	    &Failure($client, "non_authorized\n", $userinput); # Fail the user now.
1.225     foxr     2644: 	}
                   2645:     }
                   2646:     return 1;
                   2647: }
                   2648: &register_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
                   2649: 
1.518     raeburn  2650: sub update_passwd_history {
                   2651:     my ($uname,$udom,$umode,$context) = @_;
                   2652:     my $proname=&propath($udom,$uname);
                   2653:     my $now = time;
                   2654:     if (open(my $fh,">>$proname/passwd.log")) {
                   2655:         print $fh "$now:$umode:$context\n";
                   2656:         close($fh);
                   2657:     }
                   2658:     return;
                   2659: }
                   2660: 
1.575     raeburn  2661: sub inst_unamemap_check {
                   2662:     my ($cmd, $tail, $client)   = @_;
                   2663:     my $userinput               = "$cmd:$tail";
                   2664:     my %rulecheck;
                   2665:     my $outcome;
                   2666:     my ($udom,$uname,@rules) = split(/:/,$tail);
                   2667:     $udom = &unescape($udom);
                   2668:     $uname = &unescape($uname);
                   2669:     @rules = map {&unescape($_);} (@rules);
                   2670:     eval {
                   2671:         local($SIG{__DIE__})='DEFAULT';
                   2672:         $outcome = &localenroll::unamemap_check($udom,$uname,\@rules,\%rulecheck);
                   2673:     };
                   2674:     if (!$@) {
                   2675:         if ($outcome eq 'ok') {
                   2676:             my $result='';
                   2677:             foreach my $key (keys(%rulecheck)) {
                   2678:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   2679:             }
                   2680:             &Reply($client,\$result,$userinput);
                   2681:         } else {
                   2682:             &Reply($client,"error\n", $userinput);
                   2683:         }
                   2684:     } else {
                   2685:         &Failure($client,"unknown_cmd\n",$userinput);
                   2686:     }
                   2687: }
                   2688: &register_handler("instunamemapcheck",\&inst_unamemap_check,0,1,0);
                   2689: 
                   2690: 
1.225     foxr     2691: #
                   2692: #   Determines if this is the home server for a user.  The home server
                   2693: #   for a user will have his/her lon-capa passwd file.  Therefore all we need
                   2694: #   to do is determine if this file exists.
                   2695: #
                   2696: # Parameters:
                   2697: #    $cmd      - The command that got us here.
                   2698: #    $tail     - Tail of the command (remaining parameters).
                   2699: #    $client   - File descriptor connected to client.
                   2700: # Returns
                   2701: #     0        - Requested to exit, caller should shut down.
                   2702: #     1        - Continue processing.
                   2703: # Implicit inputs:
                   2704: #    The authentication systems describe above have their own forms of implicit
                   2705: #    input into the authentication process that are described above.
                   2706: #
                   2707: sub is_home_handler {
                   2708:     my ($cmd, $tail, $client) = @_;
                   2709:    
                   2710:     my $userinput  = "$cmd:$tail";
                   2711:    
                   2712:     my ($udom,$uname)=split(/:/,$tail);
                   2713:     chomp($uname);
                   2714:     my $passfile = &password_filename($udom, $uname);
                   2715:     if($passfile) {
                   2716: 	&Reply( $client, "found\n", $userinput);
                   2717:     } else {
                   2718: 	&Failure($client, "not_found\n", $userinput);
                   2719:     }
                   2720:     return 1;
                   2721: }
                   2722: &register_handler("home", \&is_home_handler, 0,1,0);
                   2723: 
                   2724: #
1.434     www      2725: #   Process an update request for a resource.
                   2726: #   A resource has been modified that we hold a subscription to.
1.225     foxr     2727: #   If the resource is not local, then we must update, or at least invalidate our
                   2728: #   cached copy of the resource. 
                   2729: # Parameters:
                   2730: #    $cmd      - The command that got us here.
                   2731: #    $tail     - Tail of the command (remaining parameters).
                   2732: #    $client   - File descriptor connected to client.
                   2733: # Returns
                   2734: #     0        - Requested to exit, caller should shut down.
                   2735: #     1        - Continue processing.
                   2736: # Implicit inputs:
                   2737: #    The authentication systems describe above have their own forms of implicit
                   2738: #    input into the authentication process that are described above.
                   2739: #
                   2740: sub update_resource_handler {
                   2741: 
                   2742:     my ($cmd, $tail, $client) = @_;
                   2743:    
                   2744:     my $userinput = "$cmd:$tail";
                   2745:    
                   2746:     my $fname= $tail;		# This allows interactive testing
                   2747: 
                   2748: 
                   2749:     my $ownership=ishome($fname);
                   2750:     if ($ownership eq 'not_owner') {
                   2751: 	if (-e $fname) {
1.434     www      2752:             # Delete preview file, if exists
                   2753:             unlink("$fname.tmp");
                   2754:             # Get usage stats
1.225     foxr     2755: 	    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
                   2756: 		$atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
                   2757: 	    my $now=time;
                   2758: 	    my $since=$now-$atime;
1.434     www      2759:             # If the file has not been used within lonExpire seconds,
                   2760:             # unsubscribe from it and delete local copy
1.225     foxr     2761: 	    if ($since>$perlvar{'lonExpire'}) {
1.365     albertel 2762: 		my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
1.308     albertel 2763: 		&devalidate_meta_cache($fname);
1.225     foxr     2764: 		unlink("$fname");
1.334     albertel 2765: 		unlink("$fname.meta");
1.225     foxr     2766: 	    } else {
1.434     www      2767:             # Yes, this is in active use. Get a fresh copy. Since it might be in
                   2768:             # very active use and huge (like a movie), copy it to "in.transfer" filename first.
1.225     foxr     2769: 		my $transname="$fname.in.transfer";
1.365     albertel 2770: 		my $remoteurl=&Apache::lonnet::reply("sub:$fname","$clientname");
1.225     foxr     2771: 		my $response;
1.537     raeburn  2772: # FIXME: cannot replicate files that take more than two minutes to transfer -- needs checking now 1200s timeout used
                   2773: # for LWP request.
                   2774: 		my $request=new HTTP::Request('GET',"$remoteurl");
                   2775:                 $response=&LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,0,1);
1.225     foxr     2776: 		if ($response->is_error()) {
1.541     raeburn  2777:                     my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
                   2778:                     &devalidate_meta_cache($fname);
                   2779:                     if (-e $transname) {
                   2780:                         unlink($transname);
                   2781:                     }
                   2782:                     unlink($fname);
1.225     foxr     2783: 		    my $message=$response->status_line;
                   2784: 		    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   2785: 		} else {
                   2786: 		    if ($remoteurl!~/\.meta$/) {
1.537     raeburn  2787: 			my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2788:                         my $mresponse = &LONCAPA::LWPReq::makerequest($clientname,$mrequest,$fname.'.meta',\%perlvar,120,0,1);
                   2789: 			if ($mresponse->is_error()) {
                   2790: 			    unlink($fname.'.meta');
1.225     foxr     2791: 			}
                   2792: 		    }
1.434     www      2793:                     # we successfully transfered, copy file over to real name
1.225     foxr     2794: 		    rename($transname,$fname);
1.308     albertel 2795: 		    &devalidate_meta_cache($fname);
1.225     foxr     2796: 		}
                   2797: 	    }
                   2798: 	    &Reply( $client, "ok\n", $userinput);
                   2799: 	} else {
                   2800: 	    &Failure($client, "not_found\n", $userinput);
                   2801: 	}
                   2802:     } else {
                   2803: 	&Failure($client, "rejected\n", $userinput);
                   2804:     }
                   2805:     return 1;
                   2806: }
                   2807: &register_handler("update", \&update_resource_handler, 0 ,1, 0);
                   2808: 
1.308     albertel 2809: sub devalidate_meta_cache {
                   2810:     my ($url) = @_;
                   2811:     use Cache::Memcached;
                   2812:     my $memcache = new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.365     albertel 2813:     $url = &Apache::lonnet::declutter($url);
1.308     albertel 2814:     $url =~ s-\.meta$--;
                   2815:     my $id = &escape('meta:'.$url);
                   2816:     $memcache->delete($id);
                   2817: }
                   2818: 
1.225     foxr     2819: #
1.226     foxr     2820: #   Fetch a user file from a remote server to the user's home directory
                   2821: #   userfiles subdir.
1.225     foxr     2822: # Parameters:
                   2823: #    $cmd      - The command that got us here.
                   2824: #    $tail     - Tail of the command (remaining parameters).
                   2825: #    $client   - File descriptor connected to client.
                   2826: # Returns
                   2827: #     0        - Requested to exit, caller should shut down.
                   2828: #     1        - Continue processing.
                   2829: #
                   2830: sub fetch_user_file_handler {
                   2831: 
                   2832:     my ($cmd, $tail, $client) = @_;
                   2833: 
                   2834:     my $userinput = "$cmd:$tail";
                   2835:     my $fname           = $tail;
1.232     foxr     2836:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
1.225     foxr     2837:     my $udir=&propath($udom,$uname).'/userfiles';
                   2838:     unless (-e $udir) {
                   2839: 	mkdir($udir,0770); 
                   2840:     }
1.232     foxr     2841:     Debug("fetch user file for $fname");
1.225     foxr     2842:     if (-e $udir) {
                   2843: 	$ufile=~s/^[\.\~]+//;
1.232     foxr     2844: 
                   2845: 	# IF necessary, create the path right down to the file.
                   2846: 	# Note that any regular files in the way of this path are
                   2847: 	# wiped out to deal with some earlier folly of mine.
                   2848: 
1.267     raeburn  2849: 	if (!&mkpath($udir.'/'.$ufile)) {
1.264     albertel 2850: 	    &Failure($client, "unable_to_create\n", $userinput);	    
1.232     foxr     2851: 	}
                   2852: 
1.225     foxr     2853: 	my $destname=$udir.'/'.$ufile;
                   2854: 	my $transname=$udir.'/'.$ufile.'.in.transit';
1.476     raeburn  2855:         my $clientprotocol=$Apache::lonnet::protocol{$clientname};
                   2856:         $clientprotocol = 'http' if ($clientprotocol ne 'https');
1.486     raeburn  2857: 	my $clienthost = &Apache::lonnet::hostname($clientname);
                   2858: 	my $remoteurl=$clientprotocol.'://'.$clienthost.'/userfiles/'.$fname;
1.225     foxr     2859: 	my $response;
1.232     foxr     2860: 	Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
1.537     raeburn  2861: 	my $request=new HTTP::Request('GET',"$remoteurl");
                   2862:         my $verifycert = 1;
                   2863:         my @machine_ids = &Apache::lonnet::current_machine_ids();
                   2864:         if (grep(/^\Q$clientname\E$/,@machine_ids)) {
                   2865:             $verifycert = 0;
                   2866:         }
                   2867:         $response = &LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,$verifycert);
1.225     foxr     2868: 	if ($response->is_error()) {
                   2869: 	    unlink($transname);
                   2870: 	    my $message=$response->status_line;
                   2871: 	    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   2872: 	    &Failure($client, "failed\n", $userinput);
                   2873: 	} else {
1.232     foxr     2874: 	    Debug("Renaming $transname to $destname");
1.225     foxr     2875: 	    if (!rename($transname,$destname)) {
                   2876: 		&logthis("Unable to move $transname to $destname");
                   2877: 		unlink($transname);
                   2878: 		&Failure($client, "failed\n", $userinput);
                   2879: 	    } else {
1.495     raeburn  2880:                 if ($fname =~ /^default.+\.(page|sequence)$/) {
                   2881:                     my ($major,$minor) = split(/\./,$clientversion);
                   2882:                     if (($major < 2) || ($major == 2 && $minor < 11)) {
                   2883:                         my $now = time;
                   2884:                         &Apache::lonnet::do_cache_new('crschange',$udom.'_'.$uname,$now,600);
                   2885:                         my $key = &escape('internal.contentchange');
                   2886:                         my $what = "$key=$now";
                   2887:                         my $hashref = &tie_user_hash($udom,$uname,'environment',
                   2888:                                                      &GDBM_WRCREAT(),"P",$what);
                   2889:                         if ($hashref) {
                   2890:                             $hashref->{$key}=$now;
                   2891:                             if (!&untie_user_hash($hashref)) {
                   2892:                                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
                   2893:                                          "when updating internal.contentchange");
                   2894:                             }
                   2895:                         }
                   2896:                     }
                   2897:                 }
1.225     foxr     2898: 		&Reply($client, "ok\n", $userinput);
                   2899: 	    }
                   2900: 	}   
                   2901:     } else {
                   2902: 	&Failure($client, "not_home\n", $userinput);
                   2903:     }
                   2904:     return 1;
                   2905: }
                   2906: &register_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
                   2907: 
1.226     foxr     2908: #
                   2909: #   Remove a file from a user's home directory userfiles subdirectory.
                   2910: # Parameters:
                   2911: #    cmd   - the Lond request keyword that got us here.
                   2912: #    tail  - the part of the command past the keyword.
                   2913: #    client- File descriptor connected with the client.
                   2914: #
                   2915: # Returns:
                   2916: #    1    - Continue processing.
                   2917: sub remove_user_file_handler {
                   2918:     my ($cmd, $tail, $client) = @_;
                   2919: 
                   2920:     my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2921: 
                   2922:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2923:     if ($ufile =~m|/\.\./|) {
                   2924: 	# any files paths with /../ in them refuse 
                   2925: 	# to deal with
                   2926: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2927:     } else {
                   2928: 	my $udir = &propath($udom,$uname);
                   2929: 	if (-e $udir) {
                   2930: 	    my $file=$udir.'/userfiles/'.$ufile;
                   2931: 	    if (-e $file) {
1.253     foxr     2932: 		#
                   2933: 		#   If the file is a regular file unlink is fine...
1.520     raeburn  2934: 		#   However it's possible the client wants a dir 
                   2935: 		#   removed, in which case rmdir is more appropriate.
                   2936: 		#   Note: rmdir will only remove an empty directory.
1.253     foxr     2937: 		#
1.240     banghart 2938: 	        if (-f $file){
1.241     albertel 2939: 		    unlink($file);
1.520     raeburn  2940:                     # for html files remove the associated .bak file 
                   2941:                     # which may have been created by the editor.
                   2942:                     if ($ufile =~ m{^((docs|supplemental)/(?:\d+|default)/\d+(?:|/.+)/)[^/]+\.x?html?$}i) {
                   2943:                         my $path = $1;
                   2944:                         if (-e $file.'.bak') {
                   2945:                             unlink($file.'.bak');
                   2946:                         }
                   2947:                     }
1.241     albertel 2948: 		} elsif(-d $file) {
                   2949: 		    rmdir($file);
1.240     banghart 2950: 		}
1.226     foxr     2951: 		if (-e $file) {
1.253     foxr     2952: 		    #  File is still there after we deleted it ?!?
                   2953: 
1.226     foxr     2954: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2955: 		} else {
                   2956: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2957: 		}
                   2958: 	    } else {
                   2959: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2960: 	    }
                   2961: 	} else {
                   2962: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2963: 	}
                   2964:     }
                   2965:     return 1;
                   2966: }
                   2967: &register_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
                   2968: 
1.236     albertel 2969: #
                   2970: #   make a directory in a user's home directory userfiles subdirectory.
                   2971: # Parameters:
                   2972: #    cmd   - the Lond request keyword that got us here.
                   2973: #    tail  - the part of the command past the keyword.
                   2974: #    client- File descriptor connected with the client.
                   2975: #
                   2976: # Returns:
                   2977: #    1    - Continue processing.
                   2978: sub mkdir_user_file_handler {
                   2979:     my ($cmd, $tail, $client) = @_;
                   2980: 
                   2981:     my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2982:     $dir=&unescape($dir);
                   2983:     my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2984:     if ($ufile =~m|/\.\./|) {
                   2985: 	# any files paths with /../ in them refuse 
                   2986: 	# to deal with
                   2987: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2988:     } else {
                   2989: 	my $udir = &propath($udom,$uname);
                   2990: 	if (-e $udir) {
1.264     albertel 2991: 	    my $newdir=$udir.'/userfiles/'.$ufile.'/';
                   2992: 	    if (!&mkpath($newdir)) {
                   2993: 		&Failure($client, "failed\n", "$cmd:$tail");
1.236     albertel 2994: 	    }
1.264     albertel 2995: 	    &Reply($client, "ok\n", "$cmd:$tail");
1.236     albertel 2996: 	} else {
                   2997: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2998: 	}
                   2999:     }
                   3000:     return 1;
                   3001: }
                   3002: &register_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
                   3003: 
1.237     albertel 3004: #
                   3005: #   rename a file in a user's home directory userfiles subdirectory.
                   3006: # Parameters:
                   3007: #    cmd   - the Lond request keyword that got us here.
                   3008: #    tail  - the part of the command past the keyword.
                   3009: #    client- File descriptor connected with the client.
                   3010: #
                   3011: # Returns:
                   3012: #    1    - Continue processing.
                   3013: sub rename_user_file_handler {
                   3014:     my ($cmd, $tail, $client) = @_;
                   3015: 
                   3016:     my ($udom,$uname,$old,$new) = split(/:/, $tail);
                   3017:     $old=&unescape($old);
                   3018:     $new=&unescape($new);
                   3019:     if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
                   3020: 	# any files paths with /../ in them refuse to deal with
                   3021: 	&Failure($client, "refused\n", "$cmd:$tail");
                   3022:     } else {
                   3023: 	my $udir = &propath($udom,$uname);
                   3024: 	if (-e $udir) {
                   3025: 	    my $oldfile=$udir.'/userfiles/'.$old;
                   3026: 	    my $newfile=$udir.'/userfiles/'.$new;
                   3027: 	    if (-e $newfile) {
                   3028: 		&Failure($client, "exists\n", "$cmd:$tail");
                   3029: 	    } elsif (! -e $oldfile) {
                   3030: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   3031: 	    } else {
                   3032: 		if (!rename($oldfile,$newfile)) {
                   3033: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   3034: 		} else {
                   3035: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   3036: 		}
                   3037: 	    }
                   3038: 	} else {
                   3039: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   3040: 	}
                   3041:     }
                   3042:     return 1;
                   3043: }
                   3044: &register_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
                   3045: 
1.227     foxr     3046: #
1.382     albertel 3047: #  Checks if the specified user has an active session on the server
                   3048: #  return ok if so, not_found if not
                   3049: #
                   3050: # Parameters:
                   3051: #   cmd      - The request keyword that dispatched to tus.
                   3052: #   tail     - The tail of the request (colon separated parameters).
                   3053: #   client   - Filehandle open on the client.
                   3054: # Return:
                   3055: #    1.
                   3056: sub user_has_session_handler {
                   3057:     my ($cmd, $tail, $client) = @_;
                   3058: 
                   3059:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
                   3060:     
                   3061:     opendir(DIR,$perlvar{'lonIDsDir'});
                   3062:     my $filename;
                   3063:     while ($filename=readdir(DIR)) {
                   3064: 	last if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/);
                   3065:     }
                   3066:     if ($filename) {
                   3067: 	&Reply($client, "ok\n", "$cmd:$tail");
                   3068:     } else {
                   3069: 	&Failure($client, "not_found\n", "$cmd:$tail");
                   3070:     }
                   3071:     return 1;
                   3072: 
                   3073: }
                   3074: &register_handler("userhassession", \&user_has_session_handler, 0,1,0);
                   3075: 
1.560     raeburn  3076: sub del_usersession_handler {
                   3077:     my ($cmd, $tail, $client) = @_;
                   3078: 
                   3079:     my $result;
                   3080:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
                   3081:     if (($udom =~ /^$LONCAPA::match_domain$/) && ($uname =~ /^$LONCAPA::match_username$/)) {
                   3082:         my $lonidsdir = $perlvar{'lonIDsDir'};
                   3083:         if (-d $lonidsdir) {
                   3084:             if (opendir(DIR,$lonidsdir)) {
                   3085:                 my $filename;
                   3086:                 while ($filename=readdir(DIR)) {
                   3087:                     if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/) {
                   3088:                         if (tie(my %oldenv,'GDBM_File',"$lonidsdir/$filename",
                   3089:                                 &GDBM_READER(),0640)) {
                   3090:                             my $linkedfile;
                   3091:                             if (exists($oldenv{'user.linkedenv'})) {
                   3092:                                 $linkedfile = $oldenv{'user.linkedenv'};
                   3093:                             }
                   3094:                             untie(%oldenv);
                   3095:                             $result = unlink("$lonidsdir/$filename");
                   3096:                             if ($result) {
                   3097:                                 if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   3098:                                     if (-l "$lonidsdir/$linkedfile.id") {
                   3099:                                         unlink("$lonidsdir/$linkedfile.id");
                   3100:                                     }
                   3101:                                 }
                   3102:                             }
                   3103:                         } else {
                   3104:                             $result = unlink("$lonidsdir/$filename");
                   3105:                         }
                   3106:                         last;
                   3107:                     }
                   3108:                 }
                   3109:             }
                   3110:         }
                   3111:         if ($result == 1) {
                   3112:             &Reply($client, "$result\n", "$cmd:$tail");
                   3113:         } else {
                   3114:             &Reply($client, "not_found\n", "$cmd:$tail");
                   3115:         }
                   3116:     } else {
                   3117:         &Failure($client, "invalid_user\n", "$cmd:$tail");
                   3118:     }
                   3119:     return 1;
                   3120: }
                   3121: 
                   3122: &register_handler("delusersession", \&del_usersession_handler, 0,1,0);
                   3123: 
1.382     albertel 3124: #
1.263     albertel 3125: #  Authenticate access to a user file by checking that the token the user's 
                   3126: #  passed also exists in their session file
1.227     foxr     3127: #
                   3128: # Parameters:
                   3129: #   cmd      - The request keyword that dispatched to tus.
                   3130: #   tail     - The tail of the request (colon separated parameters).
                   3131: #   client   - Filehandle open on the client.
                   3132: # Return:
                   3133: #    1.
                   3134: sub token_auth_user_file_handler {
                   3135:     my ($cmd, $tail, $client) = @_;
                   3136: 
                   3137:     my ($fname, $session) = split(/:/, $tail);
                   3138:     
                   3139:     chomp($session);
1.393     raeburn  3140:     my $reply="non_auth";
1.343     albertel 3141:     my $file = $perlvar{'lonIDsDir'}.'/'.$session.'.id';
                   3142:     if (open(ENVIN,"$file")) {
1.332     albertel 3143: 	flock(ENVIN,LOCK_SH);
1.343     albertel 3144: 	tie(my %disk_env,'GDBM_File',"$file",&GDBM_READER(),0640);
                   3145: 	if (exists($disk_env{"userfile.$fname"})) {
1.393     raeburn  3146: 	    $reply="ok";
1.343     albertel 3147: 	} else {
                   3148: 	    foreach my $envname (keys(%disk_env)) {
                   3149: 		if ($envname=~ m|^userfile\.\Q$fname\E|) {
1.393     raeburn  3150: 		    $reply="ok";
1.343     albertel 3151: 		    last;
                   3152: 		}
                   3153: 	    }
1.227     foxr     3154: 	}
1.343     albertel 3155: 	untie(%disk_env);
1.227     foxr     3156: 	close(ENVIN);
1.387     albertel 3157: 	&Reply($client, \$reply, "$cmd:$tail");
1.227     foxr     3158:     } else {
                   3159: 	&Failure($client, "invalid_token\n", "$cmd:$tail");
                   3160:     }
                   3161:     return 1;
                   3162: 
                   3163: }
                   3164: &register_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
1.229     foxr     3165: 
                   3166: #
                   3167: #   Unsubscribe from a resource.
                   3168: #
                   3169: # Parameters:
                   3170: #    $cmd      - The command that got us here.
                   3171: #    $tail     - Tail of the command (remaining parameters).
                   3172: #    $client   - File descriptor connected to client.
                   3173: # Returns
                   3174: #     0        - Requested to exit, caller should shut down.
                   3175: #     1        - Continue processing.
                   3176: #
                   3177: sub unsubscribe_handler {
                   3178:     my ($cmd, $tail, $client) = @_;
                   3179: 
                   3180:     my $userinput= "$cmd:$tail";
                   3181:     
                   3182:     my ($fname) = split(/:/,$tail); # Split in case there's extrs.
                   3183: 
                   3184:     &Debug("Unsubscribing $fname");
                   3185:     if (-e $fname) {
                   3186: 	&Debug("Exists");
                   3187: 	&Reply($client, &unsub($fname,$clientip), $userinput);
                   3188:     } else {
                   3189: 	&Failure($client, "not_found\n", $userinput);
                   3190:     }
                   3191:     return 1;
                   3192: }
                   3193: &register_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
1.263     albertel 3194: 
1.230     foxr     3195: #   Subscribe to a resource
                   3196: #
                   3197: # Parameters:
                   3198: #    $cmd      - The command that got us here.
                   3199: #    $tail     - Tail of the command (remaining parameters).
                   3200: #    $client   - File descriptor connected to client.
                   3201: # Returns
                   3202: #     0        - Requested to exit, caller should shut down.
                   3203: #     1        - Continue processing.
                   3204: #
                   3205: sub subscribe_handler {
                   3206:     my ($cmd, $tail, $client)= @_;
                   3207: 
                   3208:     my $userinput  = "$cmd:$tail";
                   3209: 
                   3210:     &Reply( $client, &subscribe($userinput,$clientip), $userinput);
                   3211: 
                   3212:     return 1;
                   3213: }
                   3214: &register_handler("sub", \&subscribe_handler, 0, 1, 0);
                   3215: 
                   3216: #
1.379     albertel 3217: #   Determine the latest version of a resource (it looks for the highest
                   3218: #   past version and then returns that +1)
1.230     foxr     3219: #
                   3220: # Parameters:
                   3221: #    $cmd      - The command that got us here.
                   3222: #    $tail     - Tail of the command (remaining parameters).
1.379     albertel 3223: #                 (Should consist of an absolute path to a file)
1.230     foxr     3224: #    $client   - File descriptor connected to client.
                   3225: # Returns
                   3226: #     0        - Requested to exit, caller should shut down.
                   3227: #     1        - Continue processing.
                   3228: #
                   3229: sub current_version_handler {
                   3230:     my ($cmd, $tail, $client) = @_;
                   3231: 
                   3232:     my $userinput= "$cmd:$tail";
                   3233:    
                   3234:     my $fname   = $tail;
                   3235:     &Reply( $client, &currentversion($fname)."\n", $userinput);
                   3236:     return 1;
                   3237: 
                   3238: }
                   3239: &register_handler("currentversion", \&current_version_handler, 0, 1, 0);
                   3240: 
                   3241: #  Make an entry in a user's activity log.
                   3242: #
                   3243: # Parameters:
                   3244: #    $cmd      - The command that got us here.
                   3245: #    $tail     - Tail of the command (remaining parameters).
                   3246: #    $client   - File descriptor connected to client.
                   3247: # Returns
                   3248: #     0        - Requested to exit, caller should shut down.
                   3249: #     1        - Continue processing.
                   3250: #
                   3251: sub activity_log_handler {
                   3252:     my ($cmd, $tail, $client) = @_;
                   3253: 
                   3254: 
                   3255:     my $userinput= "$cmd:$tail";
                   3256: 
                   3257:     my ($udom,$uname,$what)=split(/:/,$tail);
                   3258:     chomp($what);
                   3259:     my $proname=&propath($udom,$uname);
                   3260:     my $now=time;
                   3261:     my $hfh;
                   3262:     if ($hfh=IO::File->new(">>$proname/activity.log")) { 
                   3263: 	print $hfh "$now:$clientname:$what\n";
                   3264: 	&Reply( $client, "ok\n", $userinput); 
                   3265:     } else {
                   3266: 	&Failure($client, "error: ".($!+0)." IO::File->new Failed "
                   3267: 		 ."while attempting log\n", 
                   3268: 		 $userinput);
                   3269:     }
                   3270: 
                   3271:     return 1;
                   3272: }
1.263     albertel 3273: &register_handler("log", \&activity_log_handler, 0, 1, 0);
1.230     foxr     3274: 
                   3275: #
                   3276: #   Put a namespace entry in a user profile hash.
                   3277: #   My druthers would be for this to be an encrypted interaction too.
                   3278: #   anything that might be an inadvertent covert channel about either
                   3279: #   user authentication or user personal information....
                   3280: #
                   3281: # Parameters:
                   3282: #    $cmd      - The command that got us here.
                   3283: #    $tail     - Tail of the command (remaining parameters).
                   3284: #    $client   - File descriptor connected to client.
                   3285: # Returns
                   3286: #     0        - Requested to exit, caller should shut down.
                   3287: #     1        - Continue processing.
                   3288: #
                   3289: sub put_user_profile_entry {
                   3290:     my ($cmd, $tail, $client)  = @_;
1.229     foxr     3291: 
1.230     foxr     3292:     my $userinput = "$cmd:$tail";
                   3293:     
1.242     raeburn  3294:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
1.230     foxr     3295:     if ($namespace ne 'roles') {
                   3296: 	chomp($what);
                   3297: 	my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3298: 				  &GDBM_WRCREAT(),"P",$what);
                   3299: 	if($hashref) {
                   3300: 	    my @pairs=split(/\&/,$what);
                   3301: 	    foreach my $pair (@pairs) {
                   3302: 		my ($key,$value)=split(/=/,$pair);
                   3303: 		$hashref->{$key}=$value;
                   3304: 	    }
1.311     albertel 3305: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     3306: 		&Reply( $client, "ok\n", $userinput);
                   3307: 	    } else {
                   3308: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3309: 			"while attempting put\n", 
                   3310: 			$userinput);
                   3311: 	    }
                   3312: 	} else {
1.316     albertel 3313: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.230     foxr     3314: 		     "while attempting put\n", $userinput);
                   3315: 	}
                   3316:     } else {
                   3317:         &Failure( $client, "refused\n", $userinput);
                   3318:     }
                   3319:     
                   3320:     return 1;
                   3321: }
                   3322: &register_handler("put", \&put_user_profile_entry, 0, 1, 0);
                   3323: 
1.283     albertel 3324: #   Put a piece of new data in hash, returns error if entry already exists
                   3325: # Parameters:
                   3326: #    $cmd      - The command that got us here.
                   3327: #    $tail     - Tail of the command (remaining parameters).
                   3328: #    $client   - File descriptor connected to client.
                   3329: # Returns
                   3330: #     0        - Requested to exit, caller should shut down.
                   3331: #     1        - Continue processing.
                   3332: #
                   3333: sub newput_user_profile_entry {
                   3334:     my ($cmd, $tail, $client)  = @_;
                   3335: 
                   3336:     my $userinput = "$cmd:$tail";
                   3337: 
                   3338:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
                   3339:     if ($namespace eq 'roles') {
                   3340:         &Failure( $client, "refused\n", $userinput);
                   3341: 	return 1;
                   3342:     }
                   3343: 
                   3344:     chomp($what);
                   3345: 
                   3346:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3347: 				 &GDBM_WRCREAT(),"N",$what);
                   3348:     if(!$hashref) {
1.316     albertel 3349: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.283     albertel 3350: 		  "while attempting put\n", $userinput);
                   3351: 	return 1;
                   3352:     }
                   3353: 
                   3354:     my @pairs=split(/\&/,$what);
                   3355:     foreach my $pair (@pairs) {
                   3356: 	my ($key,$value)=split(/=/,$pair);
                   3357: 	if (exists($hashref->{$key})) {
1.513     raeburn  3358:             if (!&untie_user_hash($hashref)) {
                   3359:                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
                   3360:                          "while attempting newput - early out as key exists");
                   3361:             }
                   3362:             &Failure($client, "key_exists: ".$key."\n",$userinput);
                   3363:             return 1;
1.283     albertel 3364: 	}
                   3365:     }
                   3366: 
                   3367:     foreach my $pair (@pairs) {
                   3368: 	my ($key,$value)=split(/=/,$pair);
                   3369: 	$hashref->{$key}=$value;
                   3370:     }
                   3371: 
1.311     albertel 3372:     if (&untie_user_hash($hashref)) {
1.283     albertel 3373: 	&Reply( $client, "ok\n", $userinput);
                   3374:     } else {
                   3375: 	&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3376: 		 "while attempting put\n", 
                   3377: 		 $userinput);
                   3378:     }
                   3379:     return 1;
                   3380: }
                   3381: &register_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
                   3382: 
1.230     foxr     3383: # 
                   3384: #   Increment a profile entry in the user history file.
                   3385: #   The history contains keyword value pairs.  In this case,
                   3386: #   The value itself is a pair of numbers.  The first, the current value
                   3387: #   the second an increment that this function applies to the current
                   3388: #   value.
                   3389: #
                   3390: # Parameters:
                   3391: #    $cmd      - The command that got us here.
                   3392: #    $tail     - Tail of the command (remaining parameters).
                   3393: #    $client   - File descriptor connected to client.
                   3394: # Returns
                   3395: #     0        - Requested to exit, caller should shut down.
                   3396: #     1        - Continue processing.
                   3397: #
                   3398: sub increment_user_value_handler {
                   3399:     my ($cmd, $tail, $client) = @_;
                   3400:     
                   3401:     my $userinput   = "$cmd:$tail";
                   3402:     
                   3403:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
                   3404:     if ($namespace ne 'roles') {
                   3405:         chomp($what);
                   3406: 	my $hashref = &tie_user_hash($udom, $uname,
                   3407: 				     $namespace, &GDBM_WRCREAT(),
                   3408: 				     "P",$what);
                   3409: 	if ($hashref) {
                   3410: 	    my @pairs=split(/\&/,$what);
                   3411: 	    foreach my $pair (@pairs) {
                   3412: 		my ($key,$value)=split(/=/,$pair);
1.284     raeburn  3413:                 $value = &unescape($value);
1.230     foxr     3414: 		# We could check that we have a number...
                   3415: 		if (! defined($value) || $value eq '') {
                   3416: 		    $value = 1;
                   3417: 		}
                   3418: 		$hashref->{$key}+=$value;
1.284     raeburn  3419:                 if ($namespace eq 'nohist_resourcetracker') {
                   3420:                     if ($hashref->{$key} < 0) {
                   3421:                         $hashref->{$key} = 0;
                   3422:                     }
                   3423:                 }
1.230     foxr     3424: 	    }
1.311     albertel 3425: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     3426: 		&Reply( $client, "ok\n", $userinput);
                   3427: 	    } else {
                   3428: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3429: 			 "while attempting inc\n", $userinput);
                   3430: 	    }
                   3431: 	} else {
                   3432: 	    &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3433: 		     "while attempting inc\n", $userinput);
                   3434: 	}
                   3435:     } else {
                   3436: 	&Failure($client, "refused\n", $userinput);
                   3437:     }
                   3438:     
                   3439:     return 1;
                   3440: }
                   3441: &register_handler("inc", \&increment_user_value_handler, 0, 1, 0);
                   3442: 
                   3443: #
                   3444: #   Put a new role for a user.  Roles are LonCAPA's packaging of permissions.
                   3445: #   Each 'role' a user has implies a set of permissions.  Adding a new role
                   3446: #   for a person grants the permissions packaged with that role
                   3447: #   to that user when the role is selected.
                   3448: #
                   3449: # Parameters:
                   3450: #    $cmd       - The command string (rolesput).
                   3451: #    $tail      - The remainder of the request line.  For rolesput this
                   3452: #                 consists of a colon separated list that contains:
                   3453: #                 The domain and user that is granting the role (logged).
                   3454: #                 The domain and user that is getting the role.
                   3455: #                 The roles being granted as a set of & separated pairs.
                   3456: #                 each pair a key value pair.
                   3457: #    $client    - File descriptor connected to the client.
                   3458: # Returns:
                   3459: #     0         - If the daemon should exit
                   3460: #     1         - To continue processing.
                   3461: #
                   3462: #
                   3463: sub roles_put_handler {
                   3464:     my ($cmd, $tail, $client) = @_;
                   3465: 
                   3466:     my $userinput  = "$cmd:$tail";
                   3467: 
                   3468:     my ( $exedom, $exeuser, $udom, $uname,  $what) = split(/:/,$tail);
                   3469:     
                   3470: 
                   3471:     my $namespace='roles';
                   3472:     chomp($what);
                   3473:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3474: 				 &GDBM_WRCREAT(), "P",
                   3475: 				 "$exedom:$exeuser:$what");
                   3476:     #
                   3477:     #  Log the attempt to set a role.  The {}'s here ensure that the file 
                   3478:     #  handle is open for the minimal amount of time.  Since the flush
                   3479:     #  is done on close this improves the chances the log will be an un-
                   3480:     #  corrupted ordered thing.
                   3481:     if ($hashref) {
1.261     foxr     3482: 	my $pass_entry = &get_auth_type($udom, $uname);
                   3483: 	my ($auth_type,$pwd)  = split(/:/, $pass_entry);
                   3484: 	$auth_type = $auth_type.":";
1.230     foxr     3485: 	my @pairs=split(/\&/,$what);
                   3486: 	foreach my $pair (@pairs) {
                   3487: 	    my ($key,$value)=split(/=/,$pair);
                   3488: 	    &manage_permissions($key, $udom, $uname,
1.260     foxr     3489: 			       $auth_type);
1.230     foxr     3490: 	    $hashref->{$key}=$value;
                   3491: 	}
1.311     albertel 3492: 	if (&untie_user_hash($hashref)) {
1.230     foxr     3493: 	    &Reply($client, "ok\n", $userinput);
                   3494: 	} else {
                   3495: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3496: 		     "while attempting rolesput\n", $userinput);
                   3497: 	}
                   3498:     } else {
                   3499: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3500: 		 "while attempting rolesput\n", $userinput);
                   3501:     }
                   3502:     return 1;
                   3503: }
                   3504: &register_handler("rolesput", \&roles_put_handler, 1,1,0);  # Encoded client only.
                   3505: 
                   3506: #
1.231     foxr     3507: #   Deletes (removes) a role for a user.   This is equivalent to removing
                   3508: #  a permissions package associated with the role from the user's profile.
                   3509: #
                   3510: # Parameters:
                   3511: #     $cmd                 - The command (rolesdel)
                   3512: #     $tail                - The remainder of the request line. This consists
                   3513: #                             of:
                   3514: #                             The domain and user requesting the change (logged)
                   3515: #                             The domain and user being changed.
                   3516: #                             The roles being revoked.  These are shipped to us
                   3517: #                             as a bunch of & separated role name keywords.
                   3518: #     $client              - The file handle open on the client.
                   3519: # Returns:
                   3520: #     1                    - Continue processing
                   3521: #     0                    - Exit.
                   3522: #
                   3523: sub roles_delete_handler {
                   3524:     my ($cmd, $tail, $client)  = @_;
                   3525: 
                   3526:     my $userinput    = "$cmd:$tail";
                   3527:    
                   3528:     my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
                   3529:     &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
                   3530: 	   "what = ".$what);
                   3531:     my $namespace='roles';
                   3532:     chomp($what);
                   3533:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3534: 				 &GDBM_WRCREAT(), "D",
                   3535: 				 "$exedom:$exeuser:$what");
                   3536:     
                   3537:     if ($hashref) {
                   3538: 	my @rolekeys=split(/\&/,$what);
                   3539: 	
                   3540: 	foreach my $key (@rolekeys) {
                   3541: 	    delete $hashref->{$key};
                   3542: 	}
1.315     albertel 3543: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3544: 	    &Reply($client, "ok\n", $userinput);
                   3545: 	} else {
                   3546: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3547: 		     "while attempting rolesdel\n", $userinput);
                   3548: 	}
                   3549:     } else {
                   3550:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3551: 		 "while attempting rolesdel\n", $userinput);
                   3552:     }
                   3553:     
                   3554:     return 1;
                   3555: }
                   3556: &register_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
                   3557: 
                   3558: # Unencrypted get from a user's profile database.  See 
                   3559: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
                   3560: # This function retrieves a keyed item from a specific named database in the
                   3561: # user's directory.
                   3562: #
                   3563: # Parameters:
                   3564: #   $cmd             - Command request keyword (get).
                   3565: #   $tail            - Tail of the command.  This is a colon separated list
                   3566: #                      consisting of the domain and username that uniquely
                   3567: #                      identifies the profile,
                   3568: #                      The 'namespace' which selects the gdbm file to 
                   3569: #                      do the lookup in, 
                   3570: #                      & separated list of keys to lookup.  Note that
                   3571: #                      the values are returned as an & separated list too.
                   3572: #   $client          - File descriptor open on the client.
                   3573: # Returns:
                   3574: #   1       - Continue processing.
                   3575: #   0       - Exit.
                   3576: #
                   3577: sub get_profile_entry {
                   3578:     my ($cmd, $tail, $client) = @_;
                   3579: 
                   3580:     my $userinput= "$cmd:$tail";
                   3581:    
                   3582:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   3583:     chomp($what);
1.255     foxr     3584: 
1.390     raeburn  3585: 
1.255     foxr     3586:     my $replystring = read_profile($udom, $uname, $namespace, $what);
                   3587:     my ($first) = split(/:/,$replystring);
                   3588:     if($first ne "error") {
1.387     albertel 3589: 	&Reply($client, \$replystring, $userinput);
1.231     foxr     3590:     } else {
1.255     foxr     3591: 	&Failure($client, $replystring." while attempting get\n", $userinput);
1.231     foxr     3592:     }
                   3593:     return 1;
1.255     foxr     3594: 
                   3595: 
1.231     foxr     3596: }
                   3597: &register_handler("get", \&get_profile_entry, 0,1,0);
                   3598: 
                   3599: #
                   3600: #  Process the encrypted get request.  Note that the request is sent
                   3601: #  in clear, but the reply is encrypted.  This is a small covert channel:
                   3602: #  information about the sensitive keys is given to the snooper.  Just not
                   3603: #  information about the values of the sensitive key.  Hmm if I wanted to
                   3604: #  know these I'd snoop for the egets. Get the profile item names from them
                   3605: #  and then issue a get for them since there's no enforcement of the
                   3606: #  requirement of an encrypted get for particular profile items.  If I
                   3607: #  were re-doing this, I'd force the request to be encrypted as well as the
                   3608: #  reply.  I'd also just enforce encrypted transactions for all gets since
                   3609: #  that would prevent any covert channel snooping.
                   3610: #
                   3611: #  Parameters:
                   3612: #     $cmd               - Command keyword of request (eget).
1.536     raeburn  3613: #     $tail              - Tail of the command.  See GetProfileEntry
                   3614: #                          for more information about this.
1.231     foxr     3615: #     $client            - File open on the client.
                   3616: #  Returns:
                   3617: #     1      - Continue processing
                   3618: #     0      - server should exit.
                   3619: sub get_profile_entry_encrypted {
                   3620:     my ($cmd, $tail, $client) = @_;
                   3621: 
                   3622:     my $userinput = "$cmd:$tail";
                   3623:    
1.339     albertel 3624:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
1.231     foxr     3625:     chomp($what);
1.255     foxr     3626:     my $qresult = read_profile($udom, $uname, $namespace, $what);
                   3627:     my ($first) = split(/:/, $qresult);
                   3628:     if($first ne "error") {
                   3629: 	
                   3630: 	if ($cipher) {
                   3631: 	    my $cmdlength=length($qresult);
                   3632: 	    $qresult.="         ";
                   3633: 	    my $encqresult='';
                   3634: 	    for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   3635: 		$encqresult.= unpack("H16", 
                   3636: 				     $cipher->encrypt(substr($qresult,
                   3637: 							     $encidx,
                   3638: 							     8)));
                   3639: 	    }
                   3640: 	    &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
                   3641: 	} else {
1.231     foxr     3642: 		&Failure( $client, "error:no_key\n", $userinput);
                   3643: 	    }
                   3644:     } else {
1.255     foxr     3645: 	&Failure($client, "$qresult while attempting eget\n", $userinput);
                   3646: 
1.231     foxr     3647:     }
                   3648:     
                   3649:     return 1;
                   3650: }
1.255     foxr     3651: &register_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
1.263     albertel 3652: 
1.231     foxr     3653: #
                   3654: #   Deletes a key in a user profile database.
                   3655: #   
                   3656: #   Parameters:
                   3657: #       $cmd                  - Command keyword (del).
                   3658: #       $tail                 - Command tail.  IN this case a colon
                   3659: #                               separated list containing:
                   3660: #                               The domain and user that identifies uniquely
                   3661: #                               the identity of the user.
                   3662: #                               The profile namespace (name of the profile
                   3663: #                               database file).
                   3664: #                               & separated list of keywords to delete.
                   3665: #       $client              - File open on client socket.
                   3666: # Returns:
                   3667: #     1   - Continue processing
                   3668: #     0   - Exit server.
                   3669: #
                   3670: #
                   3671: sub delete_profile_entry {
                   3672:     my ($cmd, $tail, $client) = @_;
                   3673: 
                   3674:     my $userinput = "cmd:$tail";
                   3675: 
                   3676:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   3677:     chomp($what);
                   3678:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3679: 				 &GDBM_WRCREAT(),
                   3680: 				 "D",$what);
                   3681:     if ($hashref) {
                   3682:         my @keys=split(/\&/,$what);
                   3683: 	foreach my $key (@keys) {
                   3684: 	    delete($hashref->{$key});
                   3685: 	}
1.315     albertel 3686: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3687: 	    &Reply($client, "ok\n", $userinput);
                   3688: 	} else {
                   3689: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3690: 		    "while attempting del\n", $userinput);
                   3691: 	}
                   3692:     } else {
                   3693: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3694: 		 "while attempting del\n", $userinput);
                   3695:     }
                   3696:     return 1;
                   3697: }
                   3698: &register_handler("del", \&delete_profile_entry, 0, 1, 0);
1.263     albertel 3699: 
1.231     foxr     3700: #
                   3701: #  List the set of keys that are defined in a profile database file.
                   3702: #  A successful reply from this will contain an & separated list of
                   3703: #  the keys. 
                   3704: # Parameters:
                   3705: #     $cmd              - Command request (keys).
                   3706: #     $tail             - Remainder of the request, a colon separated
                   3707: #                         list containing domain/user that identifies the
                   3708: #                         user being queried, and the database namespace
                   3709: #                         (database filename essentially).
                   3710: #     $client           - File open on the client.
                   3711: #  Returns:
                   3712: #    1    - Continue processing.
                   3713: #    0    - Exit the server.
                   3714: #
                   3715: sub get_profile_keys {
                   3716:     my ($cmd, $tail, $client) = @_;
                   3717: 
                   3718:     my $userinput = "$cmd:$tail";
                   3719: 
                   3720:     my ($udom,$uname,$namespace)=split(/:/,$tail);
                   3721:     my $qresult='';
                   3722:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3723: 				  &GDBM_READER());
                   3724:     if ($hashref) {
                   3725: 	foreach my $key (keys %$hashref) {
                   3726: 	    $qresult.="$key&";
                   3727: 	}
1.315     albertel 3728: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3729: 	    $qresult=~s/\&$//;
1.387     albertel 3730: 	    &Reply($client, \$qresult, $userinput);
1.231     foxr     3731: 	} else {
                   3732: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3733: 		    "while attempting keys\n", $userinput);
                   3734: 	}
                   3735:     } else {
                   3736: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3737: 		 "while attempting keys\n", $userinput);
                   3738:     }
                   3739:    
                   3740:     return 1;
                   3741: }
                   3742: &register_handler("keys", \&get_profile_keys, 0, 1, 0);
                   3743: 
                   3744: #
                   3745: #   Dump the contents of a user profile database.
                   3746: #   Note that this constitutes a very large covert channel too since
                   3747: #   the dump will return sensitive information that is not encrypted.
                   3748: #   The naive security assumption is that the session negotiation ensures
                   3749: #   our client is trusted and I don't believe that's assured at present.
                   3750: #   Sure want badly to go to ssl or tls.  Of course if my peer isn't really
                   3751: #   a LonCAPA node they could have negotiated an encryption key too so >sigh<.
                   3752: # 
                   3753: #  Parameters:
                   3754: #     $cmd           - The command request keyword (currentdump).
                   3755: #     $tail          - Remainder of the request, consisting of a colon
                   3756: #                      separated list that has the domain/username and
                   3757: #                      the namespace to dump (database file).
                   3758: #     $client        - file open on the remote client.
                   3759: # Returns:
                   3760: #     1    - Continue processing.
                   3761: #     0    - Exit the server.
                   3762: #
                   3763: sub dump_profile_database {
                   3764:     my ($cmd, $tail, $client) = @_;
                   3765: 
1.494     droeschl 3766:     my $res = LONCAPA::Lond::dump_profile_database($tail);
                   3767: 
                   3768:     if ($res =~ /^error:/) {
                   3769:         Failure($client, \$res, "$cmd:$tail");
                   3770:     } else {
                   3771:         Reply($client, \$res, "$cmd:$tail");
                   3772:     }
                   3773: 
                   3774:     return 1;  
                   3775: 
                   3776:     #TODO remove 
1.231     foxr     3777:     my $userinput = "$cmd:$tail";
                   3778:    
                   3779:     my ($udom,$uname,$namespace) = split(/:/,$tail);
                   3780:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3781: 				 &GDBM_READER());
                   3782:     if ($hashref) {
                   3783: 	# Structure of %data:
                   3784: 	# $data{$symb}->{$parameter}=$value;
                   3785: 	# $data{$symb}->{'v.'.$parameter}=$version;
                   3786: 	# since $parameter will be unescaped, we do not
                   3787:  	# have to worry about silly parameter names...
                   3788: 	
                   3789:         my $qresult='';
                   3790: 	my %data = ();                     # A hash of anonymous hashes..
                   3791: 	while (my ($key,$value) = each(%$hashref)) {
                   3792: 	    my ($v,$symb,$param) = split(/:/,$key);
                   3793: 	    next if ($v eq 'version' || $symb eq 'keys');
                   3794: 	    next if (exists($data{$symb}) && 
                   3795: 		     exists($data{$symb}->{$param}) &&
                   3796: 		     $data{$symb}->{'v.'.$param} > $v);
                   3797: 	    $data{$symb}->{$param}=$value;
                   3798: 	    $data{$symb}->{'v.'.$param}=$v;
                   3799: 	}
1.311     albertel 3800: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3801: 	    while (my ($symb,$param_hash) = each(%data)) {
                   3802: 		while(my ($param,$value) = each (%$param_hash)){
                   3803: 		    next if ($param =~ /^v\./);       # Ignore versions...
                   3804: 		    #
                   3805: 		    #   Just dump the symb=value pairs separated by &
                   3806: 		    #
                   3807: 		    $qresult.=$symb.':'.$param.'='.$value.'&';
                   3808: 		}
                   3809: 	    }
                   3810: 	    chop($qresult);
1.387     albertel 3811: 	    &Reply($client , \$qresult, $userinput);
1.231     foxr     3812: 	} else {
                   3813: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3814: 		     "while attempting currentdump\n", $userinput);
                   3815: 	}
                   3816:     } else {
                   3817: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3818: 		"while attempting currentdump\n", $userinput);
                   3819:     }
                   3820: 
                   3821:     return 1;
                   3822: }
                   3823: &register_handler("currentdump", \&dump_profile_database, 0, 1, 0);
                   3824: 
                   3825: #
                   3826: #   Dump a profile database with an optional regular expression
                   3827: #   to match against the keys.  In this dump, no effort is made
                   3828: #   to separate symb from version information. Presumably the
                   3829: #   databases that are dumped by this command are of a different
                   3830: #   structure.  Need to look at this and improve the documentation of
                   3831: #   both this and the currentdump handler.
                   3832: # Parameters:
                   3833: #    $cmd                     - The command keyword.
                   3834: #    $tail                    - All of the characters after the $cmd:
                   3835: #                               These are expected to be a colon
                   3836: #                               separated list containing:
                   3837: #                               domain/user - identifying the user.
                   3838: #                               namespace   - identifying the database.
                   3839: #                               regexp      - optional regular expression
                   3840: #                                             that is matched against
                   3841: #                                             database keywords to do
                   3842: #                                             selective dumps.
1.488     raeburn  3843: #                               range       - optional range of entries
                   3844: #                                             e.g., 10-20 would return the
                   3845: #                                             10th to 19th items, etc.  
1.231     foxr     3846: #   $client                   - Channel open on the client.
                   3847: # Returns:
                   3848: #    1    - Continue processing.
                   3849: # Side effects:
                   3850: #    response is written to $client.
                   3851: #
                   3852: sub dump_with_regexp {
                   3853:     my ($cmd, $tail, $client) = @_;
                   3854: 
1.494     droeschl 3855:     my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
1.490     droeschl 3856:     
                   3857:     if ($res =~ /^error:/) {
                   3858:         Failure($client, \$res, "$cmd:$tail");
                   3859:     } else {
                   3860:         Reply($client, \$res, "$cmd:$tail");
                   3861:     }
1.231     foxr     3862: 
                   3863:     return 1;
                   3864: }
                   3865: &register_handler("dump", \&dump_with_regexp, 0, 1, 0);
                   3866: 
1.568     raeburn  3867: #
                   3868: #  Process the encrypted dump request. Original call should
                   3869: #  be from lonnet::dump() with seventh arg ($encrypt) set to
                   3870: #  1, to ensure that both request and response are encrypted.
                   3871: #
                   3872: #  Parameters:
                   3873: #     $cmd               - Command keyword of request (edump).
                   3874: #     $tail              - Tail of the command.
                   3875: #                          See &dump_with_regexp for more
                   3876: #                          information about this.
                   3877: #     $client            - File open on the client.
                   3878: #  Returns:
                   3879: #     1      - Continue processing
                   3880: #     0      - server should exit.
                   3881: #
                   3882: 
                   3883: sub encrypted_dump_with_regexp {
                   3884:     my ($cmd, $tail, $client) = @_;
                   3885:     my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
                   3886: 
                   3887:     if ($res =~ /^error:/) {
                   3888:         Failure($client, \$res, "$cmd:$tail");
                   3889:     } else {
                   3890:         if ($cipher) {
                   3891:             my $cmdlength=length($res);
                   3892:             $res.="         ";
                   3893:             my $encres='';
                   3894:             for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   3895:                 $encres.= unpack("H16",
                   3896:                                  $cipher->encrypt(substr($res,
                   3897:                                                          $encidx,
                   3898:                                                          8)));
                   3899:             }
                   3900:             &Reply( $client,"enc:$cmdlength:$encres\n","$cmd:$tail");
                   3901:         } else {
                   3902:             &Failure( $client, "error:no_key\n","$cmd:$tail");
                   3903:         }
                   3904:     }
                   3905: }
                   3906: &register_handler("edump", \&encrypted_dump_with_regexp, 0, 1, 0);
                   3907: 
1.231     foxr     3908: #  Store a set of key=value pairs associated with a versioned name.
                   3909: #
                   3910: #  Parameters:
                   3911: #    $cmd                - Request command keyword.
                   3912: #    $tail               - Tail of the request.  This is a colon
                   3913: #                          separated list containing:
                   3914: #                          domain/user - User and authentication domain.
                   3915: #                          namespace   - Name of the database being modified
                   3916: #                          rid         - Resource keyword to modify.
                   3917: #                          what        - new value associated with rid.
1.512     raeburn  3918: #                          laststore   - (optional) version=timestamp
                   3919: #                                        for most recent transaction for rid
                   3920: #                                        in namespace, when cstore was called
1.231     foxr     3921: #
                   3922: #    $client             - Socket open on the client.
                   3923: #
                   3924: #
                   3925: #  Returns:
                   3926: #      1 (keep on processing).
                   3927: #  Side-Effects:
                   3928: #    Writes to the client
1.512     raeburn  3929: #    Successful storage will cause either 'ok', or, if $laststore was included
                   3930: #    in the tail of the request, and the version number for the last transaction
                   3931: #    is larger than the version in $laststore, delay:$numtrans , where $numtrans
                   3932: #    is the number of store evevnts recorded for rid in namespace since
                   3933: #    lonnet::store() was called by the client.
                   3934: #
1.231     foxr     3935: sub store_handler {
                   3936:     my ($cmd, $tail, $client) = @_;
                   3937:  
                   3938:     my $userinput = "$cmd:$tail";
1.512     raeburn  3939:     chomp($tail);
                   3940:     my ($udom,$uname,$namespace,$rid,$what,$laststore) =split(/:/,$tail);
1.231     foxr     3941:     if ($namespace ne 'roles') {
                   3942: 
                   3943: 	my @pairs=split(/\&/,$what);
                   3944: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
1.268     albertel 3945: 				       &GDBM_WRCREAT(), "S",
1.231     foxr     3946: 				       "$rid:$what");
                   3947: 	if ($hashref) {
                   3948: 	    my $now = time;
1.512     raeburn  3949:             my $numtrans;
                   3950:             if ($laststore) {
                   3951:                 my ($previousversion,$previoustime) = split(/\=/,$laststore);
                   3952:                 my ($lastversion,$lasttime) = (0,0);
                   3953:                 $lastversion = $hashref->{"version:$rid"};
                   3954:                 if ($lastversion) {
                   3955:                     $lasttime = $hashref->{"$lastversion:$rid:timestamp"};
                   3956:                 }
                   3957:                 if (($previousversion) && ($previousversion !~ /\D/)) {
                   3958:                     if (($lastversion > $previousversion) && ($lasttime >= $previoustime)) {
                   3959:                         $numtrans = $lastversion - $previousversion;
                   3960:                     }
                   3961:                 } elsif ($lastversion) {
                   3962:                     $numtrans = $lastversion;
                   3963:                 }
                   3964:                 if ($numtrans) {
                   3965:                     $numtrans =~ s/D//g;
                   3966:                 }
                   3967:             }
1.231     foxr     3968: 	    $hashref->{"version:$rid"}++;
                   3969: 	    my $version=$hashref->{"version:$rid"};
                   3970: 	    my $allkeys=''; 
                   3971: 	    foreach my $pair (@pairs) {
                   3972: 		my ($key,$value)=split(/=/,$pair);
                   3973: 		$allkeys.=$key.':';
                   3974: 		$hashref->{"$version:$rid:$key"}=$value;
                   3975: 	    }
                   3976: 	    $hashref->{"$version:$rid:timestamp"}=$now;
                   3977: 	    $allkeys.='timestamp';
                   3978: 	    $hashref->{"$version:keys:$rid"}=$allkeys;
1.311     albertel 3979: 	    if (&untie_user_hash($hashref)) {
1.512     raeburn  3980:                 my $msg = 'ok';
                   3981:                 if ($numtrans) {
                   3982:                     $msg = 'delay:'.$numtrans;
                   3983:                 }
                   3984: 		&Reply($client, "$msg\n", $userinput);
1.231     foxr     3985: 	    } else {
                   3986: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3987: 			"while attempting store\n", $userinput);
                   3988: 	    }
                   3989: 	} else {
                   3990: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3991: 		     "while attempting store\n", $userinput);
                   3992: 	}
                   3993:     } else {
                   3994: 	&Failure($client, "refused\n", $userinput);
                   3995:     }
                   3996: 
                   3997:     return 1;
                   3998: }
                   3999: &register_handler("store", \&store_handler, 0, 1, 0);
1.263     albertel 4000: 
1.323     albertel 4001: #  Modify a set of key=value pairs associated with a versioned name.
                   4002: #
                   4003: #  Parameters:
                   4004: #    $cmd                - Request command keyword.
                   4005: #    $tail               - Tail of the request.  This is a colon
                   4006: #                          separated list containing:
                   4007: #                          domain/user - User and authentication domain.
                   4008: #                          namespace   - Name of the database being modified
                   4009: #                          rid         - Resource keyword to modify.
                   4010: #                          v           - Version item to modify
                   4011: #                          what        - new value associated with rid.
                   4012: #
                   4013: #    $client             - Socket open on the client.
                   4014: #
                   4015: #
                   4016: #  Returns:
                   4017: #      1 (keep on processing).
                   4018: #  Side-Effects:
                   4019: #    Writes to the client
                   4020: sub putstore_handler {
                   4021:     my ($cmd, $tail, $client) = @_;
                   4022:  
                   4023:     my $userinput = "$cmd:$tail";
                   4024: 
                   4025:     my ($udom,$uname,$namespace,$rid,$v,$what) =split(/:/,$tail);
                   4026:     if ($namespace ne 'roles') {
                   4027: 
                   4028: 	chomp($what);
                   4029: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
                   4030: 				       &GDBM_WRCREAT(), "M",
                   4031: 				       "$rid:$v:$what");
                   4032: 	if ($hashref) {
                   4033: 	    my $now = time;
                   4034: 	    my %data = &hash_extract($what);
                   4035: 	    my @allkeys;
                   4036: 	    while (my($key,$value) = each(%data)) {
                   4037: 		push(@allkeys,$key);
                   4038: 		$hashref->{"$v:$rid:$key"} = $value;
                   4039: 	    }
                   4040: 	    my $allkeys = join(':',@allkeys);
                   4041: 	    $hashref->{"$v:keys:$rid"}=$allkeys;
                   4042: 
                   4043: 	    if (&untie_user_hash($hashref)) {
                   4044: 		&Reply($client, "ok\n", $userinput);
                   4045: 	    } else {
                   4046: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4047: 			"while attempting store\n", $userinput);
                   4048: 	    }
                   4049: 	} else {
                   4050: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4051: 		     "while attempting store\n", $userinput);
                   4052: 	}
                   4053:     } else {
                   4054: 	&Failure($client, "refused\n", $userinput);
                   4055:     }
                   4056: 
                   4057:     return 1;
                   4058: }
                   4059: &register_handler("putstore", \&putstore_handler, 0, 1, 0);
                   4060: 
                   4061: sub hash_extract {
                   4062:     my ($str)=@_;
                   4063:     my %hash;
                   4064:     foreach my $pair (split(/\&/,$str)) {
                   4065: 	my ($key,$value)=split(/=/,$pair);
                   4066: 	$hash{$key}=$value;
                   4067:     }
                   4068:     return (%hash);
                   4069: }
                   4070: sub hash_to_str {
                   4071:     my ($hash_ref)=@_;
                   4072:     my $str;
                   4073:     foreach my $key (keys(%$hash_ref)) {
                   4074: 	$str.=$key.'='.$hash_ref->{$key}.'&';
                   4075:     }
                   4076:     $str=~s/\&$//;
                   4077:     return $str;
                   4078: }
                   4079: 
1.231     foxr     4080: #
                   4081: #  Dump out all versions of a resource that has key=value pairs associated
                   4082: # with it for each version.  These resources are built up via the store
                   4083: # command.
                   4084: #
                   4085: #  Parameters:
                   4086: #     $cmd               - Command keyword.
                   4087: #     $tail              - Remainder of the request which consists of:
                   4088: #                          domain/user   - User and auth. domain.
                   4089: #                          namespace     - name of resource database.
                   4090: #                          rid           - Resource id.
                   4091: #    $client             - socket open on the client.
                   4092: #
                   4093: # Returns:
                   4094: #      1  indicating the caller should not yet exit.
                   4095: # Side-effects:
                   4096: #   Writes a reply to the client.
                   4097: #   The reply is a string of the following shape:
                   4098: #   version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
                   4099: #    Where the 1 above represents version 1.
                   4100: #    this continues for all pairs of keys in all versions.
                   4101: #
                   4102: #
                   4103: #    
                   4104: #
                   4105: sub restore_handler {
                   4106:     my ($cmd, $tail, $client) = @_;
                   4107: 
                   4108:     my $userinput = "$cmd:$tail";	# Only used for logging purposes.
1.351     banghart 4109:     my ($udom,$uname,$namespace,$rid) = split(/:/,$tail);
1.352     albertel 4110:     $namespace=~s/\//\_/g;
1.350     albertel 4111:     $namespace = &LONCAPA::clean_username($namespace);
1.349     albertel 4112: 
1.231     foxr     4113:     chomp($rid);
                   4114:     my $qresult='';
1.309     albertel 4115:     my $hashref = &tie_user_hash($udom, $uname, $namespace, &GDBM_READER());
                   4116:     if ($hashref) {
                   4117: 	my $version=$hashref->{"version:$rid"};
1.231     foxr     4118: 	$qresult.="version=$version&";
                   4119: 	my $scope;
                   4120: 	for ($scope=1;$scope<=$version;$scope++) {
1.309     albertel 4121: 	    my $vkeys=$hashref->{"$scope:keys:$rid"};
1.231     foxr     4122: 	    my @keys=split(/:/,$vkeys);
                   4123: 	    my $key;
                   4124: 	    $qresult.="$scope:keys=$vkeys&";
                   4125: 	    foreach $key (@keys) {
1.309     albertel 4126: 		$qresult.="$scope:$key=".$hashref->{"$scope:$rid:$key"}."&";
1.231     foxr     4127: 	    }                                  
                   4128: 	}
1.311     albertel 4129: 	if (&untie_user_hash($hashref)) {
1.231     foxr     4130: 	    $qresult=~s/\&$//;
1.387     albertel 4131: 	    &Reply( $client, \$qresult, $userinput);
1.231     foxr     4132: 	} else {
                   4133: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4134: 		    "while attempting restore\n", $userinput);
                   4135: 	}
                   4136:     } else {
                   4137: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4138: 		"while attempting restore\n", $userinput);
                   4139:     }
                   4140:   
                   4141:     return 1;
                   4142: 
                   4143: 
                   4144: }
                   4145: &register_handler("restore", \&restore_handler, 0,1,0);
1.234     foxr     4146: 
                   4147: #
1.324     raeburn  4148: #   Add a chat message to a synchronous discussion board.
1.234     foxr     4149: #
                   4150: # Parameters:
                   4151: #    $cmd                - Request keyword.
                   4152: #    $tail               - Tail of the command. A colon separated list
                   4153: #                          containing:
                   4154: #                          cdom    - Domain on which the chat board lives
1.324     raeburn  4155: #                          cnum    - Course containing the chat board.
                   4156: #                          newpost - Body of the posting.
                   4157: #                          group   - Optional group, if chat board is only 
                   4158: #                                    accessible in a group within the course 
1.234     foxr     4159: #   $client              - Socket open on the client.
                   4160: # Returns:
                   4161: #   1    - Indicating caller should keep on processing.
                   4162: #
                   4163: # Side-effects:
                   4164: #   writes a reply to the client.
                   4165: #
                   4166: #
                   4167: sub send_chat_handler {
                   4168:     my ($cmd, $tail, $client) = @_;
                   4169: 
                   4170:     
                   4171:     my $userinput = "$cmd:$tail";
                   4172: 
1.324     raeburn  4173:     my ($cdom,$cnum,$newpost,$group)=split(/\:/,$tail);
                   4174:     &chat_add($cdom,$cnum,$newpost,$group);
1.234     foxr     4175:     &Reply($client, "ok\n", $userinput);
                   4176: 
                   4177:     return 1;
                   4178: }
                   4179: &register_handler("chatsend", \&send_chat_handler, 0, 1, 0);
1.263     albertel 4180: 
1.234     foxr     4181: #
1.324     raeburn  4182: #   Retrieve the set of chat messages from a discussion board.
1.234     foxr     4183: #
                   4184: #  Parameters:
                   4185: #    $cmd             - Command keyword that initiated the request.
                   4186: #    $tail            - Remainder of the request after the command
                   4187: #                       keyword.  In this case a colon separated list of
                   4188: #                       chat domain    - Which discussion board.
                   4189: #                       chat id        - Discussion thread(?)
                   4190: #                       domain/user    - Authentication domain and username
                   4191: #                                        of the requesting person.
1.324     raeburn  4192: #                       group          - Optional course group containing
                   4193: #                                        the board.      
1.234     foxr     4194: #   $client           - Socket open on the client program.
                   4195: # Returns:
                   4196: #    1     - continue processing
                   4197: # Side effects:
                   4198: #    Response is written to the client.
                   4199: #
                   4200: sub retrieve_chat_handler {
                   4201:     my ($cmd, $tail, $client) = @_;
                   4202: 
                   4203: 
                   4204:     my $userinput = "$cmd:$tail";
                   4205: 
1.324     raeburn  4206:     my ($cdom,$cnum,$udom,$uname,$group)=split(/\:/,$tail);
1.234     foxr     4207:     my $reply='';
1.324     raeburn  4208:     foreach (&get_chat($cdom,$cnum,$udom,$uname,$group)) {
1.234     foxr     4209: 	$reply.=&escape($_).':';
                   4210:     }
                   4211:     $reply=~s/\:$//;
1.387     albertel 4212:     &Reply($client, \$reply, $userinput);
1.234     foxr     4213: 
                   4214: 
                   4215:     return 1;
                   4216: }
                   4217: &register_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
                   4218: 
                   4219: #
                   4220: #  Initiate a query of an sql database.  SQL query repsonses get put in
                   4221: #  a file for later retrieval.  This prevents sql query results from
                   4222: #  bottlenecking the system.  Note that with loncnew, perhaps this is
                   4223: #  less of an issue since multiple outstanding requests can be concurrently
                   4224: #  serviced.
                   4225: #
                   4226: #  Parameters:
1.535     raeburn  4227: #     $cmd       - Command keyword that initiated the request.
1.234     foxr     4228: #     $tail      - Remainder of the command after the keyword.
                   4229: #                  For this function, this consists of a query and
                   4230: #                  3 arguments that are self-documentingly labelled
                   4231: #                  in the original arg1, arg2, arg3.
                   4232: #     $client    - Socket open on the client.
                   4233: # Return:
                   4234: #    1   - Indicating processing should continue.
                   4235: # Side-effects:
                   4236: #    a reply is written to $client.
                   4237: #
                   4238: sub send_query_handler {
                   4239:     my ($cmd, $tail, $client) = @_;
                   4240: 
                   4241:     my $userinput = "$cmd:$tail";
                   4242: 
                   4243:     my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
                   4244:     $query=~s/\n*$//g;
1.534     raeburn  4245:     if (($query eq 'usersearch') || ($query eq 'instdirsearch')) {
                   4246:         my $usersearchconf = &get_usersearch_config($currentdomainid,'directorysrch');
                   4247:         my $earlyout;
                   4248:         if (ref($usersearchconf) eq 'HASH') {
                   4249:             if ($currentdomainid eq $clienthomedom) {
                   4250:                 if ($query eq 'usersearch') {
                   4251:                     if ($usersearchconf->{'lcavailable'} eq '0') {
                   4252:                         $earlyout = 1;
                   4253:                     }
                   4254:                 } else {
                   4255:                     if ($usersearchconf->{'available'} eq '0') {
                   4256:                         $earlyout = 1;
                   4257:                     }
                   4258:                 }
                   4259:             } else {
                   4260:                 if ($query eq 'usersearch') {
                   4261:                     if ($usersearchconf->{'lclocalonly'}) {
                   4262:                         $earlyout = 1;
                   4263:                     }
                   4264:                 } else {
                   4265:                     if ($usersearchconf->{'localonly'}) {
                   4266:                         $earlyout = 1;
                   4267:                     }
                   4268:                 }
                   4269:             }
                   4270:         }
                   4271:         if ($earlyout) {
                   4272:             &Reply($client, "query_not_authorized\n");
                   4273:             return 1;
                   4274:         }
                   4275:     }
1.234     foxr     4276:     &Reply($client, "". &sql_reply("$clientname\&$query".
                   4277: 				"\&$arg1"."\&$arg2"."\&$arg3")."\n",
                   4278: 	  $userinput);
                   4279:     
                   4280:     return 1;
                   4281: }
                   4282: &register_handler("querysend", \&send_query_handler, 0, 1, 0);
                   4283: 
                   4284: #
                   4285: #   Add a reply to an sql query.  SQL queries are done asyncrhonously.
                   4286: #   The query is submitted via a "querysend" transaction.
                   4287: #   There it is passed on to the lonsql daemon, queued and issued to
                   4288: #   mysql.
                   4289: #     This transaction is invoked when the sql transaction is complete
                   4290: #   it stores the query results in flie and indicates query completion.
                   4291: #   presumably local software then fetches this response... I'm guessing
                   4292: #   the sequence is: lonc does a querysend, we ask lonsql to do it.
                   4293: #   lonsql on completion of the query interacts with the lond of our
                   4294: #   client to do a query reply storing two files:
                   4295: #    - id     - The results of the query.
                   4296: #    - id.end - Indicating the transaction completed. 
                   4297: #    NOTE: id is a unique id assigned to the query and querysend time.
                   4298: # Parameters:
                   4299: #    $cmd        - Command keyword that initiated this request.
                   4300: #    $tail       - Remainder of the tail.  In this case that's a colon
                   4301: #                  separated list containing the query Id and the 
                   4302: #                  results of the query.
                   4303: #    $client     - Socket open on the client.
                   4304: # Return:
                   4305: #    1           - Indicating that we should continue processing.
                   4306: # Side effects:
                   4307: #    ok written to the client.
                   4308: #
                   4309: sub reply_query_handler {
                   4310:     my ($cmd, $tail, $client) = @_;
                   4311: 
                   4312: 
                   4313:     my $userinput = "$cmd:$tail";
                   4314: 
1.339     albertel 4315:     my ($id,$reply)=split(/:/,$tail); 
1.234     foxr     4316:     my $store;
                   4317:     my $execdir=$perlvar{'lonDaemons'};
                   4318:     if ($store=IO::File->new(">$execdir/tmp/$id")) {
                   4319: 	$reply=~s/\&/\n/g;
                   4320: 	print $store $reply;
                   4321: 	close $store;
                   4322: 	my $store2=IO::File->new(">$execdir/tmp/$id.end");
                   4323: 	print $store2 "done\n";
                   4324: 	close $store2;
                   4325: 	&Reply($client, "ok\n", $userinput);
                   4326:     } else {
                   4327: 	&Failure($client, "error: ".($!+0)
                   4328: 		." IO::File->new Failed ".
                   4329: 		"while attempting queryreply\n", $userinput);
                   4330:     }
                   4331:  
                   4332: 
                   4333:     return 1;
                   4334: }
                   4335: &register_handler("queryreply", \&reply_query_handler, 0, 1, 0);
                   4336: 
                   4337: #
                   4338: #  Process the courseidput request.  Not quite sure what this means
                   4339: #  at the system level sense.  It appears a gdbm file in the 
                   4340: #  /home/httpd/lonUsers/$domain/nohist_courseids is tied and
                   4341: #  a set of entries made in that database.
                   4342: #
                   4343: # Parameters:
                   4344: #   $cmd      - The command keyword that initiated this request.
                   4345: #   $tail     - Tail of the command.  In this case consists of a colon
                   4346: #               separated list contaning the domain to apply this to and
                   4347: #               an ampersand separated list of keyword=value pairs.
1.272     raeburn  4348: #               Each value is a colon separated list that includes:  
                   4349: #               description, institutional code and course owner.
                   4350: #               For backward compatibility with versions included
                   4351: #               in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
                   4352: #               code and/or course owner are preserved from the existing 
                   4353: #               record when writing a new record in response to 1.1 or 
                   4354: #               1.2 implementations of lonnet::flushcourselogs().   
                   4355: #                      
1.234     foxr     4356: #   $client   - Socket open on the client.
                   4357: # Returns:
                   4358: #   1    - indicating that processing should continue
                   4359: #
                   4360: # Side effects:
                   4361: #   reply is written to the client.
                   4362: #
                   4363: sub put_course_id_handler {
                   4364:     my ($cmd, $tail, $client) = @_;
                   4365: 
                   4366: 
                   4367:     my $userinput = "$cmd:$tail";
                   4368: 
1.266     raeburn  4369:     my ($udom, $what) = split(/:/, $tail,2);
1.234     foxr     4370:     chomp($what);
                   4371:     my $now=time;
                   4372:     my @pairs=split(/\&/,$what);
                   4373: 
                   4374:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   4375:     if ($hashref) {
                   4376: 	foreach my $pair (@pairs) {
1.271     raeburn  4377:             my ($key,$courseinfo) = split(/=/,$pair,2);
                   4378:             $courseinfo =~ s/=/:/g;
1.384     raeburn  4379:             if (defined($hashref->{$key})) {
                   4380:                 my $value = &Apache::lonnet::thaw_unescape($hashref->{$key});
                   4381:                 if (ref($value) eq 'HASH') {
                   4382:                     my @items = ('description','inst_code','owner','type');
                   4383:                     my @new_items = split(/:/,$courseinfo,-1);
                   4384:                     my %storehash; 
                   4385:                     for (my $i=0; $i<@new_items; $i++) {
1.391     raeburn  4386:                         $storehash{$items[$i]} = &unescape($new_items[$i]);
1.384     raeburn  4387:                     }
                   4388:                     $hashref->{$key} = 
                   4389:                         &Apache::lonnet::freeze_escape(\%storehash);
                   4390:                     my $unesc_key = &unescape($key);
                   4391:                     $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
                   4392:                     next;
1.383     raeburn  4393:                 }
1.384     raeburn  4394:             }
                   4395:             my @current_items = split(/:/,$hashref->{$key},-1);
                   4396:             shift(@current_items); # remove description
                   4397:             pop(@current_items);   # remove last access
                   4398:             my $numcurrent = scalar(@current_items);
                   4399:             if ($numcurrent > 3) {
                   4400:                 $numcurrent = 3;
                   4401:             }
                   4402:             my @new_items = split(/:/,$courseinfo,-1);
                   4403:             my $numnew = scalar(@new_items);
                   4404:             if ($numcurrent > 0) {
                   4405:                 if ($numnew <= $numcurrent) { # flushcourselogs() from pre 2.2 
                   4406:                     for (my $j=$numcurrent-$numnew; $j>=0; $j--) {
                   4407:                         $courseinfo .= ':'.$current_items[$numcurrent-$j-1];
1.333     raeburn  4408:                     }
1.272     raeburn  4409:                 }
                   4410:             }
1.384     raeburn  4411:             $hashref->{$key}=$courseinfo.':'.$now;
1.234     foxr     4412: 	}
1.311     albertel 4413: 	if (&untie_domain_hash($hashref)) {
1.253     foxr     4414: 	    &Reply( $client, "ok\n", $userinput);
1.234     foxr     4415: 	} else {
1.253     foxr     4416: 	    &Failure($client, "error: ".($!+0)
1.234     foxr     4417: 		     ." untie(GDBM) Failed ".
                   4418: 		     "while attempting courseidput\n", $userinput);
                   4419: 	}
                   4420:     } else {
1.253     foxr     4421: 	&Failure($client, "error: ".($!+0)
1.234     foxr     4422: 		 ." tie(GDBM) Failed ".
                   4423: 		 "while attempting courseidput\n", $userinput);
                   4424:     }
                   4425: 
                   4426:     return 1;
                   4427: }
                   4428: &register_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
                   4429: 
1.383     raeburn  4430: sub put_course_id_hash_handler {
                   4431:     my ($cmd, $tail, $client) = @_;
                   4432:     my $userinput = "$cmd:$tail";
1.384     raeburn  4433:     my ($udom,$mode,$what) = split(/:/, $tail,3);
1.383     raeburn  4434:     chomp($what);
                   4435:     my $now=time;
                   4436:     my @pairs=split(/\&/,$what);
1.384     raeburn  4437:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
1.383     raeburn  4438:     if ($hashref) {
                   4439:         foreach my $pair (@pairs) {
                   4440:             my ($key,$value)=split(/=/,$pair);
1.384     raeburn  4441:             my $unesc_key = &unescape($key);
                   4442:             if ($mode ne 'timeonly') {
                   4443:                 if (!defined($hashref->{&escape('lasttime:'.$unesc_key)})) {
                   4444:                     my $curritems = &Apache::lonnet::thaw_unescape($key); 
                   4445:                     if (ref($curritems) ne 'HASH') {
                   4446:                         my @current_items = split(/:/,$hashref->{$key},-1);
                   4447:                         my $lasttime = pop(@current_items);
                   4448:                         $hashref->{&escape('lasttime:'.$unesc_key)} = $lasttime;
                   4449:                     } else {
                   4450:                         $hashref->{&escape('lasttime:'.$unesc_key)} = '';
                   4451:                     }
                   4452:                 } 
                   4453:                 $hashref->{$key} = $value;
                   4454:             }
                   4455:             if ($mode ne 'notime') {
                   4456:                 $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
                   4457:             }
1.383     raeburn  4458:         }
                   4459:         if (&untie_domain_hash($hashref)) {
                   4460:             &Reply($client, "ok\n", $userinput);
                   4461:         } else {
                   4462:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4463:                      "while attempting courseidputhash\n", $userinput);
                   4464:         }
                   4465:     } else {
                   4466:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4467:                   "while attempting courseidputhash\n", $userinput);
                   4468:     }
                   4469:     return 1;
                   4470: }
                   4471: &register_handler("courseidputhash", \&put_course_id_hash_handler, 0, 1, 0);
                   4472: 
1.234     foxr     4473: #  Retrieves the value of a course id resource keyword pattern
                   4474: #  defined since a starting date.  Both the starting date and the
                   4475: #  keyword pattern are optional.  If the starting date is not supplied it
                   4476: #  is treated as the beginning of time.  If the pattern is not found,
                   4477: #  it is treatred as "." matching everything.
                   4478: #
                   4479: #  Parameters:
                   4480: #     $cmd     - Command keyword that resulted in us being dispatched.
                   4481: #     $tail    - The remainder of the command that, in this case, consists
                   4482: #                of a colon separated list of:
                   4483: #                 domain   - The domain in which the course database is 
                   4484: #                            defined.
                   4485: #                 since    - Optional parameter describing the minimum
                   4486: #                            time of definition(?) of the resources that
                   4487: #                            will match the dump.
                   4488: #                 description - regular expression that is used to filter
                   4489: #                            the dump.  Only keywords matching this regexp
                   4490: #                            will be used.
1.272     raeburn  4491: #                 institutional code - optional supplied code to filter 
                   4492: #                            the dump. Only courses with an institutional code 
                   4493: #                            that match the supplied code will be returned.
1.336     raeburn  4494: #                 owner    - optional supplied username and domain of owner to
                   4495: #                            filter the dump.  Only courses for which the course
                   4496: #                            owner matches the supplied username and/or domain
                   4497: #                            will be returned. Pre-2.2.0 legacy entries from 
                   4498: #                            nohist_courseiddump will only contain usernames.
1.384     raeburn  4499: #                 type     - optional parameter for selection 
1.418     raeburn  4500: #                 regexp_ok - if 1 or -1 allow the supplied institutional code
                   4501: #                            filter to behave as a regular expression:
                   4502: #	                      1 will not exclude the course if the instcode matches the RE 
                   4503: #                            -1 will exclude the course if the instcode matches the RE
1.384     raeburn  4504: #                 rtn_as_hash - whether to return the information available for
                   4505: #                            each matched item as a frozen hash of all 
                   4506: #                            key, value pairs in the item's hash, or as a 
                   4507: #                            colon-separated list of (in order) description,
                   4508: #                            institutional code, and course owner.
1.404     raeburn  4509: #                 selfenrollonly - filter by courses allowing self-enrollment  
                   4510: #                                  now or in the future (selfenrollonly = 1).
                   4511: #                 catfilter - filter by course category, assigned to a course 
                   4512: #                             using manually defined categories (i.e., not
1.407     raeburn  4513: #                             self-cataloging based on on institutional code).   
1.404     raeburn  4514: #                 showhidden - include course in results even if course  
1.407     raeburn  4515: #                              was set to be excluded from course catalog (DC only).
1.404     raeburn  4516: #                 caller -  if set to 'coursecatalog', courses set to be hidden
                   4517: #                           from course catalog will be excluded from results (unless
                   4518: #                           overridden by "showhidden".
1.427     raeburn  4519: #                 cloner - escaped username:domain of course cloner (if picking course to
1.419     raeburn  4520: #                          clone).
                   4521: #                 cc_clone_list - escaped comma separated list of courses for which 
                   4522: #                                 course cloner has active CC role (and so can clone
                   4523: #                                 automatically).
1.427     raeburn  4524: #                 cloneonly - filter by courses for which cloner has rights to clone.
                   4525: #                 createdbefore - include courses for which creation date preceeded this date.
                   4526: #                 createdafter - include courses for which creation date followed this date.
                   4527: #                 creationcontext - include courses created in specified context 
1.404     raeburn  4528: #
1.445     raeburn  4529: #                 domcloner - flag to indicate if user can create CCs in course's domain.
1.505     raeburn  4530: #                             If so, ability to clone course is automatic.
                   4531: #                 hasuniquecode - filter by courses for which a six character unique code has 
                   4532: #                                 been set.
1.445     raeburn  4533: #
1.234     foxr     4534: #     $client  - The socket open on the client.
                   4535: # Returns:
                   4536: #    1     - Continue processing.
                   4537: # Side Effects:
                   4538: #   a reply is written to $client.
                   4539: sub dump_course_id_handler {
                   4540:     my ($cmd, $tail, $client) = @_;
1.494     droeschl 4541: 
                   4542:     my $res = LONCAPA::Lond::dump_course_id_handler($tail);
                   4543:     if ($res =~ /^error:/) {
                   4544:         Failure($client, \$res, "$cmd:$tail");
                   4545:     } else {
                   4546:         Reply($client, \$res, "$cmd:$tail");
                   4547:     }
                   4548: 
                   4549:     return 1;  
                   4550: 
                   4551:     #TODO remove
1.234     foxr     4552:     my $userinput = "$cmd:$tail";
                   4553: 
1.333     raeburn  4554:     my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter,
1.404     raeburn  4555:         $typefilter,$regexp_ok,$rtn_as_hash,$selfenrollonly,$catfilter,$showhidden,
1.427     raeburn  4556:         $caller,$cloner,$cc_clone_list,$cloneonly,$createdbefore,$createdafter,
1.505     raeburn  4557:         $creationcontext,$domcloner,$hasuniquecode) =split(/:/,$tail);
1.397     raeburn  4558:     my $now = time;
1.419     raeburn  4559:     my ($cloneruname,$clonerudom,%cc_clone);
1.234     foxr     4560:     if (defined($description)) {
                   4561: 	$description=&unescape($description);
                   4562:     } else {
                   4563: 	$description='.';
                   4564:     }
1.266     raeburn  4565:     if (defined($instcodefilter)) {
                   4566:         $instcodefilter=&unescape($instcodefilter);
                   4567:     } else {
                   4568:         $instcodefilter='.';
                   4569:     }
1.336     raeburn  4570:     my ($ownerunamefilter,$ownerdomfilter);
1.266     raeburn  4571:     if (defined($ownerfilter)) {
                   4572:         $ownerfilter=&unescape($ownerfilter);
1.336     raeburn  4573:         if ($ownerfilter ne '.' && defined($ownerfilter)) {
                   4574:             if ($ownerfilter =~ /^([^:]*):([^:]*)$/) {
                   4575:                  $ownerunamefilter = $1;
                   4576:                  $ownerdomfilter = $2;
                   4577:             } else {
                   4578:                 $ownerunamefilter = $ownerfilter;
                   4579:                 $ownerdomfilter = '';
                   4580:             }
                   4581:         }
1.266     raeburn  4582:     } else {
                   4583:         $ownerfilter='.';
                   4584:     }
1.336     raeburn  4585: 
1.282     raeburn  4586:     if (defined($coursefilter)) {
                   4587:         $coursefilter=&unescape($coursefilter);
                   4588:     } else {
                   4589:         $coursefilter='.';
                   4590:     }
1.333     raeburn  4591:     if (defined($typefilter)) {
                   4592:         $typefilter=&unescape($typefilter);
                   4593:     } else {
                   4594:         $typefilter='.';
                   4595:     }
1.344     raeburn  4596:     if (defined($regexp_ok)) {
                   4597:         $regexp_ok=&unescape($regexp_ok);
                   4598:     }
1.401     raeburn  4599:     if (defined($catfilter)) {
                   4600:         $catfilter=&unescape($catfilter);
                   4601:     }
1.419     raeburn  4602:     if (defined($cloner)) {
                   4603:         $cloner = &unescape($cloner);
                   4604:         ($cloneruname,$clonerudom) = ($cloner =~ /^($LONCAPA::match_username):($LONCAPA::match_domain)$/); 
                   4605:     }
                   4606:     if (defined($cc_clone_list)) {
                   4607:         $cc_clone_list = &unescape($cc_clone_list);
                   4608:         my @cc_cloners = split('&',$cc_clone_list);
                   4609:         foreach my $cid (@cc_cloners) {
                   4610:             my ($clonedom,$clonenum) = split(':',$cid);
                   4611:             next if ($clonedom ne $udom); 
                   4612:             $cc_clone{$clonedom.'_'.$clonenum} = 1;
                   4613:         } 
                   4614:     }
1.431     raeburn  4615:     if ($createdbefore ne '') {
1.427     raeburn  4616:         $createdbefore = &unescape($createdbefore);
                   4617:     } else {
                   4618:        $createdbefore = 0;
                   4619:     }
1.431     raeburn  4620:     if ($createdafter ne '') {
1.427     raeburn  4621:         $createdafter = &unescape($createdafter);
                   4622:     } else {
                   4623:         $createdafter = 0;
                   4624:     }
1.431     raeburn  4625:     if ($creationcontext ne '') {
1.427     raeburn  4626:         $creationcontext = &unescape($creationcontext);
                   4627:     } else {
                   4628:         $creationcontext = '.';
                   4629:     }
1.505     raeburn  4630:     unless ($hasuniquecode) {
                   4631:         $hasuniquecode = '.';
                   4632:     }
1.384     raeburn  4633:     my $unpack = 1;
1.485     raeburn  4634:     if ($description eq '.' && $instcodefilter eq '.' && $ownerfilter eq '.' && 
1.384     raeburn  4635:         $typefilter eq '.') {
                   4636:         $unpack = 0;
                   4637:     }
                   4638:     if (!defined($since)) { $since=0; }
1.234     foxr     4639:     my $qresult='';
                   4640:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   4641:     if ($hashref) {
1.384     raeburn  4642: 	while (my ($key,$value) = each(%$hashref)) {
1.397     raeburn  4643:             my ($unesc_key,$lasttime_key,$lasttime,$is_hash,%val,
1.427     raeburn  4644:                 %unesc_val,$selfenroll_end,$selfenroll_types,$created,
                   4645:                 $context);
1.384     raeburn  4646:             $unesc_key = &unescape($key);
                   4647:             if ($unesc_key =~ /^lasttime:/) {
                   4648:                 next;
                   4649:             } else {
                   4650:                 $lasttime_key = &escape('lasttime:'.$unesc_key);
                   4651:             }
                   4652:             if ($hashref->{$lasttime_key} ne '') {
                   4653:                 $lasttime = $hashref->{$lasttime_key};
                   4654:                 next if ($lasttime<$since);
                   4655:             }
1.419     raeburn  4656:             my ($canclone,$valchange);
1.384     raeburn  4657:             my $items = &Apache::lonnet::thaw_unescape($value);
                   4658:             if (ref($items) eq 'HASH') {
1.429     raeburn  4659:                 if ($hashref->{$lasttime_key} eq '') {
1.430     raeburn  4660:                     next if ($since > 1);
1.429     raeburn  4661:                 }
1.384     raeburn  4662:                 $is_hash =  1;
1.445     raeburn  4663:                 if ($domcloner) {
                   4664:                     $canclone = 1;
                   4665:                 } elsif (defined($clonerudom)) {
1.419     raeburn  4666:                     if ($items->{'cloners'}) {
                   4667:                         my @cloneable = split(',',$items->{'cloners'});
                   4668:                         if (@cloneable) {
                   4669:                             if (grep(/^\*$/,@cloneable))  {
                   4670:                                 $canclone = 1;
                   4671:                             } elsif (grep(/^\*:\Q$clonerudom\E$/,@cloneable)) {
                   4672:                                 $canclone = 1;
                   4673:                             } elsif (grep(/^\Q$cloneruname\E:\Q$clonerudom\E$/,@cloneable)) {
                   4674:                                 $canclone = 1;
                   4675:                             }
                   4676:                         }
                   4677:                         unless ($canclone) {
                   4678:                             if ($cloneruname ne '' && $clonerudom ne '') {
                   4679:                                 if ($cc_clone{$unesc_key}) {
                   4680:                                     $canclone = 1;
                   4681:                                     $items->{'cloners'} .= ','.$cloneruname.':'.
                   4682:                                                            $clonerudom;
                   4683:                                     $valchange = 1;
                   4684:                                 }
                   4685:                             }
                   4686:                         }
                   4687:                     } elsif (defined($cloneruname)) {
                   4688:                         if ($cc_clone{$unesc_key}) {
                   4689:                             $canclone = 1;
                   4690:                             $items->{'cloners'} = $cloneruname.':'.$clonerudom;
                   4691:                             $valchange = 1;
                   4692:                         }
1.437     raeburn  4693:                         unless ($canclone) {
                   4694:                             if ($items->{'owner'} =~ /:/) {
                   4695:                                 if ($items->{'owner'} eq $cloner) {
                   4696:                                     $canclone = 1;
                   4697:                                 }
1.444     raeburn  4698:                             } elsif ($cloner eq $items->{'owner'}.':'.$udom) {
1.437     raeburn  4699:                                 $canclone = 1;
                   4700:                             }
                   4701:                             if ($canclone) {
                   4702:                                 $items->{'cloners'} = $cloneruname.':'.$clonerudom;
                   4703:                                 $valchange = 1;
                   4704:                             }
                   4705:                         }
1.419     raeburn  4706:                     }
                   4707:                 }
1.384     raeburn  4708:                 if ($unpack || !$rtn_as_hash) {
                   4709:                     $unesc_val{'descr'} = $items->{'description'};
                   4710:                     $unesc_val{'inst_code'} = $items->{'inst_code'};
                   4711:                     $unesc_val{'owner'} = $items->{'owner'};
                   4712:                     $unesc_val{'type'} = $items->{'type'};
1.419     raeburn  4713:                     $unesc_val{'cloners'} = $items->{'cloners'};
1.427     raeburn  4714:                     $unesc_val{'created'} = $items->{'created'};
                   4715:                     $unesc_val{'context'} = $items->{'context'};
1.404     raeburn  4716:                 }
                   4717:                 $selfenroll_types = $items->{'selfenroll_types'};
                   4718:                 $selfenroll_end = $items->{'selfenroll_end_date'};
1.427     raeburn  4719:                 $created = $items->{'created'};
                   4720:                 $context = $items->{'context'};
1.505     raeburn  4721:                 if ($hasuniquecode ne '.') {
                   4722:                     next unless ($items->{'uniquecode'});
                   4723:                 }
1.404     raeburn  4724:                 if ($selfenrollonly) {
                   4725:                     next if (!$selfenroll_types);
                   4726:                     if (($selfenroll_end > 0) && ($selfenroll_end <= $now)) {
                   4727:                         next;
1.397     raeburn  4728:                     }
1.404     raeburn  4729:                 }
1.427     raeburn  4730:                 if ($creationcontext ne '.') {
                   4731:                     next if (($context ne '') && ($context ne $creationcontext));  
                   4732:                 }
                   4733:                 if ($createdbefore > 0) {
                   4734:                     next if (($created eq '') || ($created > $createdbefore));   
                   4735:                 }
                   4736:                 if ($createdafter > 0) {
                   4737:                     next if (($created eq '') || ($created <= $createdafter)); 
                   4738:                 }
1.404     raeburn  4739:                 if ($catfilter ne '') {
1.406     raeburn  4740:                     next if ($items->{'categories'} eq '');
                   4741:                     my @categories = split('&',$items->{'categories'}); 
1.407     raeburn  4742:                     next if (@categories == 0);
                   4743:                     my @subcats = split('&',$catfilter);
                   4744:                     my $matchcat = 0;
                   4745:                     foreach my $cat (@categories) {
                   4746:                         if (grep(/^\Q$cat\E$/,@subcats)) {
                   4747:                             $matchcat = 1;
                   4748:                             last;
                   4749:                         }
                   4750:                     }
                   4751:                     next if (!$matchcat);
1.404     raeburn  4752:                 }
                   4753:                 if ($caller eq 'coursecatalog') {
1.405     raeburn  4754:                     if ($items->{'hidefromcat'} eq 'yes') {
                   4755:                         next if !$showhidden;
1.401     raeburn  4756:                     }
1.384     raeburn  4757:                 }
1.383     raeburn  4758:             } else {
1.401     raeburn  4759:                 next if ($catfilter ne '');
1.419     raeburn  4760:                 next if ($selfenrollonly);
1.427     raeburn  4761:                 next if ($createdbefore || $createdafter);
                   4762:                 next if ($creationcontext ne '.');
1.419     raeburn  4763:                 if ((defined($clonerudom)) && (defined($cloneruname)))  {
                   4764:                     if ($cc_clone{$unesc_key}) {
                   4765:                         $canclone = 1;
                   4766:                         $val{'cloners'} = &escape($cloneruname.':'.$clonerudom);
                   4767:                     }
                   4768:                 }
1.384     raeburn  4769:                 $is_hash =  0;
1.388     raeburn  4770:                 my @courseitems = split(/:/,$value);
1.403     raeburn  4771:                 $lasttime = pop(@courseitems);
1.402     raeburn  4772:                 if ($hashref->{$lasttime_key} eq '') {
                   4773:                     next if ($lasttime<$since);
                   4774:                 }
1.384     raeburn  4775: 	        ($val{'descr'},$val{'inst_code'},$val{'owner'},$val{'type'}) = @courseitems;
1.383     raeburn  4776:             }
1.419     raeburn  4777:             if ($cloneonly) {
                   4778:                next unless ($canclone);
                   4779:             }
1.266     raeburn  4780:             my $match = 1;
1.384     raeburn  4781: 	    if ($description ne '.') {
                   4782:                 if (!$is_hash) {
                   4783:                     $unesc_val{'descr'} = &unescape($val{'descr'});
                   4784:                 }
                   4785:                 if (eval{$unesc_val{'descr'} !~ /\Q$description\E/i}) {
1.266     raeburn  4786:                     $match = 0;
1.384     raeburn  4787:                 }
1.266     raeburn  4788:             }
1.384     raeburn  4789:             if ($instcodefilter ne '.') {
                   4790:                 if (!$is_hash) {
                   4791:                     $unesc_val{'inst_code'} = &unescape($val{'inst_code'});
                   4792:                 }
1.418     raeburn  4793:                 if ($regexp_ok == 1) {
1.384     raeburn  4794:                     if (eval{$unesc_val{'inst_code'} !~ /$instcodefilter/}) {
1.344     raeburn  4795:                         $match = 0;
                   4796:                     }
1.418     raeburn  4797:                 } elsif ($regexp_ok == -1) {
                   4798:                     if (eval{$unesc_val{'inst_code'} =~ /$instcodefilter/}) {
                   4799:                         $match = 0;
                   4800:                     }
1.344     raeburn  4801:                 } else {
1.384     raeburn  4802:                     if (eval{$unesc_val{'inst_code'} !~ /\Q$instcodefilter\E/i}) {
1.344     raeburn  4803:                         $match = 0;
                   4804:                     }
1.266     raeburn  4805:                 }
1.234     foxr     4806: 	    }
1.384     raeburn  4807:             if ($ownerfilter ne '.') {
                   4808:                 if (!$is_hash) {
                   4809:                     $unesc_val{'owner'} = &unescape($val{'owner'});
                   4810:                 }
1.336     raeburn  4811:                 if (($ownerunamefilter ne '') && ($ownerdomfilter ne '')) {
1.384     raeburn  4812:                     if ($unesc_val{'owner'} =~ /:/) {
                   4813:                         if (eval{$unesc_val{'owner'} !~ 
                   4814:                              /\Q$ownerunamefilter\E:\Q$ownerdomfilter\E$/i}) {
1.336     raeburn  4815:                             $match = 0;
                   4816:                         } 
                   4817:                     } else {
1.384     raeburn  4818:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336     raeburn  4819:                             $match = 0;
                   4820:                         }
                   4821:                     }
                   4822:                 } elsif ($ownerunamefilter ne '') {
1.384     raeburn  4823:                     if ($unesc_val{'owner'} =~ /:/) {
                   4824:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E:[^:]+$/i}) {
1.336     raeburn  4825:                              $match = 0;
                   4826:                         }
                   4827:                     } else {
1.384     raeburn  4828:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336     raeburn  4829:                             $match = 0;
                   4830:                         }
                   4831:                     }
                   4832:                 } elsif ($ownerdomfilter ne '') {
1.384     raeburn  4833:                     if ($unesc_val{'owner'} =~ /:/) {
                   4834:                         if (eval{$unesc_val{'owner'} !~ /^[^:]+:\Q$ownerdomfilter\E/}) {
1.336     raeburn  4835:                              $match = 0;
                   4836:                         }
                   4837:                     } else {
                   4838:                         if ($ownerdomfilter ne $udom) {
                   4839:                             $match = 0;
                   4840:                         }
                   4841:                     }
1.266     raeburn  4842:                 }
                   4843:             }
1.384     raeburn  4844:             if ($coursefilter ne '.') {
                   4845:                 if (eval{$unesc_key !~ /^$udom(_)\Q$coursefilter\E$/}) {
1.282     raeburn  4846:                     $match = 0;
                   4847:                 }
                   4848:             }
1.384     raeburn  4849:             if ($typefilter ne '.') {
                   4850:                 if (!$is_hash) {
                   4851:                     $unesc_val{'type'} = &unescape($val{'type'});
                   4852:                 }
                   4853:                 if ($unesc_val{'type'} eq '') {
1.333     raeburn  4854:                     if ($typefilter ne 'Course') {
                   4855:                         $match = 0;
                   4856:                     }
1.383     raeburn  4857:                 } else {
1.384     raeburn  4858:                     if (eval{$unesc_val{'type'} !~ /^\Q$typefilter\E$/}) {
1.333     raeburn  4859:                         $match = 0;
                   4860:                     }
                   4861:                 }
                   4862:             }
1.266     raeburn  4863:             if ($match == 1) {
1.384     raeburn  4864:                 if ($rtn_as_hash) {
                   4865:                     if ($is_hash) {
1.419     raeburn  4866:                         if ($valchange) {
                   4867:                             my $newvalue = &Apache::lonnet::freeze_escape($items);
                   4868:                             $qresult.=$key.'='.$newvalue.'&';
                   4869:                         } else {
                   4870:                             $qresult.=$key.'='.$value.'&';
                   4871:                         }
1.384     raeburn  4872:                     } else {
1.388     raeburn  4873:                         my %rtnhash = ( 'description' => &unescape($val{'descr'}),
                   4874:                                         'inst_code' => &unescape($val{'inst_code'}),
                   4875:                                         'owner'     => &unescape($val{'owner'}),
                   4876:                                         'type'      => &unescape($val{'type'}),
1.419     raeburn  4877:                                         'cloners'   => &unescape($val{'cloners'}),
1.384     raeburn  4878:                                       );
                   4879:                         my $items = &Apache::lonnet::freeze_escape(\%rtnhash);
                   4880:                         $qresult.=$key.'='.$items.'&';
                   4881:                     }
1.383     raeburn  4882:                 } else {
1.384     raeburn  4883:                     if ($is_hash) {
                   4884:                         $qresult .= $key.'='.&escape($unesc_val{'descr'}).':'.
                   4885:                                     &escape($unesc_val{'inst_code'}).':'.
                   4886:                                     &escape($unesc_val{'owner'}).'&';
                   4887:                     } else {
                   4888:                         $qresult .= $key.'='.$val{'descr'}.':'.$val{'inst_code'}.
                   4889:                                     ':'.$val{'owner'}.'&';
                   4890:                     }
1.383     raeburn  4891:                 }
1.266     raeburn  4892:             }
1.234     foxr     4893: 	}
1.311     albertel 4894: 	if (&untie_domain_hash($hashref)) {
1.234     foxr     4895: 	    chop($qresult);
1.387     albertel 4896: 	    &Reply($client, \$qresult, $userinput);
1.234     foxr     4897: 	} else {
                   4898: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4899: 		    "while attempting courseiddump\n", $userinput);
                   4900: 	}
                   4901:     } else {
                   4902: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4903: 		"while attempting courseiddump\n", $userinput);
                   4904:     }
                   4905:     return 1;
                   4906: }
                   4907: &register_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
1.238     foxr     4908: 
1.438     raeburn  4909: sub course_lastaccess_handler {
                   4910:     my ($cmd, $tail, $client) = @_;
                   4911:     my $userinput = "$cmd:$tail";
                   4912:     my ($cdom,$cnum) = split(':',$tail); 
                   4913:     my (%lastaccess,$qresult);
                   4914:     my $hashref = &tie_domain_hash($cdom, "nohist_courseids", &GDBM_WRCREAT());
                   4915:     if ($hashref) {
                   4916:         while (my ($key,$value) = each(%$hashref)) {
                   4917:             my ($unesc_key,$lasttime);
                   4918:             $unesc_key = &unescape($key);
                   4919:             if ($cnum) {
                   4920:                 next unless ($unesc_key =~ /\Q$cdom\E_\Q$cnum\E$/);
                   4921:             }
                   4922:             if ($unesc_key =~ /^lasttime:($LONCAPA::match_domain\_$LONCAPA::match_courseid)/) {
                   4923:                 $lastaccess{$1} = $value;
                   4924:             } else {
                   4925:                 my $items = &Apache::lonnet::thaw_unescape($value);
                   4926:                 if (ref($items) eq 'HASH') {
                   4927:                     unless ($lastaccess{$unesc_key}) {
                   4928:                         $lastaccess{$unesc_key} = '';
                   4929:                     }
                   4930:                 } else {
                   4931:                     my @courseitems = split(':',$value);
                   4932:                     $lastaccess{$unesc_key} = pop(@courseitems);
                   4933:                 }
                   4934:             }
                   4935:         }
                   4936:         foreach my $cid (sort(keys(%lastaccess))) {
                   4937:             $qresult.=&escape($cid).'='.$lastaccess{$cid}.'&'; 
                   4938:         }
                   4939:         if (&untie_domain_hash($hashref)) {
                   4940:             if ($qresult) {
                   4941:                 chop($qresult);
                   4942:             }
                   4943:             &Reply($client, \$qresult, $userinput);
                   4944:         } else {
                   4945:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4946:                     "while attempting lastacourseaccess\n", $userinput);
                   4947:         }
                   4948:     } else {
                   4949:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4950:                 "while attempting lastcourseaccess\n", $userinput);
                   4951:     }
                   4952:     return 1;
                   4953: }
                   4954: &register_handler("courselastaccess",\&course_lastaccess_handler, 0, 1, 0);
                   4955: 
1.561     raeburn  4956: sub course_sessions_handler {
                   4957:     my ($cmd, $tail, $client) = @_;
                   4958:     my $userinput = "$cmd:$tail";
                   4959:     my ($cdom,$cnum,$lastactivity) = split(':',$tail);
                   4960:     my $dbsuffix = '_'.$cdom.'_'.$cnum.'.db';
                   4961:     my (%sessions,$qresult);
                   4962:     my $now=time;
                   4963:     if (opendir(DIR,$perlvar{'lonIDsDir'})) {
                   4964:         my $filename;
                   4965:         while ($filename=readdir(DIR)) {
                   4966:             next if ($filename=~/^\./);
                   4967:             next if ($filename=~/^publicuser_/);
                   4968:             next if ($filename=~/^[a-f0-9]+_(linked|lti_\d+)\.id$/);
1.562     raeburn  4969:             if ($filename =~ /^($LONCAPA::match_username)_\d+_($LONCAPA::match_domain)_/) {
1.561     raeburn  4970:                 my ($uname,$udom) = ($1,$2);
1.562     raeburn  4971:                 next unless (-e "$perlvar{'lonDaemons'}/tmp/$uname$dbsuffix");
1.561     raeburn  4972:                 my $mtime = (stat("$perlvar{'lonIDsDir'}/$filename"))[9];
                   4973:                 if ($lastactivity < 0) {
1.563     raeburn  4974:                     next if ($mtime-$now > $lastactivity);
1.561     raeburn  4975:                 } else {
1.563     raeburn  4976:                     next if ($now-$mtime > $lastactivity);
1.561     raeburn  4977:                 }
                   4978:                 $sessions{$uname.':'.$udom} = $mtime;
                   4979:             }
                   4980:         }
                   4981:         closedir(DIR); 
                   4982:     }
                   4983:     foreach my $user (keys(%sessions)) {
                   4984:         $qresult.=&escape($user).'='.$sessions{$user}.'&';
                   4985:     }
                   4986:     if ($qresult) {
                   4987:         chop($qresult);
                   4988:     }
                   4989:     &Reply($client, \$qresult, $userinput);
                   4990:     return 1;
                   4991: }
                   4992: &register_handler("coursesessions",\&course_sessions_handler, 0, 1, 0);
                   4993: 
1.238     foxr     4994: #
1.348     raeburn  4995: # Puts an unencrypted entry in a namespace db file at the domain level 
                   4996: #
                   4997: # Parameters:
                   4998: #    $cmd      - The command that got us here.
                   4999: #    $tail     - Tail of the command (remaining parameters).
                   5000: #    $client   - File descriptor connected to client.
                   5001: # Returns
                   5002: #     0        - Requested to exit, caller should shut down.
                   5003: #     1        - Continue processing.
                   5004: #  Side effects:
                   5005: #     reply is written to $client.
                   5006: #
                   5007: sub put_domain_handler {
                   5008:     my ($cmd,$tail,$client) = @_;
                   5009: 
                   5010:     my $userinput = "$cmd:$tail";
                   5011: 
                   5012:     my ($udom,$namespace,$what) =split(/:/,$tail,3);
                   5013:     chomp($what);
                   5014:     my @pairs=split(/\&/,$what);
                   5015:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_WRCREAT(),
                   5016:                                    "P", $what);
                   5017:     if ($hashref) {
                   5018:         foreach my $pair (@pairs) {
                   5019:             my ($key,$value)=split(/=/,$pair);
                   5020:             $hashref->{$key}=$value;
                   5021:         }
                   5022:         if (&untie_domain_hash($hashref)) {
                   5023:             &Reply($client, "ok\n", $userinput);
                   5024:         } else {
                   5025:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5026:                      "while attempting putdom\n", $userinput);
                   5027:         }
                   5028:     } else {
                   5029:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5030:                   "while attempting putdom\n", $userinput);
                   5031:     }
                   5032: 
                   5033:     return 1;
                   5034: }
                   5035: &register_handler("putdom", \&put_domain_handler, 0, 1, 0);
                   5036: 
1.517     raeburn  5037: # Updates one or more entries in clickers.db file at the domain level
                   5038: #
                   5039: # Parameters:
                   5040: #    $cmd      - The command that got us here.
                   5041: #    $tail     - Tail of the command (remaining parameters).
                   5042: #                In this case a colon separated list containing:
                   5043: #                (a) the domain for which we are updating the entries,
                   5044: #                (b) the action required -- add or del -- and
                   5045: #                (c) a &-separated list of entries to add or delete.
                   5046: #    $client   - File descriptor connected to client.
                   5047: # Returns
                   5048: #     1        - Continue processing.
                   5049: #     0        - Requested to exit, caller should shut down.
                   5050: #  Side effects:
                   5051: #     reply is written to $client.
                   5052: #
                   5053: 
                   5054: 
                   5055: sub update_clickers {
                   5056:     my ($cmd, $tail, $client)  = @_;
                   5057: 
                   5058:     my $userinput = "$cmd:$tail";
                   5059:     my ($udom,$action,$what) =split(/:/,$tail,3);
                   5060:     chomp($what);
                   5061: 
                   5062:     my $hashref = &tie_domain_hash($udom, "clickers", &GDBM_WRCREAT(),
                   5063:                                  "U","$action:$what");
                   5064: 
                   5065:     if (!$hashref) {
                   5066:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5067:                   "while attempting updateclickers\n", $userinput);
                   5068:         return 1;
                   5069:     }
                   5070: 
                   5071:     my @pairs=split(/\&/,$what);
                   5072:     foreach my $pair (@pairs) {
                   5073:         my ($key,$value)=split(/=/,$pair);
                   5074:         if ($action eq 'add') {
                   5075:             if (exists($hashref->{$key})) {
                   5076:                 my @newvals = split(/,/,&unescape($value));
                   5077:                 my @currvals = split(/,/,&unescape($hashref->{$key}));
                   5078:                 my @merged = sort(keys(%{{map { $_ => 1 } (@newvals,@currvals)}}));
                   5079:                 $hashref->{$key}=&escape(join(',',@merged));
                   5080:             } else {
                   5081:                 $hashref->{$key}=$value;
                   5082:             }
                   5083:         } elsif ($action eq 'del') {
                   5084:             if (exists($hashref->{$key})) {
                   5085:                 my %current;
                   5086:                 map { $current{$_} = 1; } split(/,/,&unescape($hashref->{$key}));
                   5087:                 map { delete($current{$_}); } split(/,/,&unescape($value));
                   5088:                 if (keys(%current)) {
                   5089:                     $hashref->{$key}=&escape(join(',',sort(keys(%current))));
                   5090:                 } else {
                   5091:                     delete($hashref->{$key});
                   5092:                 }
                   5093:             }
                   5094:         }
                   5095:     }
                   5096:     if (&untie_user_hash($hashref)) {
                   5097:         &Reply( $client, "ok\n", $userinput);
                   5098:     } else {
                   5099:         &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   5100:                  "while attempting put\n",
                   5101:                  $userinput);
                   5102:     }
                   5103:     return 1;
                   5104: }
                   5105: &register_handler("updateclickers", \&update_clickers, 0, 1, 0);
                   5106: 
                   5107: 
                   5108: # Deletes one or more entries in a namespace db file at the domain level
                   5109: #
                   5110: # Parameters:
                   5111: #    $cmd      - The command that got us here.
                   5112: #    $tail     - Tail of the command (remaining parameters).
                   5113: #                In this case a colon separated list containing:
                   5114: #                (a) the domain for which we are deleting the entries,
                   5115: #                (b) &-separated list of keys to delete.  
                   5116: #    $client   - File descriptor connected to client.
                   5117: # Returns
                   5118: #     1        - Continue processing.
                   5119: #     0        - Requested to exit, caller should shut down.
                   5120: #  Side effects:
                   5121: #     reply is written to $client.
                   5122: #
                   5123: 
                   5124: sub del_domain_handler {
                   5125:     my ($cmd,$tail,$client) = @_;
                   5126: 
                   5127:     my $userinput = "$cmd:$tail";
                   5128: 
                   5129:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   5130:     chomp($what);
                   5131:     my $hashref = &tie_domain_hash($udom,$namespace,&GDBM_WRCREAT(),
                   5132:                                    "D", $what);
                   5133:     if ($hashref) {
                   5134:         my @keys=split(/\&/,$what);
                   5135:         foreach my $key (@keys) {
                   5136:             delete($hashref->{$key});
                   5137:         }
                   5138:         if (&untie_user_hash($hashref)) {
                   5139:             &Reply($client, "ok\n", $userinput);
                   5140:         } else {
                   5141:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5142:                     "while attempting deldom\n", $userinput);
                   5143:         }
                   5144:     } else {
                   5145:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5146:                  "while attempting deldom\n", $userinput);
                   5147:     }
                   5148:     return 1;
                   5149: }
                   5150: &register_handler("deldom", \&del_domain_handler, 0, 1, 0);
                   5151: 
                   5152: 
1.348     raeburn  5153: # Unencrypted get from the namespace database file at the domain level.
                   5154: # This function retrieves a keyed item from a specific named database in the
                   5155: # domain directory.
                   5156: #
                   5157: # Parameters:
1.565     raeburn  5158: #   $cmd             - Command request keyword (getdom).
1.348     raeburn  5159: #   $tail            - Tail of the command.  This is a colon separated list
                   5160: #                      consisting of the domain and the 'namespace' 
                   5161: #                      which selects the gdbm file to do the lookup in,
                   5162: #                      & separated list of keys to lookup.  Note that
                   5163: #                      the values are returned as an & separated list too.
                   5164: #   $client          - File descriptor open on the client.
                   5165: # Returns:
                   5166: #   1       - Continue processing.
                   5167: #   0       - Exit.
                   5168: #  Side effects:
                   5169: #     reply is written to $client.
                   5170: #
                   5171: 
                   5172: sub get_domain_handler {
                   5173:     my ($cmd, $tail, $client) = @_;
                   5174: 
1.536     raeburn  5175:     my $userinput = "$cmd:$tail";
                   5176: 
                   5177:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
1.573     raeburn  5178:     if (($namespace =~ /^enc/) || ($namespace eq 'private')) {
1.536     raeburn  5179:         &Failure( $client, "refused\n", $userinput);
                   5180:     } else {
1.565     raeburn  5181:         my $res = LONCAPA::Lond::get_dom($userinput);
                   5182:         if ($res =~ /^error:/) {
                   5183:             &Failure($client, \$res, $userinput);
1.536     raeburn  5184:         } else {
1.565     raeburn  5185:             &Reply($client, \$res, $userinput);
1.536     raeburn  5186:         }
                   5187:     }
                   5188: 
                   5189:     return 1;
                   5190: }
                   5191: &register_handler("getdom", \&get_domain_handler, 0, 1, 0);
                   5192: 
1.572     raeburn  5193: #
                   5194: # Encrypted get from the namespace database file at the domain level.
                   5195: # This function retrieves a keyed item from a specific named database in the
                   5196: # domain directory.
                   5197: #
                   5198: # Parameters:
                   5199: #   $cmd             - Command request keyword (egetdom).
                   5200: #   $tail            - Tail of the command.  This is a colon separated list
                   5201: #                      consisting of the domain and the 'namespace'
                   5202: #                      which selects the gdbm file to do the lookup in,
                   5203: #                      & separated list of keys to lookup.  Note that
                   5204: #                      the values are returned as an & separated list too.
                   5205: #   $client          - File descriptor open on the client.
                   5206: # Returns:
                   5207: #   1       - Continue processing.
                   5208: #   0       - Exit.
                   5209: #  Side effects:
                   5210: #     reply is encrypted before being written to $client.
                   5211: #
1.536     raeburn  5212: sub encrypted_get_domain_handler {
                   5213:     my ($cmd, $tail, $client) = @_;
                   5214: 
                   5215:     my $userinput = "$cmd:$tail";
1.348     raeburn  5216: 
1.573     raeburn  5217:     my ($udom,$namespace,$what) = split(/:/,$tail,3);
                   5218:     if ($namespace eq 'private') {
                   5219:         &Failure( $client, "refused\n", $userinput);
1.565     raeburn  5220:     } else {
1.573     raeburn  5221:         my $res = LONCAPA::Lond::get_dom($userinput);
                   5222:         if ($res =~ /^error:/) {
                   5223:             &Failure($client, \$res, $userinput);
                   5224:         } else {
                   5225:             if ($cipher) {
                   5226:                 my $cmdlength=length($res);
                   5227:                 $res.="         ";
                   5228:                 my $encres='';
                   5229:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   5230:                     $encres.= unpack("H16",
                   5231:                                      $cipher->encrypt(substr($res,
                   5232:                                                              $encidx,
                   5233:                                                              8)));
                   5234:                 }
                   5235:                 &Reply( $client,"enc:$cmdlength:$encres\n",$userinput);
                   5236:             } else {
                   5237:                 &Failure( $client, "error:no_key\n",$userinput);
1.536     raeburn  5238:             }
1.348     raeburn  5239:         }
                   5240:     }
                   5241:     return 1;
                   5242: }
1.536     raeburn  5243: &register_handler("egetdom", \&encrypted_get_domain_handler, 1, 1, 0);
1.348     raeburn  5244: 
1.420     raeburn  5245: #
1.572     raeburn  5246: # Encrypted get from the namespace database file at the domain level.
                   5247: # This function retrieves a keyed item from a specific named database in the
                   5248: # domain directory.
                   5249: #
                   5250: # Parameters:
                   5251: #   $cmd             - Command request keyword (lti).
                   5252: #   $tail            - Tail of the command.  This is a colon-separated list
                   5253: #                      consisting of the domain, coursenum, if for LTI-
                   5254: #                      enabled deep-linking to course content using
                   5255: #                      link protection configured within a course,
                   5256: #                      context (=deeplink) if for LTI-enabled deep-linking
                   5257: #                      to course content using LTI Provider settings
                   5258: #                      configured within a course's domain, the (escaped)
                   5259: #                      launch URL, the (escaped) method (typically POST),
                   5260: #                      and a frozen hash of the LTI launch parameters
                   5261: #                      from the LTI payload.
                   5262: #   $client          - File descriptor open on the client.
                   5263: # Returns:
                   5264: #   1       - Continue processing.
                   5265: #   0       - Exit.
                   5266: #  Side effects:
                   5267: #     The reply will contain an LTI itemID, if the signed LTI payload
1.579     raeburn  5268: #     could be verified using the consumer key and the shared secret
                   5269: #     available for that key (for the itemID) for either the course or domain,
                   5270: #     depending on values for cnum and context. The reply is encrypted before
1.572     raeburn  5271: #     being written to $client.
                   5272: #
                   5273: sub lti_handler {
                   5274:     my ($cmd, $tail, $client) = @_;
                   5275: 
                   5276:     my $userinput = "$cmd:$tail";
                   5277: 
                   5278:     my ($cdom,$cnum,$context,$escurl,$escmethod,$items) = split(/:/,$tail);
                   5279:     my $url = &unescape($escurl);
                   5280:     my $method = &unescape($escmethod);
                   5281:     my $params = &Apache::lonnet::thaw_unescape($items);
                   5282:     my $res;
                   5283:     if ($cnum ne '') {
                   5284:         $res = &LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
                   5285:     } else {
                   5286:         $res = &LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
                   5287:     }
                   5288:     if ($res =~ /^error:/) {
                   5289:         &Failure($client, \$res, $userinput);
                   5290:     } else {
                   5291:         if ($cipher) {
                   5292:             my $cmdlength=length($res);
                   5293:             $res.="         ";
                   5294:             my $encres='';
                   5295:             for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   5296:                 $encres.= unpack("H16",
                   5297:                                  $cipher->encrypt(substr($res,
                   5298:                                                          $encidx,
                   5299:                                                          8)));
                   5300:             }
                   5301:             &Reply( $client,"enc:$cmdlength:$encres\n",$userinput);
                   5302:         } else {
                   5303:             &Failure( $client, "error:no_key\n",$userinput);
                   5304:         }
                   5305:     }
                   5306:     return 1;
                   5307: }
                   5308: &register_handler("lti", \&lti_handler, 1, 1, 0);
                   5309: 
                   5310: #
1.579     raeburn  5311: # Data for LTI payload (received encrypted) are unencrypted and
1.577     raeburn  5312: # then signed with the appropriate key and secret, before re-encrypting
1.579     raeburn  5313: # the signed payload which is sent to the client for unencryption by
                   5314: # the caller: lonnet::sign_lti()) before dispatch either to a web browser
                   5315: # (launch) or to a remote web service (roster, logout, or grade).  
1.577     raeburn  5316: #
                   5317: # Parameters:
                   5318: #   $cmd             - Command request keyword (signlti).
                   5319: #   $tail            - Tail of the command.  This is a colon-separated list
                   5320: #                      consisting of the domain, coursenum (if for an External
1.578     raeburn  5321: #                      Tool defined in a course), crsdef (true if defined in
1.579     raeburn  5322: #                      a course), type (linkprot or lti)
                   5323: #                      context (launch, roster, logout, or grade),
1.578     raeburn  5324: #                      escaped launch URL, numeric ID of external tool,
1.577     raeburn  5325: #                      version number for encryption key (if tool's LTI secret was
1.578     raeburn  5326: #                      encrypted before storing), a frozen hash of LTI launch 
                   5327: #                      parameters, and a frozen hash of LTI information,
                   5328: #                      (e.g., method => 'HMAC-SHA1',
                   5329: #                             respfmt => 'to_authorization_header').
1.577     raeburn  5330: #   $client          - File descriptor open on the client.
                   5331: # Returns:
                   5332: #   1       - Continue processing.
                   5333: #   0       - Exit.
                   5334: #  Side effects:
                   5335: #     The reply will contain the LTI payload, as & separated key=value pairs,
                   5336: #     where value is itself a frozen hash, if the required key and secret
1.579     raeburn  5337: #     for the specific tool ID are available. The payload data are retrieved from
1.578     raeburn  5338: #     a call to Lond::sign_lti_payload(), and the reply is encrypted before being
1.577     raeburn  5339: #     written to $client.
                   5340: #
                   5341: sub sign_lti_handler {
                   5342:     my ($cmd, $tail, $client) = @_;
                   5343: 
                   5344:     my $userinput = "$cmd:$tail";
                   5345: 
1.579     raeburn  5346:     my ($cdom,$cnum,$crsdef,$type,$context,$escurl,
                   5347:         $ltinum,$keynum,$paramsref,$inforef) = split(/:/,$tail);
1.577     raeburn  5348:     my $url = &unescape($escurl);
                   5349:     my $params = &Apache::lonnet::thaw_unescape($paramsref);
                   5350:     my $info = &Apache::lonnet::thaw_unescape($inforef);
                   5351:     my $res =
1.579     raeburn  5352:         &LONCAPA::Lond::sign_lti_payload($cdom,$cnum,$crsdef,$type,$context,$url,$ltinum,
                   5353:                                          $keynum,$perlvar{'lonVersion'},$params,$info);
1.577     raeburn  5354:     my $result;
                   5355:     if (ref($res) eq 'HASH') {
                   5356:         foreach my $key (keys(%{$res})) {
                   5357:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($res->{$key}).'&';
                   5358:         }
                   5359:         $result =~ s/\&$//;
                   5360:     } else {
                   5361:         $result = $res;
                   5362:     }
                   5363:     if ($result =~ /^error:/) {
                   5364:         &Failure($client, \$result, $userinput);
                   5365:     } else {
                   5366:         if ($cipher) {
                   5367:             my $cmdlength=length($result);
                   5368:             $result.="         ";
                   5369:             my $encres='';
                   5370:             for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   5371:                 $encres.= unpack("H16",
                   5372:                                  $cipher->encrypt(substr($result,
                   5373:                                                          $encidx,
                   5374:                                                          8)));
                   5375:             }
                   5376:             &Reply( $client,"enc:$cmdlength:$encres\n",$userinput);
                   5377:         } else {
                   5378:             &Failure( $client, "error:no_key\n",$userinput);
                   5379:         }
                   5380:     }
                   5381:     return 1;
                   5382: }
                   5383: &register_handler("signlti", \&sign_lti_handler, 1, 1, 0);
                   5384: 
                   5385: #
1.238     foxr     5386: #  Puts an id to a domains id database. 
                   5387: #
                   5388: #  Parameters:
                   5389: #   $cmd     - The command that triggered us.
                   5390: #   $tail    - Remainder of the request other than the command. This is a 
                   5391: #              colon separated list containing:
                   5392: #              $domain  - The domain for which we are writing the id.
                   5393: #              $pairs  - The id info to write... this is and & separated list
                   5394: #                        of keyword=value.
                   5395: #   $client  - Socket open on the client.
                   5396: #  Returns:
                   5397: #    1   - Continue processing.
                   5398: #  Side effects:
                   5399: #     reply is written to $client.
                   5400: #
                   5401: sub put_id_handler {
                   5402:     my ($cmd,$tail,$client) = @_;
                   5403: 
                   5404: 
                   5405:     my $userinput = "$cmd:$tail";
                   5406: 
                   5407:     my ($udom,$what)=split(/:/,$tail);
                   5408:     chomp($what);
                   5409:     my @pairs=split(/\&/,$what);
                   5410:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   5411: 				   "P", $what);
                   5412:     if ($hashref) {
                   5413: 	foreach my $pair (@pairs) {
                   5414: 	    my ($key,$value)=split(/=/,$pair);
                   5415: 	    $hashref->{$key}=$value;
                   5416: 	}
1.311     albertel 5417: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     5418: 	    &Reply($client, "ok\n", $userinput);
                   5419: 	} else {
                   5420: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5421: 		     "while attempting idput\n", $userinput);
                   5422: 	}
                   5423:     } else {
                   5424: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5425: 		  "while attempting idput\n", $userinput);
                   5426:     }
                   5427: 
                   5428:     return 1;
                   5429: }
1.263     albertel 5430: &register_handler("idput", \&put_id_handler, 0, 1, 0);
1.238     foxr     5431: 
                   5432: #
                   5433: #  Retrieves a set of id values from the id database.
                   5434: #  Returns an & separated list of results, one for each requested id to the
                   5435: #  client.
                   5436: #
                   5437: # Parameters:
                   5438: #   $cmd       - Command keyword that caused us to be dispatched.
                   5439: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5440: #               domain - the domain whose id table we dump
                   5441: #               ids      Consists of an & separated list of
                   5442: #                        id keywords whose values will be fetched.
                   5443: #                        nonexisting keywords will have an empty value.
                   5444: #   $client    - Socket open on the client.
                   5445: #
                   5446: # Returns:
                   5447: #    1 - indicating processing should continue.
                   5448: # Side effects:
                   5449: #   An & separated list of results is written to $client.
                   5450: #
                   5451: sub get_id_handler {
                   5452:     my ($cmd, $tail, $client) = @_;
                   5453: 
                   5454:     
                   5455:     my $userinput = "$client:$tail";
                   5456:     
                   5457:     my ($udom,$what)=split(/:/,$tail);
                   5458:     chomp($what);
                   5459:     my @queries=split(/\&/,$what);
                   5460:     my $qresult='';
                   5461:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
                   5462:     if ($hashref) {
                   5463: 	for (my $i=0;$i<=$#queries;$i++) {
                   5464: 	    $qresult.="$hashref->{$queries[$i]}&";
                   5465: 	}
1.311     albertel 5466: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     5467: 	    $qresult=~s/\&$//;
1.387     albertel 5468: 	    &Reply($client, \$qresult, $userinput);
1.238     foxr     5469: 	} else {
                   5470: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5471: 		      "while attempting idget\n",$userinput);
                   5472: 	}
                   5473:     } else {
                   5474: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5475: 		 "while attempting idget\n",$userinput);
                   5476:     }
                   5477:     
                   5478:     return 1;
                   5479: }
1.263     albertel 5480: &register_handler("idget", \&get_id_handler, 0, 1, 0);
1.238     foxr     5481: 
1.501     raeburn  5482: #   Deletes one or more ids in a domain's id database.
                   5483: #
                   5484: #   Parameters:
                   5485: #       $cmd                  - Command keyword (iddel).
                   5486: #       $tail                 - Command tail.  In this case a colon
                   5487: #                               separated list containing:
                   5488: #                               The domain for which we are deleting the id(s).
                   5489: #                               &-separated list of id(s) to delete.
                   5490: #       $client               - File open on client socket.
                   5491: # Returns:
                   5492: #     1   - Continue processing
                   5493: #     0   - Exit server.
                   5494: #     
                   5495: #
                   5496: 
                   5497: sub del_id_handler {
                   5498:     my ($cmd,$tail,$client) = @_;
                   5499: 
                   5500:     my $userinput = "$cmd:$tail";
                   5501: 
                   5502:     my ($udom,$what)=split(/:/,$tail);
                   5503:     chomp($what);
                   5504:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   5505:                                    "D", $what);
                   5506:     if ($hashref) {
                   5507:         my @keys=split(/\&/,$what);
                   5508:         foreach my $key (@keys) {
                   5509:             delete($hashref->{$key});
                   5510:         }
                   5511:         if (&untie_user_hash($hashref)) {
                   5512:             &Reply($client, "ok\n", $userinput);
                   5513:         } else {
                   5514:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5515:                     "while attempting iddel\n", $userinput);
                   5516:         }
                   5517:     } else {
                   5518:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5519:                  "while attempting iddel\n", $userinput);
                   5520:     }
                   5521:     return 1;
                   5522: }
                   5523: &register_handler("iddel", \&del_id_handler, 0, 1, 0);
                   5524: 
1.238     foxr     5525: #
1.299     raeburn  5526: # Puts broadcast e-mail sent by Domain Coordinator in nohist_dcmail database 
                   5527: #
                   5528: # Parameters
                   5529: #   $cmd       - Command keyword that caused us to be dispatched.
                   5530: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5531: #               domain - the domain whose dcmail we are recording
                   5532: #               email    Consists of key=value pair 
                   5533: #                        where key is unique msgid
                   5534: #                        and value is message (in XML)
                   5535: #   $client    - Socket open on the client.
                   5536: #
                   5537: # Returns:
                   5538: #    1 - indicating processing should continue.
                   5539: # Side effects
                   5540: #     reply is written to $client.
                   5541: #
                   5542: sub put_dcmail_handler {
                   5543:     my ($cmd,$tail,$client) = @_;
                   5544:     my $userinput = "$cmd:$tail";
1.463     foxr     5545: 
                   5546: 
1.299     raeburn  5547:     my ($udom,$what)=split(/:/,$tail);
                   5548:     chomp($what);
                   5549:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   5550:     if ($hashref) {
                   5551:         my ($key,$value)=split(/=/,$what);
                   5552:         $hashref->{$key}=$value;
                   5553:     }
1.311     albertel 5554:     if (&untie_domain_hash($hashref)) {
1.299     raeburn  5555:         &Reply($client, "ok\n", $userinput);
                   5556:     } else {
                   5557:         &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5558:                  "while attempting dcmailput\n", $userinput);
                   5559:     }
                   5560:     return 1;
                   5561: }
                   5562: &register_handler("dcmailput", \&put_dcmail_handler, 0, 1, 0);
                   5563: 
                   5564: #
                   5565: # Retrieves broadcast e-mail from nohist_dcmail database
                   5566: # Returns to client an & separated list of key=value pairs,
                   5567: # where key is msgid and value is message information.
                   5568: #
                   5569: # Parameters
                   5570: #   $cmd       - Command keyword that caused us to be dispatched.
                   5571: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5572: #               domain - the domain whose dcmail table we dump
                   5573: #               startfilter - beginning of time window 
                   5574: #               endfilter - end of time window
                   5575: #               sendersfilter - & separated list of username:domain 
                   5576: #                 for senders to search for.
                   5577: #   $client    - Socket open on the client.
                   5578: #
                   5579: # Returns:
                   5580: #    1 - indicating processing should continue.
                   5581: # Side effects
                   5582: #     reply (& separated list of msgid=messageinfo pairs) is 
                   5583: #     written to $client.
                   5584: #
                   5585: sub dump_dcmail_handler {
                   5586:     my ($cmd, $tail, $client) = @_;
                   5587:                                                                                 
                   5588:     my $userinput = "$cmd:$tail";
                   5589:     my ($udom,$startfilter,$endfilter,$sendersfilter) = split(/:/,$tail);
                   5590:     chomp($sendersfilter);
                   5591:     my @senders = ();
                   5592:     if (defined($startfilter)) {
                   5593:         $startfilter=&unescape($startfilter);
                   5594:     } else {
                   5595:         $startfilter='.';
                   5596:     }
                   5597:     if (defined($endfilter)) {
                   5598:         $endfilter=&unescape($endfilter);
                   5599:     } else {
                   5600:         $endfilter='.';
                   5601:     }
                   5602:     if (defined($sendersfilter)) {
                   5603:         $sendersfilter=&unescape($sendersfilter);
1.300     albertel 5604: 	@senders = map { &unescape($_) } split(/\&/,$sendersfilter);
1.299     raeburn  5605:     }
                   5606: 
                   5607:     my $qresult='';
                   5608:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   5609:     if ($hashref) {
                   5610:         while (my ($key,$value) = each(%$hashref)) {
                   5611:             my $match = 1;
1.303     albertel 5612:             my ($timestamp,$subj,$uname,$udom) = 
                   5613: 		split(/:/,&unescape(&unescape($key)),5); # yes, twice really
1.299     raeburn  5614:             $subj = &unescape($subj);
                   5615:             unless ($startfilter eq '.' || !defined($startfilter)) {
                   5616:                 if ($timestamp < $startfilter) {
                   5617:                     $match = 0;
                   5618:                 }
                   5619:             }
                   5620:             unless ($endfilter eq '.' || !defined($endfilter)) {
                   5621:                 if ($timestamp > $endfilter) {
                   5622:                     $match = 0;
                   5623:                 }
                   5624:             }
                   5625:             unless (@senders < 1) {
                   5626:                 unless (grep/^$uname:$udom$/,@senders) {
                   5627:                     $match = 0;
                   5628:                 }
                   5629:             }
                   5630:             if ($match == 1) {
                   5631:                 $qresult.=$key.'='.$value.'&';
                   5632:             }
                   5633:         }
1.311     albertel 5634:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5635:             chop($qresult);
1.387     albertel 5636:             &Reply($client, \$qresult, $userinput);
1.299     raeburn  5637:         } else {
                   5638:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5639:                     "while attempting dcmaildump\n", $userinput);
                   5640:         }
                   5641:     } else {
                   5642:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5643:                 "while attempting dcmaildump\n", $userinput);
                   5644:     }
                   5645:     return 1;
                   5646: }
                   5647: 
                   5648: &register_handler("dcmaildump", \&dump_dcmail_handler, 0, 1, 0);
                   5649: 
                   5650: #
                   5651: # Puts domain roles in nohist_domainroles database
                   5652: #
                   5653: # Parameters
                   5654: #   $cmd       - Command keyword that caused us to be dispatched.
                   5655: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5656: #               domain - the domain whose roles we are recording  
                   5657: #               role -   Consists of key=value pair
                   5658: #                        where key is unique role
                   5659: #                        and value is start/end date information
                   5660: #   $client    - Socket open on the client.
                   5661: #
                   5662: # Returns:
                   5663: #    1 - indicating processing should continue.
                   5664: # Side effects
                   5665: #     reply is written to $client.
                   5666: #
                   5667: 
                   5668: sub put_domainroles_handler {
                   5669:     my ($cmd,$tail,$client) = @_;
                   5670: 
                   5671:     my $userinput = "$cmd:$tail";
                   5672:     my ($udom,$what)=split(/:/,$tail);
                   5673:     chomp($what);
                   5674:     my @pairs=split(/\&/,$what);
                   5675:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   5676:     if ($hashref) {
                   5677:         foreach my $pair (@pairs) {
                   5678:             my ($key,$value)=split(/=/,$pair);
                   5679:             $hashref->{$key}=$value;
                   5680:         }
1.311     albertel 5681:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5682:             &Reply($client, "ok\n", $userinput);
                   5683:         } else {
                   5684:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5685:                      "while attempting domroleput\n", $userinput);
                   5686:         }
                   5687:     } else {
                   5688:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5689:                   "while attempting domroleput\n", $userinput);
                   5690:     }
                   5691:                                                                                   
                   5692:     return 1;
                   5693: }
                   5694: 
                   5695: &register_handler("domroleput", \&put_domainroles_handler, 0, 1, 0);
                   5696: 
                   5697: #
                   5698: # Retrieves domain roles from nohist_domainroles database
                   5699: # Returns to client an & separated list of key=value pairs,
                   5700: # where key is role and value is start and end date information.
                   5701: #
                   5702: # Parameters
                   5703: #   $cmd       - Command keyword that caused us to be dispatched.
                   5704: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5705: #               domain - the domain whose domain roles table we dump
                   5706: #   $client    - Socket open on the client.
                   5707: #
                   5708: # Returns:
                   5709: #    1 - indicating processing should continue.
                   5710: # Side effects
                   5711: #     reply (& separated list of role=start/end info pairs) is
                   5712: #     written to $client.
                   5713: #
                   5714: sub dump_domainroles_handler {
                   5715:     my ($cmd, $tail, $client) = @_;
                   5716:                                                                                            
                   5717:     my $userinput = "$cmd:$tail";
                   5718:     my ($udom,$startfilter,$endfilter,$rolesfilter) = split(/:/,$tail);
                   5719:     chomp($rolesfilter);
                   5720:     my @roles = ();
                   5721:     if (defined($startfilter)) {
                   5722:         $startfilter=&unescape($startfilter);
                   5723:     } else {
                   5724:         $startfilter='.';
                   5725:     }
                   5726:     if (defined($endfilter)) {
                   5727:         $endfilter=&unescape($endfilter);
                   5728:     } else {
                   5729:         $endfilter='.';
                   5730:     }
                   5731:     if (defined($rolesfilter)) {
                   5732:         $rolesfilter=&unescape($rolesfilter);
1.300     albertel 5733: 	@roles = split(/\&/,$rolesfilter);
1.299     raeburn  5734:     }
1.421     raeburn  5735: 
1.299     raeburn  5736:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   5737:     if ($hashref) {
                   5738:         my $qresult = '';
                   5739:         while (my ($key,$value) = each(%$hashref)) {
                   5740:             my $match = 1;
1.421     raeburn  5741:             my ($end,$start) = split(/:/,&unescape($value));
1.299     raeburn  5742:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,&unescape($key));
1.421     raeburn  5743:             unless (@roles < 1) {
                   5744:                 unless (grep/^\Q$trole\E$/,@roles) {
                   5745:                     $match = 0;
                   5746:                     next;
                   5747:                 }
                   5748:             }
1.299     raeburn  5749:             unless ($startfilter eq '.' || !defined($startfilter)) {
1.415     raeburn  5750:                 if ((defined($start)) && ($start >= $startfilter)) {
1.299     raeburn  5751:                     $match = 0;
1.421     raeburn  5752:                     next;
1.299     raeburn  5753:                 }
                   5754:             }
                   5755:             unless ($endfilter eq '.' || !defined($endfilter)) {
1.421     raeburn  5756:                 if ((defined($end)) && (($end > 0) && ($end <= $endfilter))) {
1.299     raeburn  5757:                     $match = 0;
1.421     raeburn  5758:                     next;
1.299     raeburn  5759:                 }
                   5760:             }
                   5761:             if ($match == 1) {
                   5762:                 $qresult.=$key.'='.$value.'&';
                   5763:             }
                   5764:         }
1.311     albertel 5765:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5766:             chop($qresult);
1.387     albertel 5767:             &Reply($client, \$qresult, $userinput);
1.299     raeburn  5768:         } else {
                   5769:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5770:                     "while attempting domrolesdump\n", $userinput);
                   5771:         }
                   5772:     } else {
                   5773:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5774:                 "while attempting domrolesdump\n", $userinput);
                   5775:     }
                   5776:     return 1;
                   5777: }
                   5778: 
                   5779: &register_handler("domrolesdump", \&dump_domainroles_handler, 0, 1, 0);
                   5780: 
                   5781: 
1.238     foxr     5782: #  Process the tmpput command I'm not sure what this does.. Seems to
                   5783: #  create a file in the lonDaemons/tmp directory of the form $id.tmp
                   5784: # where Id is the client's ip concatenated with a sequence number.
                   5785: # The file will contain some value that is passed in.  Is this e.g.
                   5786: # a login token?
                   5787: #
                   5788: # Parameters:
                   5789: #    $cmd     - The command that got us dispatched.
                   5790: #    $tail    - The remainder of the request following $cmd:
                   5791: #               In this case this will be the contents of the file.
                   5792: #    $client  - Socket connected to the client.
                   5793: # Returns:
                   5794: #    1 indicating processing can continue.
                   5795: # Side effects:
                   5796: #   A file is created in the local filesystem.
                   5797: #   A reply is sent to the client.
                   5798: sub tmp_put_handler {
                   5799:     my ($cmd, $what, $client) = @_;
                   5800: 
                   5801:     my $userinput = "$cmd:$what";	# Reconstruct for logging.
                   5802: 
1.347     raeburn  5803:     my ($record,$context) = split(/:/,$what);
                   5804:     if ($context ne '') {
                   5805:         chomp($context);
                   5806:         $context = &unescape($context);
                   5807:     }
                   5808:     my ($id,$store);
1.238     foxr     5809:     $tmpsnum++;
1.569     raeburn  5810:     my $numtries = 0;
                   5811:     my $execdir=$perlvar{'lonDaemons'};
                   5812:     if (($context eq 'resetpw') || ($context eq 'createaccount') ||
                   5813:         ($context eq 'sso') || ($context eq 'link') || ($context eq 'retry')) {
                   5814:         $id = &md5_hex(&md5_hex(time.{}.rand().$$.$tmpsnum));
                   5815:         while ((-e "$execdir/tmp/$id.tmp") && ($numtries <10)) {
                   5816:             undef($id);
                   5817:             $id = &md5_hex(&md5_hex(time.{}.rand().$$.$tmpsnum));
                   5818:             $numtries ++;
                   5819:         }
1.347     raeburn  5820:     } else {
                   5821:         $id = $$.'_'.$clientip.'_'.$tmpsnum;
                   5822:     }
1.238     foxr     5823:     $id=~s/\W/\_/g;
1.347     raeburn  5824:     $record=~s/\n//g;
1.569     raeburn  5825:     if (($id ne '') &&
                   5826:         ($store=IO::File->new(">$execdir/tmp/$id.tmp"))) {
1.347     raeburn  5827: 	print $store $record;
1.238     foxr     5828: 	close $store;
1.387     albertel 5829: 	&Reply($client, \$id, $userinput);
1.238     foxr     5830:     } else {
                   5831: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   5832: 		  "while attempting tmpput\n", $userinput);
                   5833:     }
                   5834:     return 1;
                   5835:   
                   5836: }
                   5837: &register_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
1.263     albertel 5838: 
1.238     foxr     5839: #   Processes the tmpget command.  This command returns the contents
                   5840: #  of a temporary resource file(?) created via tmpput.
                   5841: #
                   5842: # Paramters:
                   5843: #    $cmd      - Command that got us dispatched.
                   5844: #    $id       - Tail of the command, contain the id of the resource
                   5845: #                we want to fetch.
                   5846: #    $client   - socket open on the client.
                   5847: # Return:
                   5848: #    1         - Inidcating processing can continue.
                   5849: # Side effects:
                   5850: #   A reply is sent to the client.
                   5851: #
                   5852: sub tmp_get_handler {
                   5853:     my ($cmd, $id, $client) = @_;
                   5854: 
                   5855:     my $userinput = "$cmd:$id"; 
                   5856:     
                   5857: 
                   5858:     $id=~s/\W/\_/g;
                   5859:     my $store;
                   5860:     my $execdir=$perlvar{'lonDaemons'};
                   5861:     if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
                   5862: 	my $reply=<$store>;
1.387     albertel 5863: 	&Reply( $client, \$reply, $userinput);
1.238     foxr     5864: 	close $store;
                   5865:     } else {
                   5866: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   5867: 		  "while attempting tmpget\n", $userinput);
                   5868:     }
                   5869: 
                   5870:     return 1;
                   5871: }
                   5872: &register_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
1.263     albertel 5873: 
1.238     foxr     5874: #
                   5875: #  Process the tmpdel command.  This command deletes a temp resource
                   5876: #  created by the tmpput command.
                   5877: #
                   5878: # Parameters:
                   5879: #   $cmd      - Command that got us here.
                   5880: #   $id       - Id of the temporary resource created.
                   5881: #   $client   - socket open on the client process.
                   5882: #
                   5883: # Returns:
                   5884: #   1     - Indicating processing should continue.
                   5885: # Side Effects:
                   5886: #   A file is deleted
                   5887: #   A reply is sent to the client.
                   5888: sub tmp_del_handler {
                   5889:     my ($cmd, $id, $client) = @_;
                   5890:     
                   5891:     my $userinput= "$cmd:$id";
                   5892:     
                   5893:     chomp($id);
                   5894:     $id=~s/\W/\_/g;
                   5895:     my $execdir=$perlvar{'lonDaemons'};
                   5896:     if (unlink("$execdir/tmp/$id.tmp")) {
                   5897: 	&Reply($client, "ok\n", $userinput);
                   5898:     } else {
                   5899: 	&Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
                   5900: 		  "while attempting tmpdel\n", $userinput);
                   5901:     }
                   5902:     
                   5903:     return 1;
                   5904: 
                   5905: }
                   5906: &register_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
1.263     albertel 5907: 
1.238     foxr     5908: #
1.564     raeburn  5909: #  Process the updatebalcookie command.  This command updates a
                   5910: #  cookie in the lonBalancedir directory on a load balancer node.
                   5911: #
                   5912: # Parameters:
                   5913: #   $cmd      - Command that got us here.
                   5914: #   $tail     - Tail of the request (escaped cookie: escaped current entry)
                   5915: #
                   5916: #   $client   - socket open on the client process.
                   5917: #
                   5918: # Returns:
                   5919: #   1     - Indicating processing should continue.
                   5920: # Side Effects:
                   5921: #   A cookie file is updated from the lonBalancedir directory
                   5922: #   A reply is sent to the client.
                   5923: #
                   5924: sub update_balcookie_handler {
                   5925:     my ($cmd, $tail, $client) = @_;
                   5926: 
                   5927:     my $userinput= "$cmd:$tail";
                   5928:     chomp($tail);
                   5929:     my ($cookie,$lastentry) = map { &unescape($_) } (split(/:/,$tail));
                   5930: 
                   5931:     my $updatedone;
                   5932:     if ($cookie =~ /^$LONCAPA::match_domain\_$LONCAPA::match_username\_[a-f0-9]{32}$/) {
                   5933:         my $execdir=$perlvar{'lonBalanceDir'};
                   5934:         if (-e "$execdir/$cookie.id") {
                   5935:             my $doupdate;
                   5936:             if (open(my $fh,'<',"$execdir/$cookie.id")) {
                   5937:                 while (my $line = <$fh>) {
                   5938:                     chomp($line);
                   5939:                     if ($line eq $lastentry) {
                   5940:                         $doupdate = 1;
                   5941:                         last;
                   5942:                     }
                   5943:                 }
                   5944:                 close($fh);
                   5945:             }
                   5946:             if ($doupdate) {
                   5947:                 if (open(my $fh,'>',"$execdir/$cookie.id")) {
                   5948:                     print $fh $clientname;
                   5949:                     close($fh);
                   5950:                     $updatedone = 1;
                   5951:                 }
                   5952:             }
                   5953:         }
                   5954:     }
                   5955:     if ($updatedone) {
                   5956:         &Reply($client, "ok\n", $userinput);
                   5957:     } else {
                   5958:         &Failure( $client, "error: ".($!+0)."file update failed ".
                   5959:                   "while attempting updatebalcookie\n", $userinput);
                   5960:     }
                   5961:     return 1;
                   5962: }
                   5963: &register_handler("updatebalcookie", \&update_balcookie_handler, 0, 1, 0);
                   5964: 
                   5965: #
1.551     raeburn  5966: #  Process the delbalcookie command. This command deletes a balancer
1.564     raeburn  5967: #  cookie in the lonBalancedir directory on a load balancer node.
1.551     raeburn  5968: #
                   5969: # Parameters:
                   5970: #   $cmd      - Command that got us here.
                   5971: #   $cookie   - Cookie to be deleted.
                   5972: #   $client   - socket open on the client process.
                   5973: #
                   5974: # Returns:
                   5975: #   1     - Indicating processing should continue.
                   5976: # Side Effects:
                   5977: #   A cookie file is deleted from the lonBalancedir directory
                   5978: #   A reply is sent to the client.
                   5979: sub del_balcookie_handler {
                   5980:     my ($cmd, $cookie, $client) = @_;
                   5981: 
                   5982:     my $userinput= "$cmd:$cookie";
                   5983: 
                   5984:     chomp($cookie);
1.564     raeburn  5985:     $cookie = &unescape($cookie);
1.551     raeburn  5986:     my $deleted = '';
                   5987:     if ($cookie =~ /^$LONCAPA::match_domain\_$LONCAPA::match_username\_[a-f0-9]{32}$/) {
                   5988:         my $execdir=$perlvar{'lonBalanceDir'};
                   5989:         if (-e "$execdir/$cookie.id") {
                   5990:             if (open(my $fh,'<',"$execdir/$cookie.id")) {
                   5991:                 my $dodelete;
                   5992:                 while (my $line = <$fh>) {
                   5993:                     chomp($line);
                   5994:                     if ($line eq $clientname) {
                   5995:                         $dodelete = 1;
1.554     raeburn  5996:                         last;
1.551     raeburn  5997:                     }
                   5998:                 }
1.554     raeburn  5999:                 close($fh);
1.551     raeburn  6000:                 if ($dodelete) {
                   6001:                     if (unlink("$execdir/$cookie.id")) {
                   6002:                         $deleted = 1;
                   6003:                     }
                   6004:                 }
                   6005:             }
                   6006:         }
                   6007:     }
                   6008:     if ($deleted) {
                   6009:         &Reply($client, "ok\n", $userinput);
                   6010:     } else {
                   6011:         &Failure( $client, "error: ".($!+0)."Unlinking cookie file Failed ".
                   6012:                   "while attempting delbalcookie\n", $userinput);
                   6013:     }
                   6014:     return 1;
                   6015: }
                   6016: &register_handler("delbalcookie", \&del_balcookie_handler, 0, 1, 0);
                   6017: 
                   6018: #
1.246     foxr     6019: #   Processes the setannounce command.  This command
                   6020: #   creates a file named announce.txt in the top directory of
                   6021: #   the documentn root and sets its contents.  The announce.txt file is
                   6022: #   printed in its entirety at the LonCAPA login page.  Note:
                   6023: #   once the announcement.txt fileis created it cannot be deleted.
                   6024: #   However, setting the contents of the file to empty removes the
                   6025: #   announcement from the login page of loncapa so who cares.
                   6026: #
                   6027: # Parameters:
                   6028: #    $cmd          - The command that got us dispatched.
                   6029: #    $announcement - The text of the announcement.
                   6030: #    $client       - Socket open on the client process.
                   6031: # Retunrns:
                   6032: #   1             - Indicating request processing should continue
                   6033: # Side Effects:
                   6034: #   The file {DocRoot}/announcement.txt is created.
                   6035: #   A reply is sent to $client.
                   6036: #
                   6037: sub set_announce_handler {
                   6038:     my ($cmd, $announcement, $client) = @_;
                   6039:   
                   6040:     my $userinput    = "$cmd:$announcement";
                   6041: 
                   6042:     chomp($announcement);
                   6043:     $announcement=&unescape($announcement);
                   6044:     if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
                   6045: 				'/announcement.txt')) {
                   6046: 	print $store $announcement;
                   6047: 	close $store;
                   6048: 	&Reply($client, "ok\n", $userinput);
                   6049:     } else {
                   6050: 	&Failure($client, "error: ".($!+0)."\n", $userinput);
                   6051:     }
                   6052: 
                   6053:     return 1;
                   6054: }
                   6055: &register_handler("setannounce", \&set_announce_handler, 0, 1, 0);
1.263     albertel 6056: 
1.246     foxr     6057: #
                   6058: #  Return the version of the daemon.  This can be used to determine
                   6059: #  the compatibility of cross version installations or, alternatively to
                   6060: #  simply know who's out of date and who isn't.  Note that the version
                   6061: #  is returned concatenated with the tail.
                   6062: # Parameters:
                   6063: #   $cmd        - the request that dispatched to us.
                   6064: #   $tail       - Tail of the request (client's version?).
                   6065: #   $client     - Socket open on the client.
                   6066: #Returns:
                   6067: #   1 - continue processing requests.
                   6068: # Side Effects:
                   6069: #   Replies with version to $client.
                   6070: sub get_version_handler {
                   6071:     my ($cmd, $tail, $client) = @_;
                   6072: 
                   6073:     my $userinput  = $cmd.$tail;
                   6074:     
                   6075:     &Reply($client, &version($userinput)."\n", $userinput);
                   6076: 
                   6077: 
                   6078:     return 1;
                   6079: }
                   6080: &register_handler("version", \&get_version_handler, 0, 1, 0);
1.263     albertel 6081: 
1.246     foxr     6082: #  Set the current host and domain.  This is used to support
                   6083: #  multihomed systems.  Each IP of the system, or even separate daemons
                   6084: #  on the same IP can be treated as handling a separate lonCAPA virtual
                   6085: #  machine.  This command selects the virtual lonCAPA.  The client always
                   6086: #  knows the right one since it is lonc and it is selecting the domain/system
                   6087: #  from the hosts.tab file.
                   6088: # Parameters:
                   6089: #    $cmd      - Command that dispatched us.
                   6090: #    $tail     - Tail of the command (domain/host requested).
                   6091: #    $socket   - Socket open on the client.
                   6092: #
                   6093: # Returns:
                   6094: #     1   - Indicates the program should continue to process requests.
                   6095: # Side-effects:
                   6096: #     The default domain/system context is modified for this daemon.
                   6097: #     a reply is sent to the client.
                   6098: #
                   6099: sub set_virtual_host_handler {
                   6100:     my ($cmd, $tail, $socket) = @_;
                   6101:   
                   6102:     my $userinput  ="$cmd:$tail";
                   6103: 
                   6104:     &Reply($client, &sethost($userinput)."\n", $userinput);
                   6105: 
                   6106: 
                   6107:     return 1;
                   6108: }
1.247     albertel 6109: &register_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
1.246     foxr     6110: 
                   6111: #  Process a request to exit:
                   6112: #   - "bye" is sent to the client.
                   6113: #   - The client socket is shutdown and closed.
                   6114: #   - We indicate to the caller that we should exit.
                   6115: # Formal Parameters:
                   6116: #   $cmd                - The command that got us here.
                   6117: #   $tail               - Tail of the command (empty).
                   6118: #   $client             - Socket open on the tail.
                   6119: # Returns:
                   6120: #   0      - Indicating the program should exit!!
                   6121: #
                   6122: sub exit_handler {
                   6123:     my ($cmd, $tail, $client) = @_;
                   6124: 
                   6125:     my $userinput = "$cmd:$tail";
                   6126: 
                   6127:     &logthis("Client $clientip ($clientname) hanging up: $userinput");
                   6128:     &Reply($client, "bye\n", $userinput);
                   6129:     $client->shutdown(2);        # shutdown the socket forcibly.
                   6130:     $client->close();
                   6131: 
                   6132:     return 0;
                   6133: }
1.248     foxr     6134: &register_handler("exit", \&exit_handler, 0,1,1);
                   6135: &register_handler("init", \&exit_handler, 0,1,1);
                   6136: &register_handler("quit", \&exit_handler, 0,1,1);
                   6137: 
                   6138: #  Determine if auto-enrollment is enabled.
                   6139: #  Note that the original had what I believe to be a defect.
                   6140: #  The original returned 0 if the requestor was not a registerd client.
                   6141: #  It should return "refused".
                   6142: # Formal Parameters:
                   6143: #   $cmd       - The command that invoked us.
                   6144: #   $tail      - The tail of the command (Extra command parameters.
                   6145: #   $client    - The socket open on the client that issued the request.
                   6146: # Returns:
                   6147: #    1         - Indicating processing should continue.
                   6148: #
                   6149: sub enrollment_enabled_handler {
                   6150:     my ($cmd, $tail, $client) = @_;
                   6151:     my $userinput = $cmd.":".$tail; # For logging purposes.
                   6152: 
1.337     albertel 6153:     my ($cdom) = split(/:/, $tail, 2);   # Domain we're asking about.
1.582   ! raeburn  6154:     my $outcome;
        !          6155:     eval {
        !          6156:         local($SIG{__DIE__})='DEFAULT';
        !          6157:         $outcome = &localenroll::run($cdom);
        !          6158:     };
1.387     albertel 6159:     &Reply($client, \$outcome, $userinput);
1.248     foxr     6160:     return 1;
                   6161: }
                   6162: &register_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
                   6163: 
1.417     raeburn  6164: #
1.423     raeburn  6165: #   Validate an institutional code used for a LON-CAPA course.          
1.417     raeburn  6166: #
                   6167: # Formal Parameters:
                   6168: #   $cmd          - The command request that got us dispatched.
                   6169: #   $tail         - The tail of the command.  In this case,
                   6170: #                   this is a colon separated set of words that will be split
                   6171: #                   into:
1.424     raeburn  6172: #                        $dom      - The domain for which the check of 
                   6173: #                                    institutional course code will occur.
                   6174: #
                   6175: #                        $instcode - The institutional code for the course
                   6176: #                                    being requested, or validated for rights
                   6177: #                                    to request.
                   6178: #
                   6179: #                        $owner    - The course requestor (who will be the
                   6180: #                                    course owner, in the form username:domain
                   6181: #
1.417     raeburn  6182: #   $client       - Socket open on the client.
                   6183: # Returns:
                   6184: #    1           - Indicating processing should continue.
                   6185: #
                   6186: sub validate_instcode_handler {
                   6187:     my ($cmd, $tail, $client) = @_;
                   6188:     my $userinput = "$cmd:$tail";
1.423     raeburn  6189:     my ($dom,$instcode,$owner) = split(/:/, $tail);
1.422     raeburn  6190:     $instcode = &unescape($instcode);
                   6191:     $owner = &unescape($owner);
1.582   ! raeburn  6192:     my ($outcome,$description,$credits);
        !          6193:     eval {
        !          6194:         local($SIG{__DIE__})='DEFAULT';
        !          6195:         ($outcome,$description,$credits) =
        !          6196:             &localenroll::validate_instcode($dom,$instcode,$owner);
        !          6197:     };
1.498     raeburn  6198:     my $result = &escape($outcome).'&'.&escape($description).'&'.
                   6199:                  &escape($credits);
1.426     raeburn  6200:     &Reply($client, \$result, $userinput);
1.417     raeburn  6201: 
                   6202:     return 1;
                   6203: }
                   6204: &register_handler("autovalidateinstcode", \&validate_instcode_handler, 0, 1, 0);
                   6205: 
1.566     raeburn  6206: #
                   6207: #  Validate co-owner for cross-listed institutional code and
                   6208: #  institutional course code itself used for a LON-CAPA course.
                   6209: #
                   6210: # Formal Parameters:
                   6211: #   $cmd          - The command request that got us dispatched.
                   6212: #   $tail         - The tail of the command.  In this case,
                   6213: #                   this is a colon separated string containing:
                   6214: #      $dom            - Course's LON-CAPA domain
                   6215: #      $instcode       - Institutional course code for the course
                   6216: #      $inst_xlist     - Institutional course Id for the crosslisting
                   6217: #      $coowner        - Username of co-owner
                   6218: #      (values for all but $dom have been escaped). 
                   6219: #
                   6220: #   $client       - Socket open on the client.
                   6221: # Returns:
                   6222: #    1           - Indicating processing should continue.
                   6223: #
                   6224: sub validate_instcrosslist_handler  {
                   6225:     my ($cmd, $tail, $client) = @_;
                   6226:     my $userinput = "$cmd:$tail";
                   6227:     my ($dom,$instcode,$inst_xlist,$coowner) = split(/:/,$tail);
                   6228:     $instcode = &unescape($instcode);
                   6229:     $inst_xlist = &unescape($inst_xlist);
                   6230:     $coowner = &unescape($coowner);
1.582   ! raeburn  6231:     my $outcome;
        !          6232:     eval {
        !          6233:         local($SIG{__DIE__})='DEFAULT';
        !          6234:         $outcome = &localenroll::validate_crosslist_access($dom,$instcode,
        !          6235:                                                            $inst_xlist,$coowner);
        !          6236:     };
        !          6237: 
1.566     raeburn  6238:     &Reply($client, \$outcome, $userinput);
                   6239:     return 1;
                   6240: }
                   6241: &register_handler("autovalidateinstcrosslist", \&validate_instcrosslist_handler, 0, 1, 0);
                   6242: 
1.248     foxr     6243: #   Get the official sections for which auto-enrollment is possible.
                   6244: #   Since the admin people won't know about 'unofficial sections' 
                   6245: #   we cannot auto-enroll on them.
                   6246: # Formal Parameters:
                   6247: #    $cmd     - The command request that got us dispatched here.
                   6248: #    $tail    - The remainder of the request.  In our case this
                   6249: #               will be split into:
                   6250: #               $coursecode   - The course name from the admin point of view.
                   6251: #               $cdom         - The course's domain(?).
                   6252: #    $client  - Socket open on the client.
                   6253: # Returns:
                   6254: #    1    - Indiciting processing should continue.
                   6255: #
                   6256: sub get_sections_handler {
                   6257:     my ($cmd, $tail, $client) = @_;
                   6258:     my $userinput = "$cmd:$tail";
                   6259: 
                   6260:     my ($coursecode, $cdom) = split(/:/, $tail);
1.582   ! raeburn  6261:     my $seclist;
        !          6262:     eval {
        !          6263:         local($SIG{__DIE__})='DEFAULT';
        !          6264:         my @secs = &localenroll::get_sections($coursecode,$cdom);
        !          6265:         $seclist = &escape(join(':',@secs));
        !          6266:     };
1.387     albertel 6267:     &Reply($client, \$seclist, $userinput);
1.248     foxr     6268:     return 1;
                   6269: }
                   6270: &register_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
                   6271: 
                   6272: #   Validate the owner of a new course section.  
                   6273: #
                   6274: # Formal Parameters:
                   6275: #   $cmd      - Command that got us dispatched.
                   6276: #   $tail     - the remainder of the command.  For us this consists of a
                   6277: #               colon separated string containing:
                   6278: #                  $inst    - Course Id from the institutions point of view.
                   6279: #                  $owner   - Proposed owner of the course.
                   6280: #                  $cdom    - Domain of the course (from the institutions
                   6281: #                             point of view?)..
                   6282: #   $client   - Socket open on the client.
                   6283: #
                   6284: # Returns:
                   6285: #   1        - Processing should continue.
                   6286: #
1.582   ! raeburn  6287: 
1.248     foxr     6288: sub validate_course_owner_handler {
                   6289:     my ($cmd, $tail, $client)  = @_;
                   6290:     my $userinput = "$cmd:$tail";
1.470     raeburn  6291:     my ($inst_course_id, $owner, $cdom, $coowners) = split(/:/, $tail);
                   6292:     
1.336     raeburn  6293:     $owner = &unescape($owner);
1.470     raeburn  6294:     $coowners = &unescape($coowners);
1.582   ! raeburn  6295:     my $outcome;
        !          6296:     eval {
        !          6297:         local($SIG{__DIE__})='DEFAULT';
        !          6298:         $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom,$coowners);
        !          6299:     };
1.387     albertel 6300:     &Reply($client, \$outcome, $userinput);
1.248     foxr     6301:     return 1;
                   6302: }
                   6303: &register_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
1.263     albertel 6304: 
1.248     foxr     6305: #
                   6306: #   Validate a course section in the official schedule of classes
                   6307: #   from the institutions point of view (part of autoenrollment).
                   6308: #
                   6309: # Formal Parameters:
                   6310: #   $cmd          - The command request that got us dispatched.
                   6311: #   $tail         - The tail of the command.  In this case,
                   6312: #                   this is a colon separated set of words that will be split
                   6313: #                   into:
                   6314: #                        $inst_course_id - The course/section id from the
                   6315: #                                          institutions point of view.
                   6316: #                        $cdom           - The domain from the institutions
                   6317: #                                          point of view.
                   6318: #   $client       - Socket open on the client.
                   6319: # Returns:
                   6320: #    1           - Indicating processing should continue.
                   6321: #
                   6322: sub validate_course_section_handler {
                   6323:     my ($cmd, $tail, $client) = @_;
                   6324:     my $userinput = "$cmd:$tail";
                   6325:     my ($inst_course_id, $cdom) = split(/:/, $tail);
1.582   ! raeburn  6326:     my $outcome;
        !          6327:     eval {
        !          6328:         local($SIG{__DIE__})='DEFAULT';
        !          6329:         $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
        !          6330:     };
1.387     albertel 6331:     &Reply($client, \$outcome, $userinput);
1.248     foxr     6332:     return 1;
                   6333: }
                   6334: &register_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
                   6335: 
                   6336: #
1.340     raeburn  6337: #   Validate course owner's access to enrollment data for specific class section. 
                   6338: #   
                   6339: #
                   6340: # Formal Parameters:
                   6341: #    $cmd     - The command request that got us dispatched.
                   6342: #    $tail    - The tail of the command.   In this case this is a colon separated
1.542     raeburn  6343: #               set of values that will be split into:
1.340     raeburn  6344: #               $inst_class  - Institutional code for the specific class section   
1.542     raeburn  6345: #               $ownerlist   - An escaped comma-separated list of username:domain 
                   6346: #                              of the course owner, and co-owner(s).
1.340     raeburn  6347: #               $cdom        - The domain of the course from the institution's
                   6348: #                              point of view.
                   6349: #    $client  - The socket open on the client.
                   6350: # Returns:
                   6351: #    1 - continue processing.
                   6352: #
                   6353: 
                   6354: sub validate_class_access_handler {
                   6355:     my ($cmd, $tail, $client) = @_;
                   6356:     my $userinput = "$cmd:$tail";
1.383     raeburn  6357:     my ($inst_class,$ownerlist,$cdom) = split(/:/, $tail);
1.392     raeburn  6358:     my $owners = &unescape($ownerlist);
1.341     albertel 6359:     my $outcome;
                   6360:     eval {
                   6361: 	local($SIG{__DIE__})='DEFAULT';
1.392     raeburn  6362: 	$outcome=&localenroll::check_section($inst_class,$owners,$cdom);
1.341     albertel 6363:     };
1.387     albertel 6364:     &Reply($client,\$outcome, $userinput);
1.340     raeburn  6365:     return 1;
                   6366: }
                   6367: &register_handler("autovalidateclass_sec", \&validate_class_access_handler, 0, 1, 0);
                   6368: 
                   6369: #
1.567     raeburn  6370: #    Modify institutional sections (using customized &instsec_reformat()
                   6371: #    routine in localenroll.pm), to either clutter or declutter, for  
                   6372: #    purposes of ensuring an institutional course section (string) can
                   6373: #    be unambiguously separated into institutional course and section.
                   6374: #
                   6375: # Formal Parameters:
                   6376: #    $cmd     - The command request that got us dispatched.
                   6377: #    $tail    - The tail of the command.   In this case this is a colon separated
                   6378: #               set of values that will be split into:
                   6379: #               $cdom        - The LON-CAPA domain of the course.
                   6380: #               $action      - Either: clutter or declutter
                   6381: #                              clutter adds character(s) to eliminate ambiguity
                   6382: #                              declutter removes the added characters (e.g., for
                   6383: #                              display of the institutional course section string.
                   6384: #               $info        - A frozen hash in which keys are: 
                   6385: #                              LON-CAPA course number:Institutional course code
                   6386: #                              and values are a reference to an array of the
                   6387: #                              items to modify -- either institutional sections,
                   6388: #                              or institutional course sections (for crosslistings). 
                   6389: #    $client  - The socket open on the client.
                   6390: # Returns:
                   6391: #    1 - continue processing.
                   6392: #   
                   6393: 
                   6394: sub instsec_reformat_handler {
                   6395:     my ($cmd, $tail, $client) = @_;
                   6396:     my $userinput = "$cmd:$tail";
                   6397:     my ($cdom,$action,$info) = split(/:/,$tail);
                   6398:     my $instsecref = &Apache::lonnet::thaw_unescape($info);
                   6399:     my ($outcome,$result);
                   6400:     eval {
                   6401:         local($SIG{__DIE__})='DEFAULT';
                   6402:         $outcome=&localenroll::instsec_reformat($cdom,$action,$instsecref);
                   6403:         if ($outcome eq 'ok') {
                   6404:             if (ref($instsecref) eq 'HASH') {
                   6405:                 foreach my $key (keys(%{$instsecref})) {
                   6406:                     $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($instsecref->{$key}).'&';
                   6407:                 }
                   6408:                 $result =~ s/\&$//;
                   6409:             }
                   6410:         }
                   6411:     };
                   6412:     if (!$@) {
                   6413:         if ($outcome eq 'ok') {
                   6414:             &Reply( $client, \$result, $userinput);
                   6415:         } else {
                   6416:             &Reply($client,\$outcome, $userinput);
                   6417:         }
                   6418:     } else {
                   6419:         &Failure($client,"unknown_cmd\n",$userinput);
                   6420:     }
                   6421:     return 1;
                   6422: }
                   6423: &register_handler("autoinstsecreformat",\&instsec_reformat_handler, 0, 1, 0);
                   6424: 
                   6425: #
1.542     raeburn  6426: #   Validate course owner or co-owners(s) access to enrollment data for all sections
                   6427: #   and crosslistings for a particular course.
                   6428: #
                   6429: #
                   6430: # Formal Parameters:
                   6431: #    $cmd     - The command request that got us dispatched.
                   6432: #    $tail    - The tail of the command.   In this case this is a colon separated
                   6433: #               set of values that will be split into:
                   6434: #               $ownerlist   - An escaped comma-separated list of username:domain
                   6435: #                              of the course owner, and co-owner(s).
                   6436: #               $cdom        - The domain of the course from the institution's
                   6437: #                              point of view.
                   6438: #               $classes     - Frozen hash of institutional course sections and
                   6439: #                              crosslistings.
                   6440: #    $client  - The socket open on the client.
                   6441: # Returns:
                   6442: #    1 - continue processing.
                   6443: #
                   6444: 
                   6445: sub validate_classes_handler {
                   6446:     my ($cmd, $tail, $client) = @_;
                   6447:     my $userinput = "$cmd:$tail";
                   6448:     my ($ownerlist,$cdom,$classes) = split(/:/, $tail);
                   6449:     my $classesref = &Apache::lonnet::thaw_unescape($classes);
                   6450:     my $owners = &unescape($ownerlist);
                   6451:     my $result;
                   6452:     eval {
                   6453:         local($SIG{__DIE__})='DEFAULT';
                   6454:         my %validations;
                   6455:         my $response = &localenroll::check_instclasses($owners,$cdom,$classesref,
                   6456:                                                        \%validations);
                   6457:         if ($response eq 'ok') {
                   6458:             foreach my $key (keys(%validations)) {
                   6459:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
                   6460:             }
                   6461:             $result =~ s/\&$//;
                   6462:         } else {
                   6463:             $result = 'error';
                   6464:         }
                   6465:     };
                   6466:     if (!$@) {
                   6467:         &Reply($client, \$result, $userinput);
                   6468:     } else {
                   6469:         &Failure($client,"unknown_cmd\n",$userinput);
                   6470:     }
                   6471:     return 1;
                   6472: }
                   6473: &register_handler("autovalidateinstclasses", \&validate_classes_handler, 0, 1, 0);
                   6474: 
                   6475: #
1.340     raeburn  6476: #   Create a password for a new LON-CAPA user added by auto-enrollment.
                   6477: #   Only used for case where authentication method for new user is localauth
1.248     foxr     6478: #
                   6479: # Formal Parameters:
                   6480: #    $cmd     - The command request that got us dispatched.
                   6481: #    $tail    - The tail of the command.   In this case this is a colon separated
                   6482: #               set of words that will be split into:
1.340     raeburn  6483: #               $authparam - An authentication parameter (localauth parameter).
1.248     foxr     6484: #               $cdom      - The domain of the course from the institution's
                   6485: #                            point of view.
                   6486: #    $client  - The socket open on the client.
                   6487: # Returns:
                   6488: #    1 - continue processing.
                   6489: #
                   6490: sub create_auto_enroll_password_handler {
                   6491:     my ($cmd, $tail, $client) = @_;
                   6492:     my $userinput = "$cmd:$tail";
                   6493: 
                   6494:     my ($authparam, $cdom) = split(/:/, $userinput);
                   6495: 
                   6496:     my ($create_passwd,$authchk);
1.582   ! raeburn  6497:     eval {
        !          6498:         local($SIG{__DIE__})='DEFAULT';
        !          6499:         ($authparam,$create_passwd,$create_passwd,$authchk) = 
        !          6500:             &localenroll::create_password($authparam,$cdom);
        !          6501:     };
1.248     foxr     6502:     &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
                   6503: 	   $userinput);
                   6504: 
                   6505: 
                   6506:     return 1;
                   6507: }
                   6508: &register_handler("autocreatepassword", \&create_auto_enroll_password_handler, 
                   6509: 		  0, 1, 0);
                   6510: 
1.522     raeburn  6511: sub auto_export_grades_handler {
                   6512:     my ($cmd, $tail, $client) = @_;
                   6513:     my $userinput = "$cmd:$tail";
                   6514:     my ($cdom,$cnum,$info,$data) = split(/:/,$tail);
                   6515:     my $inforef = &Apache::lonnet::thaw_unescape($info);
                   6516:     my $dataref = &Apache::lonnet::thaw_unescape($data);
                   6517:     my ($outcome,$result);;
                   6518:     eval {
                   6519:         local($SIG{__DIE__})='DEFAULT';
                   6520:         my %rtnhash;
                   6521:         $outcome=&localenroll::export_grades($cdom,$cnum,$inforef,$dataref,\%rtnhash);
                   6522:         if ($outcome eq 'ok') {
                   6523:             foreach my $key (keys(%rtnhash)) {
                   6524:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
                   6525:             }
                   6526:             $result =~ s/\&$//;
                   6527:         }
                   6528:     };
                   6529:     if (!$@) {
                   6530:         if ($outcome eq 'ok') {
                   6531:             if ($cipher) {
                   6532:                 my $cmdlength=length($result);
                   6533:                 $result.="         ";
                   6534:                 my $encresult='';
                   6535:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   6536:                     $encresult.= unpack("H16",
                   6537:                                         $cipher->encrypt(substr($result,
                   6538:                                                                 $encidx,
                   6539:                                                                 8)));
                   6540:                 }
                   6541:                 &Reply( $client, "enc:$cmdlength:$encresult\n", $userinput);
                   6542:             } else {
                   6543:                 &Failure( $client, "error:no_key\n", $userinput);
                   6544:             }
                   6545:         } else {
                   6546:             &Reply($client, "$outcome\n", $userinput);
                   6547:         }
                   6548:     } else {
                   6549:         &Failure($client,"export_error\n",$userinput);
                   6550:     }
                   6551:     return 1;
                   6552: }
                   6553: &register_handler("autoexportgrades", \&auto_export_grades_handler,
1.536     raeburn  6554:                   1, 1, 0);
1.522     raeburn  6555: 
1.248     foxr     6556: #   Retrieve and remove temporary files created by/during autoenrollment.
                   6557: #
                   6558: # Formal Parameters:
                   6559: #    $cmd      - The command that got us dispatched.
                   6560: #    $tail     - The tail of the command.  In our case this is a colon 
                   6561: #                separated list that will be split into:
1.526     raeburn  6562: #                $filename - The name of the file to retrieve.
1.248     foxr     6563: #                            The filename is given as a path relative to
                   6564: #                            the LonCAPA temp file directory.
                   6565: #    $client   - Socket open on the client.
                   6566: #
                   6567: # Returns:
                   6568: #   1     - Continue processing.
                   6569: sub retrieve_auto_file_handler {
                   6570:     my ($cmd, $tail, $client)    = @_;
                   6571:     my $userinput                = "cmd:$tail";
                   6572: 
                   6573:     my ($filename)   = split(/:/, $tail);
                   6574: 
                   6575:     my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
1.521     raeburn  6576: 
                   6577:     if ($filename =~m{/\.\./}) {
                   6578:         &Failure($client, "refused\n", $userinput);
1.526     raeburn  6579:     } elsif ($filename !~ /^$LONCAPA::match_domain\_$LONCAPA::match_courseid\_.+_classlist\.xml$/) {
                   6580:         &Failure($client, "refused\n", $userinput);
1.521     raeburn  6581:     } elsif ( (-e $source) && ($filename ne '') ) {
1.248     foxr     6582: 	my $reply = '';
                   6583: 	if (open(my $fh,$source)) {
                   6584: 	    while (<$fh>) {
                   6585: 		chomp($_);
                   6586: 		$_ =~ s/^\s+//g;
                   6587: 		$_ =~ s/\s+$//g;
                   6588: 		$reply .= $_;
                   6589: 	    }
                   6590: 	    close($fh);
                   6591: 	    &Reply($client, &escape($reply)."\n", $userinput);
                   6592: 
                   6593: #   Does this have to be uncommented??!?  (RF).
                   6594: #
                   6595: #                                unlink($source);
                   6596: 	} else {
                   6597: 	    &Failure($client, "error\n", $userinput);
                   6598: 	}
                   6599:     } else {
                   6600: 	&Failure($client, "error\n", $userinput);
                   6601:     }
                   6602:     
                   6603: 
                   6604:     return 1;
                   6605: }
                   6606: &register_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
                   6607: 
1.423     raeburn  6608: sub crsreq_checks_handler {
                   6609:     my ($cmd, $tail, $client) = @_;
                   6610:     my $userinput = "$cmd:$tail";
                   6611:     my $dom = $tail;
                   6612:     my $result;
1.519     raeburn  6613:     my @reqtypes = ('official','unofficial','community','textbook','placement');
1.423     raeburn  6614:     eval {
                   6615:         local($SIG{__DIE__})='DEFAULT';
                   6616:         my %validations;
1.424     raeburn  6617:         my $response = &localenroll::crsreq_checks($dom,\@reqtypes,
                   6618:                                                    \%validations);
1.423     raeburn  6619:         if ($response eq 'ok') { 
                   6620:             foreach my $key (keys(%validations)) {
                   6621:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
                   6622:             }
                   6623:             $result =~ s/\&$//;
                   6624:         } else {
                   6625:             $result = 'error';
                   6626:         }
                   6627:     };
                   6628:     if (!$@) {
                   6629:         &Reply($client, \$result, $userinput);
                   6630:     } else {
                   6631:         &Failure($client,"unknown_cmd\n",$userinput);
                   6632:     }
                   6633:     return 1;
                   6634: }
                   6635: &register_handler("autocrsreqchecks", \&crsreq_checks_handler, 0, 1, 0);
                   6636: 
                   6637: sub validate_crsreq_handler {
                   6638:     my ($cmd, $tail, $client) = @_;
                   6639:     my $userinput = "$cmd:$tail";
1.508     raeburn  6640:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$customdata) = split(/:/, $tail);
1.423     raeburn  6641:     $instcode = &unescape($instcode);
                   6642:     $owner = &unescape($owner);
                   6643:     $crstype = &unescape($crstype);
                   6644:     $inststatuslist = &unescape($inststatuslist);
                   6645:     $instcode = &unescape($instcode);
                   6646:     $instseclist = &unescape($instseclist);
1.508     raeburn  6647:     my $custominfo = &Apache::lonnet::thaw_unescape($customdata);
1.423     raeburn  6648:     my $outcome;
                   6649:     eval {
                   6650:         local($SIG{__DIE__})='DEFAULT';
                   6651:         $outcome = &localenroll::validate_crsreq($dom,$owner,$crstype,
                   6652:                                                  $inststatuslist,$instcode,
1.508     raeburn  6653:                                                  $instseclist,$custominfo);
1.423     raeburn  6654:     };
                   6655:     if (!$@) {
                   6656:         &Reply($client, \$outcome, $userinput);
                   6657:     } else {
                   6658:         &Failure($client,"unknown_cmd\n",$userinput);
                   6659:     }
                   6660:     return 1;
                   6661: }
                   6662: &register_handler("autocrsreqvalidation", \&validate_crsreq_handler, 0, 1, 0);
                   6663: 
1.506     raeburn  6664: sub crsreq_update_handler {
                   6665:     my ($cmd, $tail, $client) = @_;
                   6666:     my $userinput = "$cmd:$tail";
1.509     raeburn  6667:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,$code,
                   6668:         $accessstart,$accessend,$infohashref) =
1.506     raeburn  6669:         split(/:/, $tail);
                   6670:     $crstype = &unescape($crstype);
                   6671:     $action = &unescape($action);
                   6672:     $ownername = &unescape($ownername);
                   6673:     $ownerdomain = &unescape($ownerdomain);
                   6674:     $fullname = &unescape($fullname);
                   6675:     $title = &unescape($title);
                   6676:     $code = &unescape($code);
1.509     raeburn  6677:     $accessstart = &unescape($accessstart);
                   6678:     $accessend = &unescape($accessend);
1.506     raeburn  6679:     my $incoming = &Apache::lonnet::thaw_unescape($infohashref);
                   6680:     my ($result,$outcome);
                   6681:     eval {
                   6682:         local($SIG{__DIE__})='DEFAULT';
                   6683:         my %rtnhash;
                   6684:         $outcome = &localenroll::crsreq_updates($cdom,$cnum,$crstype,$action,
                   6685:                                                 $ownername,$ownerdomain,$fullname,
1.509     raeburn  6686:                                                 $title,$code,$accessstart,$accessend,
                   6687:                                                 $incoming,\%rtnhash);
1.506     raeburn  6688:         if ($outcome eq 'ok') {
1.515     raeburn  6689:             my @posskeys = qw(createdweb createdmsg createdcustomized createdactions queuedweb queuedmsg formitems reviewweb validationjs onload javascript);
1.506     raeburn  6690:             foreach my $key (keys(%rtnhash)) {
                   6691:                 if (grep(/^\Q$key\E/,@posskeys)) {
                   6692:                     $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
                   6693:                 }
                   6694:             }
                   6695:             $result =~ s/\&$//;
                   6696:         }
                   6697:     };
                   6698:     if (!$@) {
                   6699:         if ($outcome eq 'ok') {
                   6700:             &Reply($client, \$result, $userinput);
                   6701:         } else {
                   6702:             &Reply($client, "format_error\n", $userinput);
                   6703:         }
                   6704:     } else {
                   6705:         &Failure($client,"unknown_cmd\n",$userinput);
                   6706:     }
                   6707:     return 1;
                   6708: }
                   6709: &register_handler("autocrsrequpdate", \&crsreq_update_handler, 0, 1, 0);
                   6710: 
1.248     foxr     6711: #
                   6712: #   Read and retrieve institutional code format (for support form).
                   6713: # Formal Parameters:
                   6714: #    $cmd        - Command that dispatched us.
                   6715: #    $tail       - Tail of the command.  In this case it conatins 
                   6716: #                  the course domain and the coursename.
                   6717: #    $client     - Socket open on the client.
                   6718: # Returns:
                   6719: #    1     - Continue processing.
                   6720: #
                   6721: sub get_institutional_code_format_handler {
                   6722:     my ($cmd, $tail, $client)   = @_;
                   6723:     my $userinput               = "$cmd:$tail";
                   6724: 
                   6725:     my $reply;
                   6726:     my($cdom,$course) = split(/:/,$tail);
                   6727:     my @pairs = split/\&/,$course;
                   6728:     my %instcodes = ();
                   6729:     my %codes = ();
                   6730:     my @codetitles = ();
                   6731:     my %cat_titles = ();
                   6732:     my %cat_order = ();
                   6733:     foreach (@pairs) {
                   6734: 	my ($key,$value) = split/=/,$_;
                   6735: 	$instcodes{&unescape($key)} = &unescape($value);
                   6736:     }
1.582   ! raeburn  6737:     my $formatreply; 
        !          6738:     eval {
        !          6739:         local($SIG{__DIE__})='DEFAULT';
        !          6740:         $formatreply = &localenroll::instcode_format($cdom,
        !          6741: 	   					     \%instcodes,
        !          6742: 						     \%codes,
        !          6743: 						     \@codetitles,
        !          6744: 						     \%cat_titles,
        !          6745: 						     \%cat_order);
        !          6746:     };
1.248     foxr     6747:     if ($formatreply eq 'ok') {
1.365     albertel 6748: 	my $codes_str = &Apache::lonnet::hash2str(%codes);
                   6749: 	my $codetitles_str = &Apache::lonnet::array2str(@codetitles);
                   6750: 	my $cat_titles_str = &Apache::lonnet::hash2str(%cat_titles);
                   6751: 	my $cat_order_str = &Apache::lonnet::hash2str(%cat_order);
1.248     foxr     6752: 	&Reply($client,
                   6753: 	       $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
                   6754: 	       .$cat_order_str."\n",
                   6755: 	       $userinput);
                   6756:     } else {
                   6757: 	# this else branch added by RF since if not ok, lonc will
                   6758: 	# hang waiting on reply until timeout.
                   6759: 	#
                   6760: 	&Reply($client, "format_error\n", $userinput);
                   6761:     }
                   6762:     
                   6763:     return 1;
                   6764: }
1.265     albertel 6765: &register_handler("autoinstcodeformat",
                   6766: 		  \&get_institutional_code_format_handler,0,1,0);
1.246     foxr     6767: 
1.345     raeburn  6768: sub get_institutional_defaults_handler {
                   6769:     my ($cmd, $tail, $client)   = @_;
                   6770:     my $userinput               = "$cmd:$tail";
                   6771: 
                   6772:     my $dom = $tail;
                   6773:     my %defaults_hash;
                   6774:     my @code_order;
                   6775:     my $outcome;
                   6776:     eval {
                   6777:         local($SIG{__DIE__})='DEFAULT';
                   6778:         $outcome = &localenroll::instcode_defaults($dom,\%defaults_hash,
                   6779:                                                    \@code_order);
                   6780:     };
                   6781:     if (!$@) {
                   6782:         if ($outcome eq 'ok') {
                   6783:             my $result='';
                   6784:             while (my ($key,$value) = each(%defaults_hash)) {
                   6785:                 $result.=&escape($key).'='.&escape($value).'&';
                   6786:             }
                   6787:             $result .= 'code_order='.&escape(join('&',@code_order));
1.387     albertel 6788:             &Reply($client,\$result,$userinput);
1.345     raeburn  6789:         } else {
                   6790:             &Reply($client,"error\n", $userinput);
                   6791:         }
                   6792:     } else {
                   6793:         &Failure($client,"unknown_cmd\n",$userinput);
                   6794:     }
                   6795: }
                   6796: &register_handler("autoinstcodedefaults",
                   6797:                   \&get_institutional_defaults_handler,0,1,0);
                   6798: 
1.416     raeburn  6799: sub get_possible_instcodes_handler {
                   6800:     my ($cmd, $tail, $client)   = @_;
                   6801:     my $userinput               = "$cmd:$tail";
                   6802: 
                   6803:     my $reply;
                   6804:     my $cdom = $tail;
1.417     raeburn  6805:     my (@codetitles,%cat_titles,%cat_order,@code_order);
1.582   ! raeburn  6806:     my $formatreply;
        !          6807:     eval {
        !          6808:         local($SIG{__DIE__})='DEFAULT';
        !          6809:         $formatreply = &localenroll::possible_instcodes($cdom,
        !          6810:                                                         \@codetitles,
        !          6811:                                                         \%cat_titles,
        !          6812:                                                         \%cat_order,
        !          6813:                                                         \@code_order);
        !          6814:     };
1.416     raeburn  6815:     if ($formatreply eq 'ok') {
                   6816:         my $result = join('&',map {&escape($_);} (@codetitles)).':';
1.417     raeburn  6817:         $result .= join('&',map {&escape($_);} (@code_order)).':';
1.416     raeburn  6818:         foreach my $key (keys(%cat_titles)) {
                   6819:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_titles{$key}).'&';
                   6820:         }
                   6821:         $result =~ s/\&$//;
                   6822:         $result .= ':';
                   6823:         foreach my $key (keys(%cat_order)) {
                   6824:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_order{$key}).'&';
                   6825:         }
                   6826:         $result =~ s/\&$//;
                   6827:         &Reply($client,\$result,$userinput);
                   6828:     } else {
                   6829:         &Reply($client, "format_error\n", $userinput);
                   6830:     }
                   6831:     return 1;
                   6832: }
                   6833: &register_handler("autopossibleinstcodes",
                   6834:                   \&get_possible_instcodes_handler,0,1,0);
                   6835: 
1.381     raeburn  6836: sub get_institutional_user_rules {
                   6837:     my ($cmd, $tail, $client)   = @_;
                   6838:     my $userinput               = "$cmd:$tail";
                   6839:     my $dom = &unescape($tail);
                   6840:     my (%rules_hash,@rules_order);
                   6841:     my $outcome;
                   6842:     eval {
                   6843:         local($SIG{__DIE__})='DEFAULT';
                   6844:         $outcome = &localenroll::username_rules($dom,\%rules_hash,\@rules_order);
                   6845:     };
                   6846:     if (!$@) {
                   6847:         if ($outcome eq 'ok') {
                   6848:             my $result;
                   6849:             foreach my $key (keys(%rules_hash)) {
                   6850:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6851:             }
                   6852:             $result =~ s/\&$//;
                   6853:             $result .= ':';
                   6854:             if (@rules_order > 0) {
                   6855:                 foreach my $item (@rules_order) {
                   6856:                     $result .= &escape($item).'&';
                   6857:                 }
                   6858:             }
                   6859:             $result =~ s/\&$//;
1.387     albertel 6860:             &Reply($client,\$result,$userinput);
1.381     raeburn  6861:         } else {
                   6862:             &Reply($client,"error\n", $userinput);
                   6863:         }
                   6864:     } else {
                   6865:         &Failure($client,"unknown_cmd\n",$userinput);
                   6866:     }
                   6867: }
                   6868: &register_handler("instuserrules",\&get_institutional_user_rules,0,1,0);
                   6869: 
1.389     raeburn  6870: sub get_institutional_id_rules {
                   6871:     my ($cmd, $tail, $client)   = @_;
                   6872:     my $userinput               = "$cmd:$tail";
                   6873:     my $dom = &unescape($tail);
                   6874:     my (%rules_hash,@rules_order);
                   6875:     my $outcome;
                   6876:     eval {
                   6877:         local($SIG{__DIE__})='DEFAULT';
                   6878:         $outcome = &localenroll::id_rules($dom,\%rules_hash,\@rules_order);
                   6879:     };
                   6880:     if (!$@) {
                   6881:         if ($outcome eq 'ok') {
                   6882:             my $result;
                   6883:             foreach my $key (keys(%rules_hash)) {
                   6884:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6885:             }
                   6886:             $result =~ s/\&$//;
                   6887:             $result .= ':';
                   6888:             if (@rules_order > 0) {
                   6889:                 foreach my $item (@rules_order) {
                   6890:                     $result .= &escape($item).'&';
                   6891:                 }
                   6892:             }
                   6893:             $result =~ s/\&$//;
                   6894:             &Reply($client,\$result,$userinput);
                   6895:         } else {
                   6896:             &Reply($client,"error\n", $userinput);
                   6897:         }
                   6898:     } else {
                   6899:         &Failure($client,"unknown_cmd\n",$userinput);
                   6900:     }
                   6901: }
                   6902: &register_handler("instidrules",\&get_institutional_id_rules,0,1,0);
                   6903: 
1.397     raeburn  6904: sub get_institutional_selfcreate_rules {
1.396     raeburn  6905:     my ($cmd, $tail, $client)   = @_;
                   6906:     my $userinput               = "$cmd:$tail";
                   6907:     my $dom = &unescape($tail);
                   6908:     my (%rules_hash,@rules_order);
                   6909:     my $outcome;
                   6910:     eval {
                   6911:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  6912:         $outcome = &localenroll::selfcreate_rules($dom,\%rules_hash,\@rules_order);
1.396     raeburn  6913:     };
                   6914:     if (!$@) {
                   6915:         if ($outcome eq 'ok') {
                   6916:             my $result;
                   6917:             foreach my $key (keys(%rules_hash)) {
                   6918:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6919:             }
                   6920:             $result =~ s/\&$//;
                   6921:             $result .= ':';
                   6922:             if (@rules_order > 0) {
                   6923:                 foreach my $item (@rules_order) {
                   6924:                     $result .= &escape($item).'&';
                   6925:                 }
                   6926:             }
                   6927:             $result =~ s/\&$//;
                   6928:             &Reply($client,\$result,$userinput);
                   6929:         } else {
                   6930:             &Reply($client,"error\n", $userinput);
                   6931:         }
                   6932:     } else {
                   6933:         &Failure($client,"unknown_cmd\n",$userinput);
                   6934:     }
                   6935: }
1.397     raeburn  6936: &register_handler("instemailrules",\&get_institutional_selfcreate_rules,0,1,0);
1.396     raeburn  6937: 
1.575     raeburn  6938: sub get_unamemap_rules {
                   6939:     my ($cmd, $tail, $client)   = @_;
                   6940:     my $userinput               = "$cmd:$tail";
                   6941:     my $dom = &unescape($tail);
                   6942:     my (%rules_hash,@rules_order);
                   6943:     my $outcome;
                   6944:     eval {
                   6945:         local($SIG{__DIE__})='DEFAULT';
                   6946:         $outcome = &localenroll::unamemap_rules($dom,\%rules_hash,\@rules_order);
                   6947:     };
                   6948:     if (!$@) {
                   6949:         if ($outcome eq 'ok') {
                   6950:             my $result;
                   6951:             foreach my $key (keys(%rules_hash)) {
                   6952:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6953:             }
                   6954:             $result =~ s/\&$//;
                   6955:             $result .= ':';
                   6956:             if (@rules_order > 0) {
                   6957:                 foreach my $item (@rules_order) {
                   6958:                     $result .= &escape($item).'&';
                   6959:                 }
                   6960:             }
                   6961:             $result =~ s/\&$//;
                   6962:             &Reply($client,\$result,$userinput);
                   6963:         } else {
                   6964:             &Reply($client,"error\n", $userinput);
                   6965:         }
                   6966:     } else {
                   6967:         &Failure($client,"unknown_cmd\n",$userinput);
                   6968:     }
                   6969: }
                   6970: &register_handler("unamemaprules",\&get_unamemap_rules,0,1,0);
1.381     raeburn  6971: 
                   6972: sub institutional_username_check {
                   6973:     my ($cmd, $tail, $client)   = @_;
                   6974:     my $userinput               = "$cmd:$tail";
                   6975:     my %rulecheck;
                   6976:     my $outcome;
                   6977:     my ($udom,$uname,@rules) = split(/:/,$tail);
                   6978:     $udom = &unescape($udom);
                   6979:     $uname = &unescape($uname);
                   6980:     @rules = map {&unescape($_);} (@rules);
                   6981:     eval {
                   6982:         local($SIG{__DIE__})='DEFAULT';
                   6983:         $outcome = &localenroll::username_check($udom,$uname,\@rules,\%rulecheck);
                   6984:     };
                   6985:     if (!$@) {
                   6986:         if ($outcome eq 'ok') {
                   6987:             my $result='';
                   6988:             foreach my $key (keys(%rulecheck)) {
                   6989:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6990:             }
1.387     albertel 6991:             &Reply($client,\$result,$userinput);
1.381     raeburn  6992:         } else {
                   6993:             &Reply($client,"error\n", $userinput);
                   6994:         }
                   6995:     } else {
                   6996:         &Failure($client,"unknown_cmd\n",$userinput);
                   6997:     }
                   6998: }
                   6999: &register_handler("instrulecheck",\&institutional_username_check,0,1,0);
                   7000: 
1.389     raeburn  7001: sub institutional_id_check {
                   7002:     my ($cmd, $tail, $client)   = @_;
                   7003:     my $userinput               = "$cmd:$tail";
                   7004:     my %rulecheck;
                   7005:     my $outcome;
                   7006:     my ($udom,$id,@rules) = split(/:/,$tail);
                   7007:     $udom = &unescape($udom);
                   7008:     $id = &unescape($id);
                   7009:     @rules = map {&unescape($_);} (@rules);
                   7010:     eval {
                   7011:         local($SIG{__DIE__})='DEFAULT';
                   7012:         $outcome = &localenroll::id_check($udom,$id,\@rules,\%rulecheck);
                   7013:     };
                   7014:     if (!$@) {
                   7015:         if ($outcome eq 'ok') {
                   7016:             my $result='';
                   7017:             foreach my $key (keys(%rulecheck)) {
                   7018:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   7019:             }
                   7020:             &Reply($client,\$result,$userinput);
                   7021:         } else {
                   7022:             &Reply($client,"error\n", $userinput);
                   7023:         }
                   7024:     } else {
                   7025:         &Failure($client,"unknown_cmd\n",$userinput);
                   7026:     }
                   7027: }
                   7028: &register_handler("instidrulecheck",\&institutional_id_check,0,1,0);
1.345     raeburn  7029: 
1.397     raeburn  7030: sub institutional_selfcreate_check {
1.396     raeburn  7031:     my ($cmd, $tail, $client)   = @_;
                   7032:     my $userinput               = "$cmd:$tail";
                   7033:     my %rulecheck;
                   7034:     my $outcome;
                   7035:     my ($udom,$email,@rules) = split(/:/,$tail);
                   7036:     $udom = &unescape($udom);
                   7037:     $email = &unescape($email);
                   7038:     @rules = map {&unescape($_);} (@rules);
                   7039:     eval {
                   7040:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  7041:         $outcome = &localenroll::selfcreate_check($udom,$email,\@rules,\%rulecheck);
1.396     raeburn  7042:     };
                   7043:     if (!$@) {
                   7044:         if ($outcome eq 'ok') {
                   7045:             my $result='';
                   7046:             foreach my $key (keys(%rulecheck)) {
                   7047:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   7048:             }
                   7049:             &Reply($client,\$result,$userinput);
                   7050:         } else {
                   7051:             &Reply($client,"error\n", $userinput);
                   7052:         }
                   7053:     } else {
                   7054:         &Failure($client,"unknown_cmd\n",$userinput);
                   7055:     }
                   7056: }
1.397     raeburn  7057: &register_handler("instselfcreatecheck",\&institutional_selfcreate_check,0,1,0);
1.396     raeburn  7058: 
1.317     raeburn  7059: # Get domain specific conditions for import of student photographs to a course
                   7060: #
                   7061: # Retrieves information from photo_permission subroutine in localenroll.
                   7062: # Returns outcome (ok) if no processing errors, and whether course owner is 
                   7063: # required to accept conditions of use (yes/no).
                   7064: #
                   7065: #    
                   7066: sub photo_permission_handler {
                   7067:     my ($cmd, $tail, $client)   = @_;
                   7068:     my $userinput               = "$cmd:$tail";
                   7069:     my $cdom = $tail;
                   7070:     my ($perm_reqd,$conditions);
1.320     albertel 7071:     my $outcome;
                   7072:     eval {
                   7073: 	local($SIG{__DIE__})='DEFAULT';
                   7074: 	$outcome = &localenroll::photo_permission($cdom,\$perm_reqd,
                   7075: 						  \$conditions);
                   7076:     };
                   7077:     if (!$@) {
                   7078: 	&Reply($client, &escape($outcome.':'.$perm_reqd.':'. $conditions)."\n",
                   7079: 	       $userinput);
                   7080:     } else {
                   7081: 	&Failure($client,"unknown_cmd\n",$userinput);
                   7082:     }
                   7083:     return 1;
1.317     raeburn  7084: }
                   7085: &register_handler("autophotopermission",\&photo_permission_handler,0,1,0);
                   7086: 
                   7087: #
                   7088: # Checks if student photo is available for a user in the domain, in the user's
                   7089: # directory (in /userfiles/internal/studentphoto.jpg).
                   7090: # Uses localstudentphoto:fetch() to ensure there is an up to date copy of
                   7091: # the student's photo.   
                   7092: 
                   7093: sub photo_check_handler {
                   7094:     my ($cmd, $tail, $client)   = @_;
                   7095:     my $userinput               = "$cmd:$tail";
                   7096:     my ($udom,$uname,$pid) = split(/:/,$tail);
                   7097:     $udom = &unescape($udom);
                   7098:     $uname = &unescape($uname);
                   7099:     $pid = &unescape($pid);
                   7100:     my $path=&propath($udom,$uname).'/userfiles/internal/';
                   7101:     if (!-e $path) {
                   7102:         &mkpath($path);
                   7103:     }
                   7104:     my $response;
                   7105:     my $result = &localstudentphoto::fetch($udom,$uname,$pid,\$response);
                   7106:     $result .= ':'.$response;
                   7107:     &Reply($client, &escape($result)."\n",$userinput);
1.320     albertel 7108:     return 1;
1.317     raeburn  7109: }
                   7110: &register_handler("autophotocheck",\&photo_check_handler,0,1,0);
                   7111: 
                   7112: #
                   7113: # Retrieve information from localenroll about whether to provide a button     
                   7114: # for users who have enbled import of student photos to initiate an 
                   7115: # update of photo files for registered students. Also include 
                   7116: # comment to display alongside button.  
                   7117: 
                   7118: sub photo_choice_handler {
                   7119:     my ($cmd, $tail, $client) = @_;
                   7120:     my $userinput             = "$cmd:$tail";
                   7121:     my $cdom                  = &unescape($tail);
1.320     albertel 7122:     my ($update,$comment);
                   7123:     eval {
                   7124: 	local($SIG{__DIE__})='DEFAULT';
                   7125: 	($update,$comment)    = &localenroll::manager_photo_update($cdom);
                   7126:     };
                   7127:     if (!$@) {
                   7128: 	&Reply($client,&escape($update).':'.&escape($comment)."\n",$userinput);
                   7129:     } else {
                   7130: 	&Failure($client,"unknown_cmd\n",$userinput);
                   7131:     }
                   7132:     return 1;
1.317     raeburn  7133: }
                   7134: &register_handler("autophotochoice",\&photo_choice_handler,0,1,0);
                   7135: 
1.265     albertel 7136: #
                   7137: # Gets a student's photo to exist (in the correct image type) in the user's 
                   7138: # directory.
                   7139: # Formal Parameters:
                   7140: #    $cmd     - The command request that got us dispatched.
                   7141: #    $tail    - A colon separated set of words that will be split into:
                   7142: #               $domain - student's domain
                   7143: #               $uname  - student username
                   7144: #               $type   - image type desired
                   7145: #    $client  - The socket open on the client.
                   7146: # Returns:
                   7147: #    1 - continue processing.
1.317     raeburn  7148: 
1.265     albertel 7149: sub student_photo_handler {
                   7150:     my ($cmd, $tail, $client) = @_;
1.317     raeburn  7151:     my ($domain,$uname,$ext,$type) = split(/:/, $tail);
1.265     albertel 7152: 
1.317     raeburn  7153:     my $path=&propath($domain,$uname). '/userfiles/internal/';
                   7154:     my $filename = 'studentphoto.'.$ext;
                   7155:     if ($type eq 'thumbnail') {
                   7156:         $filename = 'studentphoto_tn.'.$ext;
                   7157:     }
                   7158:     if (-e $path.$filename) {
1.265     albertel 7159: 	&Reply($client,"ok\n","$cmd:$tail");
                   7160: 	return 1;
                   7161:     }
                   7162:     &mkpath($path);
1.317     raeburn  7163:     my $file;
                   7164:     if ($type eq 'thumbnail') {
1.320     albertel 7165: 	eval {
                   7166: 	    local($SIG{__DIE__})='DEFAULT';
                   7167: 	    $file=&localstudentphoto::fetch_thumbnail($domain,$uname);
                   7168: 	};
1.317     raeburn  7169:     } else {
                   7170:         $file=&localstudentphoto::fetch($domain,$uname);
                   7171:     }
1.265     albertel 7172:     if (!$file) {
                   7173: 	&Failure($client,"unavailable\n","$cmd:$tail");
                   7174: 	return 1;
                   7175:     }
1.317     raeburn  7176:     if (!-e $path.$filename) { &convert_photo($file,$path.$filename); }
                   7177:     if (-e $path.$filename) {
1.265     albertel 7178: 	&Reply($client,"ok\n","$cmd:$tail");
                   7179: 	return 1;
                   7180:     }
                   7181:     &Failure($client,"unable_to_convert\n","$cmd:$tail");
                   7182:     return 1;
                   7183: }
                   7184: &register_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
1.246     foxr     7185: 
1.361     raeburn  7186: sub inst_usertypes_handler {
                   7187:     my ($cmd, $domain, $client) = @_;
                   7188:     my $res;
                   7189:     my $userinput = $cmd.":".$domain; # For logging purposes.
1.370     albertel 7190:     my (%typeshash,@order,$result);
                   7191:     eval {
                   7192: 	local($SIG{__DIE__})='DEFAULT';
                   7193: 	$result=&localenroll::inst_usertypes($domain,\%typeshash,\@order);
                   7194:     };
                   7195:     if ($result eq 'ok') {
1.361     raeburn  7196:         if (keys(%typeshash) > 0) {
                   7197:             foreach my $key (keys(%typeshash)) {
                   7198:                 $res.=&escape($key).'='.&escape($typeshash{$key}).'&';
                   7199:             }
                   7200:         }
                   7201:         $res=~s/\&$//;
                   7202:         $res .= ':';
                   7203:         if (@order > 0) {
                   7204:             foreach my $item (@order) {
                   7205:                 $res .= &escape($item).'&';
                   7206:             }
                   7207:         }
                   7208:         $res=~s/\&$//;
                   7209:     }
1.387     albertel 7210:     &Reply($client, \$res, $userinput);
1.361     raeburn  7211:     return 1;
                   7212: }
                   7213: &register_handler("inst_usertypes", \&inst_usertypes_handler, 0, 1, 0);
                   7214: 
1.264     albertel 7215: # mkpath makes all directories for a file, expects an absolute path with a
                   7216: # file or a trailing / if just a dir is passed
                   7217: # returns 1 on success 0 on failure
                   7218: sub mkpath {
                   7219:     my ($file)=@_;
                   7220:     my @parts=split(/\//,$file,-1);
                   7221:     my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
                   7222:     for (my $i=3;$i<= ($#parts-1);$i++) {
1.265     albertel 7223: 	$now.='/'.$parts[$i]; 
1.264     albertel 7224: 	if (!-e $now) {
                   7225: 	    if  (!mkdir($now,0770)) { return 0; }
                   7226: 	}
                   7227:     }
                   7228:     return 1;
                   7229: }
                   7230: 
1.207     foxr     7231: #---------------------------------------------------------------
                   7232: #
                   7233: #   Getting, decoding and dispatching requests:
                   7234: #
                   7235: #
                   7236: #   Get a Request:
                   7237: #   Gets a Request message from the client.  The transaction
                   7238: #   is defined as a 'line' of text.  We remove the new line
                   7239: #   from the text line.  
1.226     foxr     7240: #
1.211     albertel 7241: sub get_request {
1.207     foxr     7242:     my $input = <$client>;
                   7243:     chomp($input);
1.226     foxr     7244: 
1.234     foxr     7245:     &Debug("get_request: Request = $input\n");
1.207     foxr     7246: 
                   7247:     &status('Processing '.$clientname.':'.$input);
                   7248: 
                   7249:     return $input;
                   7250: }
1.212     foxr     7251: #---------------------------------------------------------------
                   7252: #
                   7253: #  Process a request.  This sub should shrink as each action
                   7254: #  gets farmed out into a separat sub that is registered 
                   7255: #  with the dispatch hash.  
                   7256: #
                   7257: # Parameters:
                   7258: #    user_input   - The request received from the client (lonc).
1.525     raeburn  7259: #
1.212     foxr     7260: # Returns:
                   7261: #    true to keep processing, false if caller should exit.
                   7262: #
                   7263: sub process_request {
1.525     raeburn  7264:     my ($userinput) = @_; # Easier for now to break style than to
                   7265:                           # fix all the userinput -> user_input.
1.212     foxr     7266:     my $wasenc    = 0;		# True if request was encrypted.
                   7267: # ------------------------------------------------------------ See if encrypted
1.322     albertel 7268:     # for command
                   7269:     # sethost:<server>
                   7270:     # <command>:<args>
                   7271:     #   we just send it to the processor
                   7272:     # for
                   7273:     # sethost:<server>:<command>:<args>
                   7274:     #  we do the implict set host and then do the command
                   7275:     if ($userinput =~ /^sethost:/) {
                   7276: 	(my $cmd,my $newid,$userinput) = split(':',$userinput,3);
                   7277: 	if (defined($userinput)) {
                   7278: 	    &sethost("$cmd:$newid");
                   7279: 	} else {
                   7280: 	    $userinput = "$cmd:$newid";
                   7281: 	}
                   7282:     }
                   7283: 
1.212     foxr     7284:     if ($userinput =~ /^enc/) {
                   7285: 	$userinput = decipher($userinput);
                   7286: 	$wasenc=1;
                   7287: 	if(!$userinput) {	# Cipher not defined.
1.251     foxr     7288: 	    &Failure($client, "error: Encrypted data without negotated key\n");
1.212     foxr     7289: 	    return 0;
                   7290: 	}
                   7291:     }
                   7292:     Debug("process_request: $userinput\n");
                   7293:     
1.213     foxr     7294:     #  
                   7295:     #   The 'correct way' to add a command to lond is now to
                   7296:     #   write a sub to execute it and Add it to the command dispatch
                   7297:     #   hash via a call to register_handler..  The comments to that
                   7298:     #   sub should give you enough to go on to show how to do this
                   7299:     #   along with the examples that are building up as this code
                   7300:     #   is getting refactored.   Until all branches of the
                   7301:     #   if/elseif monster below have been factored out into
                   7302:     #   separate procesor subs, if the dispatch hash is missing
                   7303:     #   the command keyword, we will fall through to the remainder
                   7304:     #   of the if/else chain below in order to keep this thing in 
                   7305:     #   working order throughout the transmogrification.
                   7306: 
                   7307:     my ($command, $tail) = split(/:/, $userinput, 2);
                   7308:     chomp($command);
                   7309:     chomp($tail);
                   7310:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
1.214     foxr     7311:     $command =~ s/(\r)//;	# And this too for parameterless commands.
                   7312:     if(!$tail) {
                   7313: 	$tail ="";		# defined but blank.
                   7314:     }
1.213     foxr     7315: 
                   7316:     &Debug("Command received: $command, encoded = $wasenc");
                   7317: 
                   7318:     if(defined $Dispatcher{$command}) {
                   7319: 
                   7320: 	my $dispatch_info = $Dispatcher{$command};
                   7321: 	my $handler       = $$dispatch_info[0];
                   7322: 	my $need_encode   = $$dispatch_info[1];
                   7323: 	my $client_types  = $$dispatch_info[2];
                   7324: 	Debug("Matched dispatch hash: mustencode: $need_encode "
                   7325: 	      ."ClientType $client_types");
                   7326:       
                   7327: 	#  Validate the request:
                   7328:       
                   7329: 	my $ok = 1;
                   7330: 	my $requesterprivs = 0;
                   7331: 	if(&isClient()) {
                   7332: 	    $requesterprivs |= $CLIENT_OK;
                   7333: 	}
                   7334: 	if(&isManager()) {
                   7335: 	    $requesterprivs |= $MANAGER_OK;
                   7336: 	}
                   7337: 	if($need_encode && (!$wasenc)) {
                   7338: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
                   7339: 	    $ok = 0;
                   7340: 	}
                   7341: 	if(($client_types & $requesterprivs) == 0) {
                   7342: 	    Debug("Client not privileged to do this operation");
                   7343: 	    $ok = 0;
                   7344: 	}
1.525     raeburn  7345:         if ($ok) {
1.535     raeburn  7346:             my $realcommand = $command;
                   7347:             if ($command eq 'querysend') {
                   7348:                 my ($query,$rest)=split(/\:/,$tail,2);
                   7349:                 $query=~s/\n*$//g;
                   7350:                 my @possqueries = 
                   7351:                     qw(userlog courselog fetchenrollment institutionalphotos usersearch instdirsearch getinstuser getmultinstusers);
                   7352:                 if (grep(/^\Q$query\E$/,@possqueries)) {
                   7353:                     $command .= '_'.$query;
                   7354:                 } elsif ($query eq 'prepare activity log') {
                   7355:                     $command .= '_activitylog';
                   7356:                 }
                   7357:             }
1.525     raeburn  7358:             if (ref($trust{$command}) eq 'HASH') {
                   7359:                 my $donechecks;
                   7360:                 if ($trust{$command}{'anywhere'}) {
                   7361:                    $donechecks = 1;
                   7362:                 } elsif ($trust{$command}{'manageronly'}) {
                   7363:                     unless (&isManager()) {
                   7364:                         $ok = 0;
                   7365:                     }
                   7366:                     $donechecks = 1;
                   7367:                 } elsif ($trust{$command}{'institutiononly'}) {
                   7368:                     unless ($clientsameinst) {
                   7369:                         $ok = 0;
                   7370:                     }
                   7371:                     $donechecks = 1;
                   7372:                 } elsif ($clientsameinst) {
                   7373:                     $donechecks = 1;
                   7374:                 }
                   7375:                 unless ($donechecks) {
                   7376:                     foreach my $rule (keys(%{$trust{$command}})) {
                   7377:                         next if ($rule eq 'remote');
                   7378:                         if ($trust{$command}{$rule}) {
                   7379:                             if ($clientprohibited{$rule}) {
                   7380:                                 $ok = 0;
                   7381:                             } else {
                   7382:                                 $ok = 1;
                   7383:                                 $donechecks = 1;
                   7384:                                 last;
                   7385:                             }
                   7386:                         }
                   7387:                     }
                   7388:                 }
                   7389:                 unless ($donechecks) {
                   7390:                     if ($trust{$command}{'remote'}) {
                   7391:                         if ($clientremoteok) {
                   7392:                             $ok = 1;
                   7393:                         } else {
                   7394:                             $ok = 0;
                   7395:                         } 
                   7396:                     }
                   7397:                 }
                   7398:             }
1.535     raeburn  7399:             $command = $realcommand;
1.525     raeburn  7400:         }
1.213     foxr     7401: 
                   7402: 	if($ok) {
                   7403: 	    Debug("Dispatching to handler $command $tail");
                   7404: 	    my $keep_going = &$handler($command, $tail, $client);
                   7405: 	    return $keep_going;
                   7406: 	} else {
                   7407: 	    Debug("Refusing to dispatch because client did not match requirements");
                   7408: 	    Failure($client, "refused\n", $userinput);
                   7409: 	    return 1;
                   7410: 	}
1.525     raeburn  7411:     }
1.213     foxr     7412: 
1.262     foxr     7413:     print $client "unknown_cmd\n";
1.212     foxr     7414: # -------------------------------------------------------------------- complete
                   7415:     Debug("process_request - returning 1");
                   7416:     return 1;
                   7417: }
1.207     foxr     7418: #
                   7419: #   Decipher encoded traffic
                   7420: #  Parameters:
                   7421: #     input      - Encoded data.
                   7422: #  Returns:
                   7423: #     Decoded data or undef if encryption key was not yet negotiated.
                   7424: #  Implicit input:
                   7425: #     cipher  - This global holds the negotiated encryption key.
                   7426: #
1.211     albertel 7427: sub decipher {
1.207     foxr     7428:     my ($input)  = @_;
                   7429:     my $output = '';
1.212     foxr     7430:     
                   7431:     
1.207     foxr     7432:     if($cipher) {
                   7433: 	my($enc, $enclength, $encinput) = split(/:/, $input);
                   7434: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
                   7435: 	    $output .= 
                   7436: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
                   7437: 	}
                   7438: 	return substr($output, 0, $enclength);
                   7439:     } else {
                   7440: 	return undef;
                   7441:     }
                   7442: }
                   7443: 
                   7444: #
                   7445: #   Register a command processor.  This function is invoked to register a sub
                   7446: #   to process a request.  Once registered, the ProcessRequest sub can automatically
                   7447: #   dispatch requests to an appropriate sub, and do the top level validity checking
                   7448: #   as well:
                   7449: #    - Is the keyword recognized.
                   7450: #    - Is the proper client type attempting the request.
                   7451: #    - Is the request encrypted if it has to be.
                   7452: #   Parameters:
                   7453: #    $request_name         - Name of the request being registered.
                   7454: #                           This is the command request that will match
                   7455: #                           against the hash keywords to lookup the information
                   7456: #                           associated with the dispatch information.
                   7457: #    $procedure           - Reference to a sub to call to process the request.
                   7458: #                           All subs get called as follows:
                   7459: #                             Procedure($cmd, $tail, $replyfd, $key)
                   7460: #                             $cmd    - the actual keyword that invoked us.
                   7461: #                             $tail   - the tail of the request that invoked us.
                   7462: #                             $replyfd- File descriptor connected to the client
                   7463: #    $must_encode          - True if the request must be encoded to be good.
                   7464: #    $client_ok            - True if it's ok for a client to request this.
                   7465: #    $manager_ok           - True if it's ok for a manager to request this.
                   7466: # Side effects:
                   7467: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
                   7468: #      - On failure, the program will die as it's a bad internal bug to try to 
                   7469: #        register a duplicate command handler.
                   7470: #
1.211     albertel 7471: sub register_handler {
1.212     foxr     7472:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
1.207     foxr     7473: 
                   7474:     #  Don't allow duplication#
                   7475:    
                   7476:     if (defined $Dispatcher{$request_name}) {
                   7477: 	die "Attempting to define a duplicate request handler for $request_name\n";
                   7478:     }
                   7479:     #   Build the client type mask:
                   7480:     
                   7481:     my $client_type_mask = 0;
                   7482:     if($client_ok) {
                   7483: 	$client_type_mask  |= $CLIENT_OK;
                   7484:     }
                   7485:     if($manager_ok) {
                   7486: 	$client_type_mask  |= $MANAGER_OK;
                   7487:     }
                   7488:    
                   7489:     #  Enter the hash:
                   7490:       
                   7491:     my @entry = ($procedure, $must_encode, $client_type_mask);
                   7492:    
                   7493:     $Dispatcher{$request_name} = \@entry;
                   7494:    
                   7495: }
                   7496: 
                   7497: 
                   7498: #------------------------------------------------------------------
                   7499: 
                   7500: 
                   7501: 
                   7502: 
1.141     foxr     7503: #
1.96      foxr     7504: #  Convert an error return code from lcpasswd to a string value.
                   7505: #
                   7506: sub lcpasswdstrerror {
                   7507:     my $ErrorCode = shift;
1.97      foxr     7508:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96      foxr     7509: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
                   7510:     } else {
1.98      foxr     7511: 	return $passwderrors[$ErrorCode];
1.96      foxr     7512:     }
                   7513: }
                   7514: 
1.23      harris41 7515: # grabs exception and records it to log before exiting
                   7516: sub catchexception {
1.27      albertel 7517:     my ($error)=@_;
1.25      www      7518:     $SIG{'QUIT'}='DEFAULT';
                   7519:     $SIG{__DIE__}='DEFAULT';
1.165     albertel 7520:     &status("Catching exception");
1.190     albertel 7521:     &logthis("<font color='red'>CRITICAL: "
1.373     albertel 7522:      ."ABNORMAL EXIT. Child $$ for server ".$perlvar{'lonHostID'}." died through "
1.27      albertel 7523:      ."a crash with this error msg->[$error]</font>");
1.57      www      7524:     &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27      albertel 7525:     if ($client) { print $client "error: $error\n"; }
1.59      www      7526:     $server->close();
1.27      albertel 7527:     die($error);
1.23      harris41 7528: }
1.63      www      7529: sub timeout {
1.165     albertel 7530:     &status("Handling Timeout");
1.190     albertel 7531:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
1.63      www      7532:     &catchexception('Timeout');
                   7533: }
1.22      harris41 7534: # -------------------------------- Set signal handlers to record abnormal exits
                   7535: 
1.226     foxr     7536: 
1.22      harris41 7537: $SIG{'QUIT'}=\&catchexception;
                   7538: $SIG{__DIE__}=\&catchexception;
                   7539: 
1.81      matthew  7540: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95      harris41 7541: &status("Read loncapa.conf and loncapa_apache.conf");
                   7542: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141     foxr     7543: %perlvar=%{$perlvarref};
1.80      harris41 7544: undef $perlvarref;
1.19      www      7545: 
1.35      harris41 7546: # ----------------------------- Make sure this process is running from user=www
                   7547: my $wwwid=getpwnam('www');
                   7548: if ($wwwid!=$<) {
1.581     raeburn  7549:    my $emailto="$perlvar{'lonAdmEMail'} $perlvar{'lonSysEMail'}";
1.134     albertel 7550:    my $subj="LON: $currenthostid User ID mismatch";
1.550     raeburn  7551:    system("echo 'User ID mismatch.  lond must be run as user www.' |".
                   7552:           " mail -s '$subj' $emailto > /dev/null");
1.35      harris41 7553:    exit 1;
                   7554: }
                   7555: 
1.19      www      7556: # --------------------------------------------- Check if other instance running
                   7557: 
                   7558: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
                   7559: 
                   7560: if (-e $pidfile) {
                   7561:    my $lfh=IO::File->new("$pidfile");
                   7562:    my $pide=<$lfh>;
                   7563:    chomp($pide);
1.29      harris41 7564:    if (kill 0 => $pide) { die "already running"; }
1.19      www      7565: }
1.1       albertel 7566: 
                   7567: # ------------------------------------------------------------- Read hosts file
                   7568: 
                   7569: 
                   7570: 
                   7571: # establish SERVER socket, bind and listen.
                   7572: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
                   7573:                                 Type      => SOCK_STREAM,
                   7574:                                 Proto     => 'tcp',
1.469     foxr     7575:                                 ReuseAddr     => 1,
1.1       albertel 7576:                                 Listen    => 10 )
1.29      harris41 7577:   or die "making socket: $@\n";
1.1       albertel 7578: 
                   7579: # --------------------------------------------------------- Do global variables
                   7580: 
                   7581: # global variables
                   7582: 
1.134     albertel 7583: my %children               = ();       # keys are current child process IDs
1.1       albertel 7584: 
                   7585: sub REAPER {                        # takes care of dead children
                   7586:     $SIG{CHLD} = \&REAPER;
1.165     albertel 7587:     &status("Handling child death");
1.178     foxr     7588:     my $pid;
                   7589:     do {
                   7590: 	$pid = waitpid(-1,&WNOHANG());
                   7591: 	if (defined($children{$pid})) {
                   7592: 	    &logthis("Child $pid died");
                   7593: 	    delete($children{$pid});
1.183     albertel 7594: 	} elsif ($pid > 0) {
1.178     foxr     7595: 	    &logthis("Unknown Child $pid died");
                   7596: 	}
                   7597:     } while ( $pid > 0 );
                   7598:     foreach my $child (keys(%children)) {
                   7599: 	$pid = waitpid($child,&WNOHANG());
                   7600: 	if ($pid > 0) {
                   7601: 	    &logthis("Child $child - $pid looks like we missed it's death");
                   7602: 	    delete($children{$pid});
                   7603: 	}
1.176     albertel 7604:     }
1.165     albertel 7605:     &status("Finished Handling child death");
1.1       albertel 7606: }
                   7607: 
                   7608: sub HUNTSMAN {                      # signal handler for SIGINT
1.165     albertel 7609:     &status("Killing children (INT)");
1.1       albertel 7610:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
                   7611:     kill 'INT' => keys %children;
1.59      www      7612:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1       albertel 7613:     my $execdir=$perlvar{'lonDaemons'};
                   7614:     unlink("$execdir/logs/lond.pid");
1.190     albertel 7615:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.165     albertel 7616:     &status("Done killing children");
1.1       albertel 7617:     exit;                           # clean up with dignity
                   7618: }
                   7619: 
                   7620: sub HUPSMAN {                      # signal handler for SIGHUP
                   7621:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
1.165     albertel 7622:     &status("Killing children for restart (HUP)");
1.1       albertel 7623:     kill 'INT' => keys %children;
1.59      www      7624:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.190     albertel 7625:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.134     albertel 7626:     my $execdir=$perlvar{'lonDaemons'};
1.30      harris41 7627:     unlink("$execdir/logs/lond.pid");
1.165     albertel 7628:     &status("Restarting self (HUP)");
1.1       albertel 7629:     exec("$execdir/lond");         # here we go again
                   7630: }
                   7631: 
1.144     foxr     7632: #
1.148     foxr     7633: #  Reload the Apache daemon's state.
1.150     foxr     7634: #  This is done by invoking /home/httpd/perl/apachereload
                   7635: #  a setuid perl script that can be root for us to do this job.
1.148     foxr     7636: #
                   7637: sub ReloadApache {
1.473     raeburn  7638: # --------------------------- Handle case of another apachereload process (locking)
1.474     raeburn  7639:     if (&LONCAPA::try_to_lock('/tmp/lock_apachereload')) {
                   7640:         my $execdir = $perlvar{'lonDaemons'};
                   7641:         my $script  = $execdir."/apachereload";
                   7642:         system($script);
                   7643:         unlink('/tmp/lock_apachereload'); #  Remove the lock file.
                   7644:     }
1.148     foxr     7645: }
                   7646: 
                   7647: #
1.144     foxr     7648: #   Called in response to a USR2 signal.
                   7649: #   - Reread hosts.tab
                   7650: #   - All children connected to hosts that were removed from hosts.tab
                   7651: #     are killed via SIGINT
                   7652: #   - All children connected to previously existing hosts are sent SIGUSR1
                   7653: #   - Our internal hosts hash is updated to reflect the new contents of
                   7654: #     hosts.tab causing connections from hosts added to hosts.tab to
                   7655: #     now be honored.
                   7656: #
                   7657: sub UpdateHosts {
1.165     albertel 7658:     &status("Reload hosts.tab");
1.147     foxr     7659:     logthis('<font color="blue"> Updating connections </font>');
1.148     foxr     7660:     #
                   7661:     #  The %children hash has the set of IP's we currently have children
                   7662:     #  on.  These need to be matched against records in the hosts.tab
                   7663:     #  Any ip's no longer in the table get killed off they correspond to
                   7664:     #  either dropped or changed hosts.  Note that the re-read of the table
                   7665:     #  will take care of new and changed hosts as connections come into being.
                   7666: 
1.371     albertel 7667:     &Apache::lonnet::reset_hosts_info();
1.532     raeburn  7668:     my %active;
1.148     foxr     7669: 
1.368     albertel 7670:     foreach my $child (keys(%children)) {
1.148     foxr     7671: 	my $childip = $children{$child};
1.374     albertel 7672: 	if ($childip ne '127.0.0.1'
                   7673: 	    && !defined(&Apache::lonnet::get_hosts_from_ip($childip))) {
1.149     foxr     7674: 	    logthis('<font color="blue"> UpdateHosts killing child '
                   7675: 		    ." $child for ip $childip </font>");
1.148     foxr     7676: 	    kill('INT', $child);
1.149     foxr     7677: 	} else {
1.532     raeburn  7678:             $active{$child} = $childip;
1.149     foxr     7679: 	    logthis('<font color="green"> keeping child for ip '
                   7680: 		    ." $childip (pid=$child) </font>");
1.148     foxr     7681: 	}
                   7682:     }
1.532     raeburn  7683: 
                   7684:     my %oldconf = %secureconf;
                   7685:     my %connchange;
1.555     raeburn  7686:     if (lonssl::Read_Connect_Config(\%secureconf,\%perlvar,\%crlchecked) eq 'ok') {
1.545     raeburn  7687:         logthis('<font color="blue"> Reloaded SSL connection rules and cleared CRL checking history </font>');
1.532     raeburn  7688:     } else {
1.545     raeburn  7689:         logthis('<font color="yellow"> Failed to reload SSL connection rules and clear CRL checking history </font>');
1.532     raeburn  7690:     }
                   7691:     if ((ref($oldconf{'connfrom'}) eq 'HASH') && (ref($secureconf{'connfrom'}) eq 'HASH')) {
                   7692:         foreach my $type ('dom','intdom','other') {
                   7693:             if ((($oldconf{'connfrom'}{$type} eq 'no') && ($secureconf{'connfrom'}{$type} eq 'req')) ||
                   7694:                 (($oldconf{'connfrom'}{$type} eq 'req') && ($secureconf{'connfrom'}{$type} eq 'no'))) {
                   7695:                 $connchange{$type} = 1;
                   7696:             }
                   7697:         }
                   7698:     }
                   7699:     if (keys(%connchange)) {
                   7700:         foreach my $child (keys(%active)) {
                   7701:             my $childip = $active{$child};
                   7702:             if ($childip ne '127.0.0.1') {
                   7703:                 my $childhostname  = gethostbyaddr(Socket::inet_aton($childip),AF_INET);
                   7704:                 if ($childhostname ne '') {
                   7705:                     my $childlonhost = &Apache::lonnet::get_server_homeID($childhostname);
                   7706:                     my ($samedom,$sameinst) = &set_client_info($childlonhost);
                   7707:                     if ($samedom) {
                   7708:                         if ($connchange{'dom'}) {
                   7709:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7710:                                    ." $child for ip $childip </font>");
                   7711:                             kill('INT', $child);
                   7712:                         }
                   7713:                     } elsif ($sameinst) {
                   7714:                         if ($connchange{'intdom'}) {
                   7715:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7716:                                    ." $child for ip $childip </font>");
                   7717:                            kill('INT', $child);
                   7718:                         }
                   7719:                     } else {
                   7720:                         if ($connchange{'other'}) {
                   7721:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7722:                                    ." $child for ip $childip </font>");
                   7723:                             kill('INT', $child);
                   7724:                         }
                   7725:                     }
                   7726:                 }
                   7727:             }
                   7728:         }
                   7729:     }
1.148     foxr     7730:     ReloadApache;
1.165     albertel 7731:     &status("Finished reloading hosts.tab");
1.144     foxr     7732: }
                   7733: 
1.57      www      7734: sub checkchildren {
1.165     albertel 7735:     &status("Checking on the children (sending signals)");
1.57      www      7736:     &initnewstatus();
                   7737:     &logstatus();
                   7738:     &logthis('Going to check on the children');
1.134     albertel 7739:     my $docdir=$perlvar{'lonDocRoot'};
1.61      harris41 7740:     foreach (sort keys %children) {
1.221     albertel 7741: 	#sleep 1;
1.57      www      7742:         unless (kill 'USR1' => $_) {
                   7743: 	    &logthis ('Child '.$_.' is dead');
                   7744:             &logstatus($$.' is dead');
1.221     albertel 7745: 	    delete($children{$_});
1.57      www      7746:         } 
1.61      harris41 7747:     }
1.63      www      7748:     sleep 5;
1.212     foxr     7749:     $SIG{ALRM} = sub { Debug("timeout"); 
                   7750: 		       die "timeout";  };
1.113     albertel 7751:     $SIG{__DIE__} = 'DEFAULT';
1.165     albertel 7752:     &status("Checking on the children (waiting for reports)");
1.63      www      7753:     foreach (sort keys %children) {
                   7754:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113     albertel 7755:           eval {
                   7756:             alarm(300);
1.63      www      7757: 	    &logthis('Child '.$_.' did not respond');
1.67      albertel 7758: 	    kill 9 => $_;
1.131     albertel 7759: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   7760: 	    #$subj="LON: $currenthostid killed lond process $_";
                   7761: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
                   7762: 	    #$execdir=$perlvar{'lonDaemons'};
                   7763: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.221     albertel 7764: 	    delete($children{$_});
1.113     albertel 7765: 	    alarm(0);
                   7766: 	  }
1.63      www      7767:         }
                   7768:     }
1.113     albertel 7769:     $SIG{ALRM} = 'DEFAULT';
1.155     albertel 7770:     $SIG{__DIE__} = \&catchexception;
1.165     albertel 7771:     &status("Finished checking children");
1.221     albertel 7772:     &logthis('Finished Checking children');
1.57      www      7773: }
                   7774: 
1.1       albertel 7775: # --------------------------------------------------------------------- Logging
                   7776: 
                   7777: sub logthis {
                   7778:     my $message=shift;
                   7779:     my $execdir=$perlvar{'lonDaemons'};
                   7780:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
                   7781:     my $now=time;
                   7782:     my $local=localtime($now);
1.58      www      7783:     $lastlog=$local.': '.$message;
1.1       albertel 7784:     print $fh "$local ($$): $message\n";
                   7785: }
                   7786: 
1.77      foxr     7787: # ------------------------- Conditional log if $DEBUG true.
                   7788: sub Debug {
                   7789:     my $message = shift;
                   7790:     if($DEBUG) {
                   7791: 	&logthis($message);
                   7792:     }
                   7793: }
1.161     foxr     7794: 
                   7795: #
                   7796: #   Sub to do replies to client.. this gives a hook for some
                   7797: #   debug tracing too:
                   7798: #  Parameters:
                   7799: #     fd      - File open on client.
                   7800: #     reply   - Text to send to client.
                   7801: #     request - Original request from client.
                   7802: #
1.490     droeschl 7803: #NOTE $reply must be terminated by exactly *one* \n. If $reply is a reference
                   7804: #this is done automatically ($$reply must not contain any \n in this case). 
                   7805: #If $reply is a string the caller has to ensure this.
1.161     foxr     7806: sub Reply {
1.192     foxr     7807:     my ($fd, $reply, $request) = @_;
1.387     albertel 7808:     if (ref($reply)) {
                   7809: 	print $fd $$reply;
                   7810: 	print $fd "\n";
                   7811: 	if ($DEBUG) { Debug("Request was $request  Reply was $$reply"); }
                   7812:     } else {
                   7813: 	print $fd $reply;
                   7814: 	if ($DEBUG) { Debug("Request was $request  Reply was $reply"); }
                   7815:     }
1.212     foxr     7816:     $Transactions++;
                   7817: }
                   7818: 
                   7819: 
                   7820: #
                   7821: #    Sub to report a failure.
                   7822: #    This function:
                   7823: #     -   Increments the failure statistic counters.
                   7824: #     -   Invokes Reply to send the error message to the client.
                   7825: # Parameters:
                   7826: #    fd       - File descriptor open on the client
                   7827: #    reply    - Reply text to emit.
                   7828: #    request  - The original request message (used by Reply
                   7829: #               to debug if that's enabled.
                   7830: # Implicit outputs:
                   7831: #    $Failures- The number of failures is incremented.
                   7832: #    Reply (invoked here) sends a message to the 
                   7833: #    client:
                   7834: #
                   7835: sub Failure {
                   7836:     my $fd      = shift;
                   7837:     my $reply   = shift;
                   7838:     my $request = shift;
                   7839:    
                   7840:     $Failures++;
                   7841:     Reply($fd, $reply, $request);      # That's simple eh?
1.161     foxr     7842: }
1.57      www      7843: # ------------------------------------------------------------------ Log status
                   7844: 
                   7845: sub logstatus {
1.178     foxr     7846:     &status("Doing logging");
                   7847:     my $docdir=$perlvar{'lonDocRoot'};
                   7848:     {
                   7849: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
1.200     matthew  7850:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
1.178     foxr     7851:         $fh->close();
                   7852:     }
1.221     albertel 7853:     &status("Finished $$.txt");
                   7854:     {
                   7855: 	open(LOG,">>$docdir/lon-status/londstatus.txt");
                   7856: 	flock(LOG,LOCK_EX);
                   7857: 	print LOG $$."\t".$clientname."\t".$currenthostid."\t"
                   7858: 	    .$status."\t".$lastlog."\t $keymode\n";
1.275     albertel 7859: 	flock(LOG,LOCK_UN);
1.221     albertel 7860: 	close(LOG);
                   7861:     }
1.178     foxr     7862:     &status("Finished logging");
1.57      www      7863: }
                   7864: 
                   7865: sub initnewstatus {
                   7866:     my $docdir=$perlvar{'lonDocRoot'};
                   7867:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
1.460     foxr     7868:     my $now=time();
1.57      www      7869:     my $local=localtime($now);
                   7870:     print $fh "LOND status $local - parent $$\n\n";
1.64      www      7871:     opendir(DIR,"$docdir/lon-status/londchld");
1.134     albertel 7872:     while (my $filename=readdir(DIR)) {
1.64      www      7873:         unlink("$docdir/lon-status/londchld/$filename");
                   7874:     }
                   7875:     closedir(DIR);
1.57      www      7876: }
                   7877: 
                   7878: # -------------------------------------------------------------- Status setting
                   7879: 
                   7880: sub status {
                   7881:     my $what=shift;
                   7882:     my $now=time;
                   7883:     my $local=localtime($now);
1.178     foxr     7884:     $status=$local.': '.$what;
                   7885:     $0='lond: '.$what.' '.$local;
1.57      www      7886: }
1.11      www      7887: 
1.13      www      7888: # -------------------------------------------------------------- Talk to lonsql
                   7889: 
1.234     foxr     7890: sub sql_reply {
1.12      harris41 7891:     my ($cmd)=@_;
1.234     foxr     7892:     my $answer=&sub_sql_reply($cmd);
                   7893:     if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
1.12      harris41 7894:     return $answer;
                   7895: }
                   7896: 
1.234     foxr     7897: sub sub_sql_reply {
1.12      harris41 7898:     my ($cmd)=@_;
                   7899:     my $unixsock="mysqlsock";
                   7900:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
                   7901:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                   7902:                                       Type    => SOCK_STREAM,
                   7903:                                       Timeout => 10)
                   7904:        or return "con_lost";
1.319     www      7905:     print $sclient "$cmd:$currentdomainid\n";
1.12      harris41 7906:     my $answer=<$sclient>;
                   7907:     chomp($answer);
                   7908:     if (!$answer) { $answer="con_lost"; }
                   7909:     return $answer;
                   7910: }
                   7911: 
1.1       albertel 7912: # --------------------------------------- Is this the home server of an author?
1.11      www      7913: 
1.1       albertel 7914: sub ishome {
                   7915:     my $author=shift;
                   7916:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   7917:     my ($udom,$uname)=split(/\//,$author);
                   7918:     my $proname=propath($udom,$uname);
                   7919:     if (-e $proname) {
                   7920: 	return 'owner';
                   7921:     } else {
                   7922:         return 'not_owner';
                   7923:     }
                   7924: }
                   7925: 
                   7926: # ======================================================= Continue main program
                   7927: # ---------------------------------------------------- Fork once and dissociate
                   7928: 
1.134     albertel 7929: my $fpid=fork;
1.1       albertel 7930: exit if $fpid;
1.29      harris41 7931: die "Couldn't fork: $!" unless defined ($fpid);
1.1       albertel 7932: 
1.29      harris41 7933: POSIX::setsid() or die "Can't start new session: $!";
1.1       albertel 7934: 
                   7935: # ------------------------------------------------------- Write our PID on disk
                   7936: 
1.134     albertel 7937: my $execdir=$perlvar{'lonDaemons'};
1.1       albertel 7938: open (PIDSAVE,">$execdir/logs/lond.pid");
                   7939: print PIDSAVE "$$\n";
                   7940: close(PIDSAVE);
1.190     albertel 7941: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.57      www      7942: &status('Starting');
1.1       albertel 7943: 
1.106     foxr     7944: 
1.1       albertel 7945: 
                   7946: # ----------------------------------------------------- Install signal handlers
                   7947: 
1.57      www      7948: 
1.1       albertel 7949: $SIG{CHLD} = \&REAPER;
                   7950: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   7951: $SIG{HUP}  = \&HUPSMAN;
1.57      www      7952: $SIG{USR1} = \&checkchildren;
1.144     foxr     7953: $SIG{USR2} = \&UpdateHosts;
1.106     foxr     7954: 
1.148     foxr     7955: #  Read the host hashes:
1.368     albertel 7956: &Apache::lonnet::load_hosts_tab();
1.447     raeburn  7957: my %iphost = &Apache::lonnet::get_iphost(1);
1.106     foxr     7958: 
1.480     raeburn  7959: $dist=`$perlvar{'lonDaemons'}/distprobe`;
1.286     albertel 7960: 
1.471     raeburn  7961: my $arch = `uname -i`;
1.475     raeburn  7962: chomp($arch);
1.471     raeburn  7963: if ($arch eq 'unknown') {
                   7964:     $arch = `uname -m`;
1.475     raeburn  7965:     chomp($arch);
1.471     raeburn  7966: }
                   7967: 
1.555     raeburn  7968: unless (lonssl::Read_Connect_Config(\%secureconf,\%perlvar,\%crlchecked) eq 'ok') {
1.532     raeburn  7969:     &logthis('<font color="blue">No connectionrules table. Will fallback to loncapa.conf</font>');
                   7970: }
                   7971: 
1.106     foxr     7972: # --------------------------------------------------------------
                   7973: #   Accept connections.  When a connection comes in, it is validated
                   7974: #   and if good, a child process is created to process transactions
                   7975: #   along the connection.
                   7976: 
1.1       albertel 7977: while (1) {
1.165     albertel 7978:     &status('Starting accept');
1.106     foxr     7979:     $client = $server->accept() or next;
1.165     albertel 7980:     &status('Accepted '.$client.' off to spawn');
1.386     albertel 7981:     make_new_child($client);
1.165     albertel 7982:     &status('Finished spawning');
1.1       albertel 7983: }
                   7984: 
1.212     foxr     7985: sub make_new_child {
                   7986:     my $pid;
                   7987: #    my $cipher;     # Now global
                   7988:     my $sigset;
1.178     foxr     7989: 
1.212     foxr     7990:     $client = shift;
                   7991:     &status('Starting new child '.$client);
                   7992:     &logthis('<font color="green"> Attempting to start child ('.$client.
                   7993: 	     ")</font>");    
                   7994:     # block signal for fork
                   7995:     $sigset = POSIX::SigSet->new(SIGINT);
                   7996:     sigprocmask(SIG_BLOCK, $sigset)
                   7997:         or die "Can't block SIGINT for fork: $!\n";
1.178     foxr     7998: 
1.212     foxr     7999:     die "fork: $!" unless defined ($pid = fork);
1.178     foxr     8000: 
1.212     foxr     8001:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
                   8002: 	                               # connection liveness.
1.178     foxr     8003: 
1.212     foxr     8004:     #
                   8005:     #  Figure out who we're talking to so we can record the peer in 
                   8006:     #  the pid hash.
                   8007:     #
                   8008:     my $caller = getpeername($client);
                   8009:     my ($port,$iaddr);
                   8010:     if (defined($caller) && length($caller) > 0) {
                   8011: 	($port,$iaddr)=unpack_sockaddr_in($caller);
                   8012:     } else {
                   8013: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
                   8014:     }
                   8015:     if (defined($iaddr)) {
                   8016: 	$clientip  = inet_ntoa($iaddr);
                   8017: 	Debug("Connected with $clientip");
                   8018:     } else {
                   8019: 	&logthis("Unable to determine clientip");
                   8020: 	$clientip='Unavailable';
                   8021:     }
                   8022:     
                   8023:     if ($pid) {
                   8024:         # Parent records the child's birth and returns.
                   8025:         sigprocmask(SIG_UNBLOCK, $sigset)
                   8026:             or die "Can't unblock SIGINT for fork: $!\n";
                   8027:         $children{$pid} = $clientip;
                   8028:         &status('Started child '.$pid);
1.462     foxr     8029: 	close($client);
1.212     foxr     8030:         return;
                   8031:     } else {
                   8032:         # Child can *not* return from this subroutine.
                   8033:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
                   8034:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
                   8035:                                 #don't get intercepted
                   8036:         $SIG{USR1}= \&logstatus;
                   8037:         $SIG{ALRM}= \&timeout;
1.468     foxr     8038: 	#
                   8039: 	# Block sigpipe as it gets thrownon socket disconnect and we want to 
                   8040: 	# deal with that as a read faiure instead.
                   8041: 	#
                   8042: 	my $blockset = POSIX::SigSet->new(SIGPIPE);
                   8043: 	sigprocmask(SIG_BLOCK, $blockset);
                   8044: 
1.212     foxr     8045:         $lastlog='Forked ';
                   8046:         $status='Forked';
1.178     foxr     8047: 
1.212     foxr     8048:         # unblock signals
                   8049:         sigprocmask(SIG_UNBLOCK, $sigset)
                   8050:             or die "Can't unblock SIGINT for fork: $!\n";
1.178     foxr     8051: 
1.212     foxr     8052: #        my $tmpsnum=0;            # Now global
                   8053: #---------------------------------------------------- kerberos 5 initialization
                   8054:         &Authen::Krb5::init_context();
1.511     raeburn  8055: 
                   8056:         my $no_ets;
1.571     raeburn  8057:         if ($dist =~ /^(?:centos|rhes|scientific|oracle|rocky|alma)(\d+)/) {
1.511     raeburn  8058:             if ($1 >= 7) {
                   8059:                 $no_ets = 1;
                   8060:             }
                   8061:         } elsif ($dist =~ /^suse(\d+\.\d+)$/) {
                   8062:             if (($1 eq '9.3') || ($1 >= 12.2)) {
                   8063:                 $no_ets = 1; 
                   8064:             }
1.514     raeburn  8065:         } elsif ($dist =~ /^sles(\d+)$/) {
                   8066:             if ($1 > 11) {
                   8067:                 $no_ets = 1;
                   8068:             }
1.511     raeburn  8069:         } elsif ($dist =~ /^fedora(\d+)$/) {
                   8070:             if ($1 < 7) {
                   8071:                 $no_ets = 1;
                   8072:             }
                   8073:         }
                   8074:         unless ($no_ets) {
1.286     albertel 8075: 	    &Authen::Krb5::init_ets();
                   8076: 	}
1.209     albertel 8077: 
1.212     foxr     8078: 	&status('Accepted connection');
                   8079: # =============================================================================
                   8080:             # do something with the connection
                   8081: # -----------------------------------------------------------------------------
                   8082: 	# see if we know client and 'check' for spoof IP by ineffective challenge
1.178     foxr     8083: 
1.278     albertel 8084: 	my $outsideip=$clientip;
                   8085: 	if ($clientip eq '127.0.0.1') {
1.368     albertel 8086: 	    $outsideip=&Apache::lonnet::get_host_ip($perlvar{'lonHostID'});
1.278     albertel 8087: 	}
1.412     foxr     8088: 	&ReadManagerTable();
1.368     albertel 8089: 	my $clientrec=defined(&Apache::lonnet::get_hosts_from_ip($outsideip));
1.278     albertel 8090: 	my $ismanager=($managers{$outsideip}    ne undef);
1.432     raeburn  8091: 	$clientname  = "[unknown]";
1.212     foxr     8092: 	if($clientrec) {	# Establish client type.
                   8093: 	    $ConnectionType = "client";
1.368     albertel 8094: 	    $clientname = (&Apache::lonnet::get_hosts_from_ip($outsideip))[-1];
1.212     foxr     8095: 	    if($ismanager) {
                   8096: 		$ConnectionType = "both";
                   8097: 	    }
                   8098: 	} else {
                   8099: 	    $ConnectionType = "manager";
1.278     albertel 8100: 	    $clientname = $managers{$outsideip};
1.212     foxr     8101: 	}
1.556     raeburn  8102: 	my $clientok;
1.178     foxr     8103: 
1.212     foxr     8104: 	if ($clientrec || $ismanager) {
                   8105: 	    &status("Waiting for init from $clientip $clientname");
                   8106: 	    &logthis('<font color="yellow">INFO: Connection, '.
                   8107: 		     $clientip.
                   8108: 		  " ($clientname) connection type = $ConnectionType </font>" );
                   8109: 	    &status("Connecting $clientip  ($clientname))"); 
                   8110: 	    my $remotereq=<$client>;
                   8111: 	    chomp($remotereq);
                   8112: 	    Debug("Got init: $remotereq");
1.337     albertel 8113: 
1.212     foxr     8114: 	    if ($remotereq =~ /^init/) {
                   8115: 		&sethost("sethost:$perlvar{'lonHostID'}");
                   8116: 		#
                   8117: 		#  If the remote is attempting a local init... give that a try:
                   8118: 		#
1.432     raeburn  8119: 		(my $i, my $inittype, $clientversion) = split(/:/, $remotereq);
1.492     droeschl 8120:         # For LON-CAPA 2.9, the  client session will have sent its LON-CAPA
                   8121:         # version when initiating the connection. For LON-CAPA 2.8 and older,
                   8122:         # the version is retrieved from the global %loncaparevs in lonnet.pm.            
1.494     droeschl 8123:         # $clientversion contains path to keyfile if $inittype eq 'local'
                   8124:         # it's overridden below in this case
1.492     droeschl 8125:         $clientversion ||= $Apache::lonnet::loncaparevs{$clientname};
1.209     albertel 8126: 
1.212     foxr     8127: 		# If the connection type is ssl, but I didn't get my
                   8128: 		# certificate files yet, then I'll drop  back to 
                   8129: 		# insecure (if allowed).
1.532     raeburn  8130: 
                   8131:                 if ($inittype eq "ssl") {
                   8132:                     my $context;
                   8133:                     if ($clientsamedom) {
                   8134:                         $context = 'dom';
                   8135:                         if ($secureconf{'connfrom'}{'dom'} eq 'no') {
                   8136:                             $inittype = "";
                   8137:                         }
                   8138:                     } elsif ($clientsameinst) {
                   8139:                         $context = 'intdom';
                   8140:                         if ($secureconf{'connfrom'}{'intdom'} eq 'no') {
                   8141:                             $inittype = "";
                   8142:                         }
                   8143:                     } else {
                   8144:                         $context = 'other';
                   8145:                         if ($secureconf{'connfrom'}{'other'} eq 'no') {
                   8146:                             $inittype = "";
                   8147:                         }
                   8148:                     }
                   8149:                     if ($inittype eq '') {
                   8150:                         &logthis("<font color=\"blue\"> Domain config set "
                   8151:                                 ."to no ssl for $clientname (context: $context)"
                   8152:                                 ." -- trying insecure auth</font>");
                   8153:                     }
                   8154:                 }
                   8155: 
1.212     foxr     8156: 		if($inittype eq "ssl") {
                   8157: 		    my ($ca, $cert) = lonssl::CertificateFile;
                   8158: 		    my $kfile       = lonssl::KeyFile;
                   8159: 		    if((!$ca)   || 
                   8160: 		       (!$cert) || 
                   8161: 		       (!$kfile)) {
                   8162: 			$inittype = ""; # This forces insecure attempt.
                   8163: 			&logthis("<font color=\"blue\"> Certificates not "
                   8164: 				 ."installed -- trying insecure auth</font>");
1.224     foxr     8165: 		    } else {	# SSL certificates are in place so
1.212     foxr     8166: 		    }		# Leave the inittype alone.
                   8167: 		}
                   8168: 
                   8169: 		if($inittype eq "local") {
1.432     raeburn  8170:                     $clientversion = $perlvar{'lonVersion'};
1.212     foxr     8171: 		    my $key = LocalConnection($client, $remotereq);
                   8172: 		    if($key) {
                   8173: 			Debug("Got local key $key");
                   8174: 			$clientok     = 1;
                   8175: 			my $cipherkey = pack("H32", $key);
                   8176: 			$cipher       = new IDEA($cipherkey);
                   8177: 			print $client "ok:local\n";
1.442     www      8178: 			&logthis('<font color="green">'
1.212     foxr     8179: 				 . "Successful local authentication </font>");
                   8180: 			$keymode = "local"
1.178     foxr     8181: 		    } else {
1.212     foxr     8182: 			Debug("Failed to get local key");
                   8183: 			$clientok = 0;
                   8184: 			shutdown($client, 3);
                   8185: 			close $client;
1.178     foxr     8186: 		    }
1.212     foxr     8187: 		} elsif ($inittype eq "ssl") {
1.532     raeburn  8188: 		    my $key = SSLConnection($client,$clientname);
1.212     foxr     8189: 		    if ($key) {
                   8190: 			$clientok = 1;
                   8191: 			my $cipherkey = pack("H32", $key);
                   8192: 			$cipher       = new IDEA($cipherkey);
                   8193: 			&logthis('<font color="green">'
                   8194: 				 ."Successfull ssl authentication with $clientname </font>");
                   8195: 			$keymode = "ssl";
                   8196: 	     
1.178     foxr     8197: 		    } else {
1.212     foxr     8198: 			$clientok = 0;
                   8199: 			close $client;
1.178     foxr     8200: 		    }
1.212     foxr     8201: 	   
                   8202: 		} else {
                   8203: 		    my $ok = InsecureConnection($client);
                   8204: 		    if($ok) {
                   8205: 			$clientok = 1;
                   8206: 			&logthis('<font color="green">'
                   8207: 				 ."Successful insecure authentication with $clientname </font>");
                   8208: 			print $client "ok\n";
                   8209: 			$keymode = "insecure";
1.178     foxr     8210: 		    } else {
1.212     foxr     8211: 			&logthis('<font color="yellow">'
                   8212: 				  ."Attempted insecure connection disallowed </font>");
                   8213: 			close $client;
                   8214: 			$clientok = 0;
1.178     foxr     8215: 		    }
                   8216: 		}
1.212     foxr     8217: 	    } else {
                   8218: 		&logthis(
                   8219: 			 "<font color='blue'>WARNING: "
                   8220: 			 ."$clientip failed to initialize: >$remotereq< </font>");
                   8221: 		&status('No init '.$clientip);
                   8222: 	    }
                   8223: 	} else {
                   8224: 	    &logthis(
                   8225: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
                   8226: 	    &status('Hung up on '.$clientip);
                   8227: 	}
                   8228:  
                   8229: 	if ($clientok) {
                   8230: # ---------------- New known client connecting, could mean machine online again
1.368     albertel 8231: 	    if (&Apache::lonnet::get_host_ip($currenthostid) ne $clientip 
1.367     albertel 8232: 		&& $clientip ne '127.0.0.1') {
1.375     albertel 8233: 		&Apache::lonnet::reconlonc($clientname);
1.212     foxr     8234: 	    }
                   8235: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
                   8236: 	    &status('Will listen to '.$clientname);
                   8237: # ------------------------------------------------------------ Process requests
                   8238: 	    my $keep_going = 1;
                   8239: 	    my $user_input;
1.556     raeburn  8240: 
1.212     foxr     8241: 	    while(($user_input = get_request) && $keep_going) {
                   8242: 		alarm(120);
                   8243: 		Debug("Main: Got $user_input\n");
                   8244: 		$keep_going = &process_request($user_input);
1.178     foxr     8245: 		alarm(0);
1.569     raeburn  8246: 		&status('Listening to '.$clientname." ($keymode)");
1.161     foxr     8247: 	    }
1.212     foxr     8248: 
1.59      www      8249: # --------------------------------------------- client unknown or fishy, refuse
1.212     foxr     8250: 	}  else {
1.161     foxr     8251: 	    print $client "refused\n";
                   8252: 	    $client->close();
1.190     albertel 8253: 	    &logthis("<font color='blue'>WARNING: "
1.161     foxr     8254: 		     ."Rejected client $clientip, closing connection</font>");
                   8255: 	}
1.525     raeburn  8256:     }
1.161     foxr     8257:     
1.1       albertel 8258: # =============================================================================
1.161     foxr     8259:     
1.190     albertel 8260:     &logthis("<font color='red'>CRITICAL: "
1.161     foxr     8261: 	     ."Disconnect from $clientip ($clientname)</font>");    
1.569     raeburn  8262: 
                   8263: 
1.161     foxr     8264:     # this exit is VERY important, otherwise the child will become
                   8265:     # a producer of more and more children, forking yourself into
                   8266:     # process death.
                   8267:     exit;
1.106     foxr     8268:     
1.78      foxr     8269: }
1.532     raeburn  8270: 
                   8271: #
                   8272: #  Used to determine if a particular client is from the same domain
1.556     raeburn  8273: #  as the current server, or from the same internet domain, and
                   8274: #  also if the client can host sessions for the domain's users.
                   8275: #  A hash is populated with keys set to commands sent by the client
                   8276: #  which may not be executed for this domain.
1.532     raeburn  8277: #
                   8278: #  Optional input -- the client to check for domain and internet domain.
                   8279: #  If not specified, defaults to the package variable: $clientname
                   8280: #
                   8281: #  If called in array context will not set package variables, but will
                   8282: #  instead return an array of two values - (a) true if client is in the
1.556     raeburn  8283: #  same domain as the server, and (b) true if client is in the same 
                   8284: #  internet domain.
1.532     raeburn  8285: #
                   8286: #  If called in scalar context, sets package variables for current client:
                   8287: #
1.556     raeburn  8288: #  $clienthomedom    - LonCAPA domain of homeID for client.
                   8289: #  $clientsamedom    - LonCAPA domain same for this host and client.
                   8290: #  $clientintdom     - LonCAPA "internet domain" for client.
                   8291: #  $clientsameinst   - LonCAPA "internet domain" same for this host & client.
                   8292: #  $clientremoteok   - If current domain permits hosting on this client: 1
                   8293: #  %clientprohibited - Commands prohibited for domain's users for this client.
                   8294: #
                   8295: #  if the host and client have the same "internet domain", then the value
                   8296: #  of $clientremoteok is not used, and no commands are prohibited.
1.532     raeburn  8297: #
                   8298: #  returns 1 to indicate package variables have been set for current client.
                   8299: #
                   8300: 
                   8301: sub set_client_info {
                   8302:     my ($lonhost) = @_;
                   8303:     $lonhost ||= $clientname;
                   8304:     my $clienthost = &Apache::lonnet::hostname($lonhost);
                   8305:     my $clientserverhomeID = &Apache::lonnet::get_server_homeID($clienthost);
                   8306:     my $homedom = &Apache::lonnet::host_domain($clientserverhomeID);
                   8307:     my $samedom = 0;
1.557     raeburn  8308:     if ($perlvar{'lonDefDomain'} eq $homedom) {
1.532     raeburn  8309:         $samedom = 1;
                   8310:     }
                   8311:     my $intdom = &Apache::lonnet::internet_dom($clientserverhomeID);
                   8312:     my $sameinst = 0;
                   8313:     if ($intdom ne '') {
                   8314:         my $internet_names = &Apache::lonnet::get_internet_names($currenthostid);
                   8315:         if (ref($internet_names) eq 'ARRAY') {
                   8316:             if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   8317:                 $sameinst = 1;
                   8318:             }
                   8319:         }
                   8320:     }
                   8321:     if (wantarray) {
                   8322:         return ($samedom,$sameinst);
                   8323:     } else {
                   8324:         $clienthomedom = $homedom;
                   8325:         $clientsamedom = $samedom;
                   8326:         $clientintdom = $intdom;
                   8327:         $clientsameinst = $sameinst;
1.556     raeburn  8328:         if ($clientsameinst) {
                   8329:             undef($clientremoteok);
                   8330:             undef(%clientprohibited);
                   8331:         } else {
                   8332:             $clientremoteok = &get_remote_hostable($currentdomainid);
                   8333:             %clientprohibited = &get_prohibited($currentdomainid);
                   8334:         }
1.532     raeburn  8335:         return 1;
                   8336:     }
                   8337: }
                   8338: 
1.261     foxr     8339: #
                   8340: #   Determine if a user is an author for the indicated domain.
                   8341: #
                   8342: # Parameters:
                   8343: #    domain          - domain to check in .
                   8344: #    user            - Name of user to check.
                   8345: #
                   8346: # Return:
                   8347: #     1             - User is an author for domain.
                   8348: #     0             - User is not an author for domain.
                   8349: sub is_author {
                   8350:     my ($domain, $user) = @_;
                   8351: 
                   8352:     &Debug("is_author: $user @ $domain");
                   8353: 
                   8354:     my $hashref = &tie_user_hash($domain, $user, "roles",
                   8355: 				 &GDBM_READER());
                   8356: 
                   8357:     #  Author role should show up as a key /domain/_au
1.78      foxr     8358: 
1.321     albertel 8359:     my $value;
1.487     foxr     8360:     if ($hashref) {
1.78      foxr     8361: 
1.487     foxr     8362: 	my $key    = "/$domain/_au";
                   8363: 	if (defined($hashref)) {
                   8364: 	    $value = $hashref->{$key};
                   8365: 	    if(!untie_user_hash($hashref)) {
                   8366: 		return 'error: ' .  ($!+0)." untie (GDBM) Failed";
                   8367: 	    }
                   8368: 	}
                   8369: 	
                   8370: 	if(defined($value)) {
                   8371: 	    &Debug("$user @ $domain is an author");
                   8372: 	}
                   8373:     } else {
                   8374: 	return 'error: '.($!+0)." tie (GDBM) Failed";
1.261     foxr     8375:     }
                   8376: 
                   8377:     return defined($value);
                   8378: }
1.78      foxr     8379: #
                   8380: #   Checks to see if the input roleput request was to set
1.482     www      8381: # an author role.  If so, creates construction space 
1.78      foxr     8382: # Parameters:
                   8383: #    request   - The request sent to the rolesput subchunk.
                   8384: #                We're looking for  /domain/_au
                   8385: #    domain    - The domain in which the user is having roles doctored.
                   8386: #    user      - Name of the user for which the role is being put.
                   8387: #    authtype  - The authentication type associated with the user.
                   8388: #
1.289     albertel 8389: sub manage_permissions {
1.192     foxr     8390:     my ($request, $domain, $user, $authtype) = @_;
1.78      foxr     8391:     # See if the request is of the form /$domain/_au
1.289     albertel 8392:     if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
1.484     raeburn  8393:         my $path=$perlvar{'lonDocRoot'}."/priv/$domain";
1.482     www      8394:         unless (-e $path) {        
                   8395:            mkdir($path);
                   8396:         }
                   8397:         unless (-e $path.'/'.$user) {
                   8398:            mkdir($path.'/'.$user);
                   8399:         }
1.78      foxr     8400:     }
                   8401: }
1.222     foxr     8402: 
                   8403: 
                   8404: #
                   8405: #  Return the full path of a user password file, whether it exists or not.
                   8406: # Parameters:
                   8407: #   domain     - Domain in which the password file lives.
                   8408: #   user       - name of the user.
                   8409: # Returns:
                   8410: #    Full passwd path:
                   8411: #
                   8412: sub password_path {
                   8413:     my ($domain, $user) = @_;
1.264     albertel 8414:     return &propath($domain, $user).'/passwd';
1.222     foxr     8415: }
                   8416: 
                   8417: #   Password Filename
                   8418: #   Returns the path to a passwd file given domain and user... only if
                   8419: #  it exists.
                   8420: # Parameters:
                   8421: #   domain    - Domain in which to search.
                   8422: #   user      - username.
                   8423: # Returns:
                   8424: #   - If the password file exists returns its path.
                   8425: #   - If the password file does not exist, returns undefined.
                   8426: #
                   8427: sub password_filename {
                   8428:     my ($domain, $user) = @_;
                   8429: 
                   8430:     Debug ("PasswordFilename called: dom = $domain user = $user");
                   8431: 
                   8432:     my $path  = &password_path($domain, $user);
                   8433:     Debug("PasswordFilename got path: $path");
                   8434:     if(-e $path) {
                   8435: 	return $path;
                   8436:     } else {
                   8437: 	return undef;
                   8438:     }
                   8439: }
                   8440: 
                   8441: #
                   8442: #   Rewrite the contents of the user's passwd file.
                   8443: #  Parameters:
                   8444: #    domain    - domain of the user.
                   8445: #    name      - User's name.
                   8446: #    contents  - New contents of the file.
1.533     raeburn  8447: #    saveold   - (optional). If true save old file in a passwd.bak file.
1.222     foxr     8448: # Returns:
                   8449: #   0    - Failed.
                   8450: #   1    - Success.
                   8451: #
                   8452: sub rewrite_password_file {
1.533     raeburn  8453:     my ($domain, $user, $contents, $saveold) = @_;
1.222     foxr     8454: 
                   8455:     my $file = &password_filename($domain, $user);
                   8456:     if (defined $file) {
1.533     raeburn  8457:         if ($saveold) {
                   8458:             my $bakfile = $file.'.bak';
                   8459:             if (CopyFile($file,$bakfile)) {
                   8460:                 chmod(0400,$bakfile);
                   8461:                 &logthis("Old password saved in passwd.bak for internally authenticated user: $user:$domain");
                   8462:             } else {
                   8463:                 &logthis("Failed to save old password in passwd.bak for internally authenticated user: $user:$domain");
                   8464:             }
                   8465:         }
1.222     foxr     8466: 	my $pf = IO::File->new(">$file");
                   8467: 	if($pf) {
                   8468: 	    print $pf "$contents\n";
                   8469: 	    return 1;
                   8470: 	} else {
                   8471: 	    return 0;
                   8472: 	}
                   8473:     } else {
                   8474: 	return 0;
                   8475:     }
                   8476: 
                   8477: }
                   8478: 
1.78      foxr     8479: #
1.222     foxr     8480: #   get_auth_type - Determines the authorization type of a user in a domain.
1.78      foxr     8481: 
                   8482: #     Returns the authorization type or nouser if there is no such user.
                   8483: #
1.436     raeburn  8484: sub get_auth_type {
1.192     foxr     8485:     my ($domain, $user)  = @_;
1.78      foxr     8486: 
1.222     foxr     8487:     Debug("get_auth_type( $domain, $user ) \n");
1.78      foxr     8488:     my $proname    = &propath($domain, $user); 
                   8489:     my $passwdfile = "$proname/passwd";
                   8490:     if( -e $passwdfile ) {
                   8491: 	my $pf = IO::File->new($passwdfile);
                   8492: 	my $realpassword = <$pf>;
                   8493: 	chomp($realpassword);
1.79      foxr     8494: 	Debug("Password info = $realpassword\n");
1.78      foxr     8495: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79      foxr     8496: 	Debug("Authtype = $authtype, content = $contentpwd\n");
1.259     raeburn  8497: 	return "$authtype:$contentpwd";     
1.224     foxr     8498:     } else {
1.79      foxr     8499: 	Debug("Returning nouser");
1.78      foxr     8500: 	return "nouser";
                   8501:     }
1.1       albertel 8502: }
                   8503: 
1.220     foxr     8504: #
                   8505: #  Validate a user given their domain, name and password.  This utility
                   8506: #  function is used by both  AuthenticateHandler and ChangePasswordHandler
                   8507: #  to validate the login credentials of a user.
                   8508: # Parameters:
                   8509: #    $domain    - The domain being logged into (this is required due to
                   8510: #                 the capability for multihomed systems.
                   8511: #    $user      - The name of the user being validated.
                   8512: #    $password  - The user's propoposed password.
                   8513: #
                   8514: # Returns:
                   8515: #     1        - The domain,user,pasword triplet corresponds to a valid
                   8516: #                user.
                   8517: #     0        - The domain,user,password triplet is not a valid user.
                   8518: #
                   8519: sub validate_user {
1.396     raeburn  8520:     my ($domain, $user, $password, $checkdefauth) = @_;
1.220     foxr     8521: 
                   8522:     # Why negative ~pi you may well ask?  Well this function is about
                   8523:     # authentication, and therefore very important to get right.
                   8524:     # I've initialized the flag that determines whether or not I've 
                   8525:     # validated correctly to a value it's not supposed to get.
                   8526:     # At the end of this function. I'll ensure that it's not still that
                   8527:     # value so we don't just wind up returning some accidental value
                   8528:     # as a result of executing an unforseen code path that
1.249     foxr     8529:     # did not set $validated.  At the end of valid execution paths,
                   8530:     # validated shoule be 1 for success or 0 for failuer.
1.220     foxr     8531: 
                   8532:     my $validated = -3.14159;
                   8533: 
                   8534:     #  How we authenticate is determined by the type of authentication
                   8535:     #  the user has been assigned.  If the authentication type is
                   8536:     #  "nouser", the user does not exist so we will return 0.
                   8537: 
1.222     foxr     8538:     my $contents = &get_auth_type($domain, $user);
1.220     foxr     8539:     my ($howpwd, $contentpwd) = split(/:/, $contents);
                   8540: 
                   8541:     my $null = pack("C",0);	# Used by kerberos auth types.
                   8542: 
1.395     raeburn  8543:     if ($howpwd eq 'nouser') {
1.396     raeburn  8544:         if ($checkdefauth) {
                   8545:             my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   8546:             if ($domdefaults{'auth_def'} eq 'localauth') {
                   8547:                 $howpwd = $domdefaults{'auth_def'};
                   8548:                 $contentpwd = $domdefaults{'auth_arg_def'};
                   8549:             } elsif ((($domdefaults{'auth_def'} eq 'krb4') || 
                   8550:                       ($domdefaults{'auth_def'} eq 'krb5')) &&
                   8551:                      ($domdefaults{'auth_arg_def'} ne '')) {
1.574     raeburn  8552:                 #
                   8553:                 # Don't attempt authentication for username and password supplied
                   8554:                 # for user without an account if uername contains @ to avoid
1.575     raeburn  8555:                 # call to &Authen::Krb5::parse_name() which will result in con_lost
1.574     raeburn  8556:                 #
                   8557:                 unless ($user =~ /\@/) {
                   8558:                     $howpwd = $domdefaults{'auth_def'};
                   8559:                     $contentpwd = $domdefaults{'auth_arg_def'};
                   8560:                 }
1.396     raeburn  8561:             }
1.395     raeburn  8562:         }
1.533     raeburn  8563:     }
1.220     foxr     8564:     if ($howpwd ne 'nouser') {
                   8565: 	if($howpwd eq "internal") { # Encrypted is in local password file.
1.518     raeburn  8566:             if (length($contentpwd) == 13) {
                   8567:                 $validated = (crypt($password,$contentpwd) eq $contentpwd);
                   8568:                 if ($validated) {
1.533     raeburn  8569:                     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   8570:                     if ($domdefaults{'intauth_switch'}) {
                   8571:                         my $ncpass = &hash_passwd($domain,$password);
                   8572:                         my $saveold;
                   8573:                         if ($domdefaults{'intauth_switch'} == 2) {
                   8574:                             $saveold = 1;
                   8575:                         }
                   8576:                         if (&rewrite_password_file($domain,$user,"$howpwd:$ncpass",$saveold)) {
                   8577:                             &update_passwd_history($user,$domain,$howpwd,'conversion');
                   8578:                             &logthis("Validated password hashed with bcrypt for $user:$domain");
                   8579:                         }
1.518     raeburn  8580:                     }
                   8581:                 }
                   8582:             } else {
1.533     raeburn  8583:                 $validated = &check_internal_passwd($password,$contentpwd,$domain,$user);
1.518     raeburn  8584:             }
1.220     foxr     8585: 	}
                   8586: 	elsif ($howpwd eq "unix") { # User is a normal unix user.
                   8587: 	    $contentpwd = (getpwnam($user))[1];
                   8588: 	    if($contentpwd) {
                   8589: 		if($contentpwd eq 'x') { # Shadow password file...
                   8590: 		    my $pwauth_path = "/usr/local/sbin/pwauth";
                   8591: 		    open PWAUTH,  "|$pwauth_path" or
                   8592: 			die "Cannot invoke authentication";
                   8593: 		    print PWAUTH "$user\n$password\n";
                   8594: 		    close PWAUTH;
                   8595: 		    $validated = ! $?;
                   8596: 
                   8597: 		} else { 	         # Passwords in /etc/passwd. 
                   8598: 		    $validated = (crypt($password,
                   8599: 					$contentpwd) eq $contentpwd);
                   8600: 		}
                   8601: 	    } else {
                   8602: 		$validated = 0;
                   8603: 	    }
1.439     raeburn  8604: 	} elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
                   8605:             my $checkwithkrb5 = 0;
                   8606:             if ($dist =~/^fedora(\d+)$/) {
                   8607:                 if ($1 > 11) {
                   8608:                     $checkwithkrb5 = 1;
                   8609:                 }
                   8610:             } elsif ($dist =~ /^suse([\d.]+)$/) {
                   8611:                 if ($1 > 11.1) {
                   8612:                     $checkwithkrb5 = 1; 
                   8613:                 }
                   8614:             }
                   8615:             if ($checkwithkrb5) {
                   8616:                 $validated = &krb5_authen($password,$null,$user,$contentpwd);
                   8617:             } else {
                   8618:                 $validated = &krb4_authen($password,$null,$user,$contentpwd);
                   8619:             }
1.224     foxr     8620: 	} elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
1.439     raeburn  8621:             $validated = &krb5_authen($password,$null,$user,$contentpwd);
1.224     foxr     8622: 	} elsif ($howpwd eq "localauth") { 
1.220     foxr     8623: 	    #  Authenticate via installation specific authentcation method:
                   8624: 	    $validated = &localauth::localauth($user, 
                   8625: 					       $password, 
1.353     albertel 8626: 					       $contentpwd,
                   8627: 					       $domain);
1.358     albertel 8628: 	    if ($validated < 0) {
1.357     albertel 8629: 		&logthis("localauth for $contentpwd $user:$domain returned a $validated");
                   8630: 		$validated = 0;
                   8631: 	    }
1.224     foxr     8632: 	} else {			# Unrecognized auth is also bad.
1.220     foxr     8633: 	    $validated = 0;
                   8634: 	}
                   8635:     } else {
                   8636: 	$validated = 0;
                   8637:     }
                   8638:     #
                   8639:     #  $validated has the correct stat of the authentication:
                   8640:     #
                   8641: 
                   8642:     unless ($validated != -3.14159) {
1.249     foxr     8643: 	#  I >really really< want to know if this happens.
                   8644: 	#  since it indicates that user authentication is badly
                   8645: 	#  broken in some code path.
                   8646:         #
                   8647: 	die "ValidateUser - failed to set the value of validated $domain, $user $password";
1.220     foxr     8648:     }
                   8649:     return $validated;
                   8650: }
                   8651: 
1.518     raeburn  8652: sub check_internal_passwd {
1.533     raeburn  8653:     my ($plainpass,$stored,$domain,$user) = @_;
1.518     raeburn  8654:     my (undef,$method,@rest) = split(/!/,$stored);
1.533     raeburn  8655:     if ($method eq 'bcrypt') {
1.518     raeburn  8656:         my $result = &hash_passwd($domain,$plainpass,@rest);
                   8657:         if ($result ne $stored) {
                   8658:             return 0;
                   8659:         }
1.533     raeburn  8660:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   8661:         if ($domdefaults{'intauth_check'}) {
                   8662:             # Upgrade to a larger number of rounds if necessary
                   8663:             my $defaultcost = $domdefaults{'intauth_cost'};
                   8664:             if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
                   8665:                 $defaultcost = 10;
                   8666:             }
                   8667:             if (int($rest[0])<int($defaultcost)) {
                   8668:                 if ($domdefaults{'intauth_check'} == 1) { 
                   8669:                     my $ncpass = &hash_passwd($domain,$plainpass);
                   8670:                     if (&rewrite_password_file($domain,$user,"internal:$ncpass")) {
                   8671:                         &update_passwd_history($user,$domain,'internal','update cost');
                   8672:                         &logthis("Validated password hashed with bcrypt for $user:$domain");
                   8673:                     }
                   8674:                     return 1;
                   8675:                 } elsif ($domdefaults{'intauth_check'} == 2) {
                   8676:                     return 0;
                   8677:                 }
                   8678:             }
                   8679:         } else {
                   8680:             return 1;
1.518     raeburn  8681:         }
                   8682:     }
                   8683:     return 0;
                   8684: }
                   8685: 
                   8686: sub get_last_authchg {
                   8687:     my ($domain,$user) = @_;
                   8688:     my $lastmod;
                   8689:     my $logname = &propath($domain,$user).'/passwd.log';
                   8690:     if (-e "$logname") {
                   8691:         $lastmod = (stat("$logname"))[9];
                   8692:     }
                   8693:     return $lastmod;
                   8694: }
                   8695: 
1.439     raeburn  8696: sub krb4_authen {
                   8697:     my ($password,$null,$user,$contentpwd) = @_;
                   8698:     my $validated = 0;
                   8699:     if (!($password =~ /$null/) ) {  # Null password not allowed.
                   8700:         eval {
                   8701:             require Authen::Krb4;
                   8702:         };
                   8703:         if (!$@) {
                   8704:             my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
                   8705:                                                        "",
                   8706:                                                        $contentpwd,,
                   8707:                                                        'krbtgt',
                   8708:                                                        $contentpwd,
                   8709:                                                        1,
                   8710:                                                        $password);
                   8711:             if(!$k4error) {
                   8712:                 $validated = 1;
                   8713:             } else {
                   8714:                 $validated = 0;
                   8715:                 &logthis('krb4: '.$user.', '.$contentpwd.', '.
                   8716:                           &Authen::Krb4::get_err_txt($Authen::Krb4::error));
                   8717:             }
                   8718:         } else {
                   8719:             $validated = krb5_authen($password,$null,$user,$contentpwd);
                   8720:         }
                   8721:     }
                   8722:     return $validated;
                   8723: }
                   8724: 
                   8725: sub krb5_authen {
                   8726:     my ($password,$null,$user,$contentpwd) = @_;
                   8727:     my $validated = 0;
                   8728:     if(!($password =~ /$null/)) { # Null password not allowed.
                   8729:         my $krbclient = &Authen::Krb5::parse_name($user.'@'
                   8730:                                                   .$contentpwd);
                   8731:         my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
                   8732:         my $krbserver  = &Authen::Krb5::parse_name($krbservice);
                   8733:         my $credentials= &Authen::Krb5::cc_default();
                   8734:         $credentials->initialize(&Authen::Krb5::parse_name($user.'@'
                   8735:                                                             .$contentpwd));
                   8736:         my $krbreturn;
                   8737:         if (exists(&Authen::Krb5::get_init_creds_password)) {
                   8738:             $krbreturn =
                   8739:                 &Authen::Krb5::get_init_creds_password($krbclient,$password,
                   8740:                                                           $krbservice);
                   8741:             $validated = (ref($krbreturn) eq 'Authen::Krb5::Creds');
                   8742:         } else {
                   8743:             $krbreturn  =
                   8744:                 &Authen::Krb5::get_in_tkt_with_password($krbclient,$krbserver,
                   8745:                                                          $password,$credentials);
                   8746:             $validated = ($krbreturn == 1);
                   8747:         }
                   8748:         if (!$validated) {
                   8749:             &logthis('krb5: '.$user.', '.$contentpwd.', '.
                   8750:                      &Authen::Krb5::error());
                   8751:         }
                   8752:     }
                   8753:     return $validated;
                   8754: }
1.220     foxr     8755: 
1.84      albertel 8756: sub addline {
                   8757:     my ($fname,$hostid,$ip,$newline)=@_;
                   8758:     my $contents;
                   8759:     my $found=0;
1.355     albertel 8760:     my $expr='^'.quotemeta($hostid).':'.quotemeta($ip).':';
1.134     albertel 8761:     my $sh;
1.84      albertel 8762:     if ($sh=IO::File->new("$fname.subscription")) {
                   8763: 	while (my $subline=<$sh>) {
                   8764: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
                   8765: 	}
                   8766: 	$sh->close();
                   8767:     }
                   8768:     $sh=IO::File->new(">$fname.subscription");
                   8769:     if ($contents) { print $sh $contents; }
                   8770:     if ($newline) { print $sh $newline; }
                   8771:     $sh->close();
                   8772:     return $found;
1.86      www      8773: }
                   8774: 
1.234     foxr     8775: sub get_chat {
1.324     raeburn  8776:     my ($cdom,$cname,$udom,$uname,$group)=@_;
1.310     albertel 8777: 
1.87      www      8778:     my @entries=();
1.324     raeburn  8779:     my $namespace = 'nohist_chatroom';
                   8780:     my $namespace_inroom = 'nohist_inchatroom';
1.335     albertel 8781:     if ($group ne '') {
1.324     raeburn  8782:         $namespace .= '_'.$group;
                   8783:         $namespace_inroom .= '_'.$group;
                   8784:     }
                   8785:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 8786: 				 &GDBM_READER());
                   8787:     if ($hashref) {
                   8788: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.311     albertel 8789: 	&untie_user_hash($hashref);
1.123     www      8790:     }
1.124     www      8791:     my @participants=();
1.134     albertel 8792:     my $cutoff=time-60;
1.324     raeburn  8793:     $hashref = &tie_user_hash($cdom, $cname, $namespace_inroom,
1.310     albertel 8794: 			      &GDBM_WRCREAT());
                   8795:     if ($hashref) {
                   8796:         $hashref->{$uname.':'.$udom}=time;
                   8797:         foreach my $user (sort(keys(%$hashref))) {
                   8798: 	    if ($hashref->{$user}>$cutoff) {
                   8799: 		push(@participants, 'active_participant:'.$user);
1.123     www      8800:             }
                   8801:         }
1.311     albertel 8802:         &untie_user_hash($hashref);
1.86      www      8803:     }
1.124     www      8804:     return (@participants,@entries);
1.86      www      8805: }
                   8806: 
1.234     foxr     8807: sub chat_add {
1.324     raeburn  8808:     my ($cdom,$cname,$newchat,$group)=@_;
1.88      albertel 8809:     my @entries=();
1.142     www      8810:     my $time=time;
1.324     raeburn  8811:     my $namespace = 'nohist_chatroom';
                   8812:     my $logfile = 'chatroom.log';
1.335     albertel 8813:     if ($group ne '') {
1.324     raeburn  8814:         $namespace .= '_'.$group;
                   8815:         $logfile = 'chatroom_'.$group.'.log';
                   8816:     }
                   8817:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 8818: 				 &GDBM_WRCREAT());
                   8819:     if ($hashref) {
                   8820: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.88      albertel 8821: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
                   8822: 	my ($thentime,$idnum)=split(/\_/,$lastid);
                   8823: 	my $newid=$time.'_000000';
                   8824: 	if ($thentime==$time) {
                   8825: 	    $idnum=~s/^0+//;
                   8826: 	    $idnum++;
                   8827: 	    $idnum=substr('000000'.$idnum,-6,6);
                   8828: 	    $newid=$time.'_'.$idnum;
                   8829: 	}
1.310     albertel 8830: 	$hashref->{$newid}=$newchat;
1.88      albertel 8831: 	my $expired=$time-3600;
1.310     albertel 8832: 	foreach my $comment (keys(%$hashref)) {
                   8833: 	    my ($thistime) = ($comment=~/(\d+)\_/);
1.88      albertel 8834: 	    if ($thistime<$expired) {
1.310     albertel 8835: 		delete $hashref->{$comment};
1.88      albertel 8836: 	    }
                   8837: 	}
1.310     albertel 8838: 	{
                   8839: 	    my $proname=&propath($cdom,$cname);
1.324     raeburn  8840: 	    if (open(CHATLOG,">>$proname/$logfile")) { 
1.310     albertel 8841: 		print CHATLOG ("$time:".&unescape($newchat)."\n");
                   8842: 	    }
                   8843: 	    close(CHATLOG);
1.142     www      8844: 	}
1.311     albertel 8845: 	&untie_user_hash($hashref);
1.86      www      8846:     }
1.84      albertel 8847: }
                   8848: 
                   8849: sub unsub {
                   8850:     my ($fname,$clientip)=@_;
                   8851:     my $result;
1.188     foxr     8852:     my $unsubs = 0;		# Number of successful unsubscribes:
                   8853: 
                   8854: 
                   8855:     # An old way subscriptions were handled was to have a 
                   8856:     # subscription marker file:
                   8857: 
                   8858:     Debug("Attempting unlink of $fname.$clientname");
1.161     foxr     8859:     if (unlink("$fname.$clientname")) {
1.188     foxr     8860: 	$unsubs++;		# Successful unsub via marker file.
                   8861:     } 
                   8862: 
                   8863:     # The more modern way to do it is to have a subscription list
                   8864:     # file:
                   8865: 
1.84      albertel 8866:     if (-e "$fname.subscription") {
1.161     foxr     8867: 	my $found=&addline($fname,$clientname,$clientip,'');
1.188     foxr     8868: 	if ($found) { 
                   8869: 	    $unsubs++;
                   8870: 	}
                   8871:     } 
                   8872: 
                   8873:     #  If either or both of these mechanisms succeeded in unsubscribing a 
                   8874:     #  resource we can return ok:
                   8875: 
                   8876:     if($unsubs) {
                   8877: 	$result = "ok\n";
1.84      albertel 8878:     } else {
1.188     foxr     8879: 	$result = "not_subscribed\n";
1.84      albertel 8880:     }
1.188     foxr     8881: 
1.84      albertel 8882:     return $result;
                   8883: }
                   8884: 
1.101     www      8885: sub currentversion {
                   8886:     my $fname=shift;
                   8887:     my $version=-1;
                   8888:     my $ulsdir='';
                   8889:     if ($fname=~/^(.+)\/[^\/]+$/) {
                   8890:        $ulsdir=$1;
                   8891:     }
1.114     albertel 8892:     my ($fnamere1,$fnamere2);
                   8893:     # remove version if already specified
1.101     www      8894:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114     albertel 8895:     # get the bits that go before and after the version number
                   8896:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
                   8897: 	$fnamere1=$1;
                   8898: 	$fnamere2='.'.$2;
                   8899:     }
1.101     www      8900:     if (-e $fname) { $version=1; }
                   8901:     if (-e $ulsdir) {
1.134     albertel 8902: 	if(-d $ulsdir) {
                   8903: 	    if (opendir(LSDIR,$ulsdir)) {
1.580     raeburn  8904:                 if (-e $fname) {
                   8905:                     $version=0;
                   8906:                 }
1.134     albertel 8907: 		my $ulsfn;
                   8908: 		while ($ulsfn=readdir(LSDIR)) {
1.101     www      8909: # see if this is a regular file (ignore links produced earlier)
1.134     albertel 8910: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
                   8911: 		    unless (-l $thisfile) {
1.160     www      8912: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134     albertel 8913: 			    if ($1>$version) { $version=$1; }
                   8914: 			}
                   8915: 		    }
                   8916: 		}
                   8917: 		closedir(LSDIR);
                   8918: 		$version++;
                   8919: 	    }
                   8920: 	}
                   8921:     }
                   8922:     return $version;
1.101     www      8923: }
                   8924: 
                   8925: sub thisversion {
                   8926:     my $fname=shift;
                   8927:     my $version=-1;
                   8928:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
                   8929: 	$version=$1;
                   8930:     }
                   8931:     return $version;
                   8932: }
                   8933: 
1.84      albertel 8934: sub subscribe {
                   8935:     my ($userinput,$clientip)=@_;
                   8936:     my $result;
1.293     albertel 8937:     my ($cmd,$fname)=split(/:/,$userinput,2);
1.84      albertel 8938:     my $ownership=&ishome($fname);
                   8939:     if ($ownership eq 'owner') {
1.101     www      8940: # explitly asking for the current version?
                   8941:         unless (-e $fname) {
                   8942:             my $currentversion=&currentversion($fname);
                   8943: 	    if (&thisversion($fname)==$currentversion) {
                   8944:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
                   8945: 		    my $root=$1;
                   8946:                     my $extension=$2;
                   8947:                     symlink($root.'.'.$extension,
                   8948:                             $root.'.'.$currentversion.'.'.$extension);
1.102     www      8949:                     unless ($extension=~/\.meta$/) {
                   8950:                        symlink($root.'.'.$extension.'.meta',
                   8951:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
                   8952: 		    }
1.101     www      8953:                 }
                   8954:             }
                   8955:         }
1.84      albertel 8956: 	if (-e $fname) {
                   8957: 	    if (-d $fname) {
                   8958: 		$result="directory\n";
                   8959: 	    } else {
1.161     foxr     8960: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134     albertel 8961: 		my $now=time;
1.161     foxr     8962: 		my $found=&addline($fname,$clientname,$clientip,
                   8963: 				   "$clientname:$clientip:$now\n");
1.84      albertel 8964: 		if ($found) { $result="$fname\n"; }
                   8965: 		# if they were subscribed to only meta data, delete that
                   8966:                 # subscription, when you subscribe to a file you also get
                   8967:                 # the metadata
                   8968: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
                   8969: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
1.476     raeburn  8970:                 my $protocol = $Apache::lonnet::protocol{$perlvar{'lonHostID'}};
                   8971:                 $protocol = 'http' if ($protocol ne 'https');
                   8972: 		$fname=$protocol.'://'.&Apache::lonnet::hostname($perlvar{'lonHostID'})."/".$fname;
1.84      albertel 8973: 		$result="$fname\n";
                   8974: 	    }
                   8975: 	} else {
                   8976: 	    $result="not_found\n";
                   8977: 	}
                   8978:     } else {
                   8979: 	$result="rejected\n";
                   8980:     }
                   8981:     return $result;
                   8982: }
1.287     foxr     8983: #  Change the passwd of a unix user.  The caller must have
                   8984: #  first verified that the user is a loncapa user.
                   8985: #
                   8986: # Parameters:
                   8987: #    user      - Unix user name to change.
                   8988: #    pass      - New password for the user.
                   8989: # Returns:
                   8990: #    ok    - if success
                   8991: #    other - Some meaningfule error message string.
                   8992: # NOTE:
                   8993: #    invokes a setuid script to change the passwd.
                   8994: sub change_unix_password {
                   8995:     my ($user, $pass) = @_;
                   8996: 
                   8997:     &Debug("change_unix_password");
                   8998:     my $execdir=$perlvar{'lonDaemons'};
                   8999:     &Debug("Opening lcpasswd pipeline");
                   9000:     my $pf = IO::File->new("|$execdir/lcpasswd > "
                   9001: 			   ."$perlvar{'lonDaemons'}"
                   9002: 			   ."/logs/lcpasswd.log");
                   9003:     print $pf "$user\n$pass\n$pass\n";
                   9004:     close $pf;
                   9005:     my $err = $?;
                   9006:     return ($err < @passwderrors) ? $passwderrors[$err] : 
                   9007: 	"pwchange_falure - unknown error";
                   9008: 
                   9009:     
                   9010: }
                   9011: 
1.91      albertel 9012: 
                   9013: sub make_passwd_file {
1.518     raeburn  9014:     my ($uname,$udom,$umode,$npass,$passfilename,$action)=@_;
1.390     raeburn  9015:     my $result="ok";
1.91      albertel 9016:     if ($umode eq 'krb4' or $umode eq 'krb5') {
                   9017: 	{
                   9018: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     9019: 	    if ($pf) {
                   9020: 		print $pf "$umode:$npass\n";
1.518     raeburn  9021:                 &update_passwd_history($uname,$udom,$umode,$action);
1.261     foxr     9022: 	    } else {
                   9023: 		$result = "pass_file_failed_error";
                   9024: 	    }
1.91      albertel 9025: 	}
                   9026:     } elsif ($umode eq 'internal') {
1.518     raeburn  9027:         my $ncpass = &hash_passwd($udom,$npass);
1.91      albertel 9028: 	{
                   9029: 	    &Debug("Creating internal auth");
                   9030: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     9031: 	    if($pf) {
1.518     raeburn  9032: 		print $pf "internal:$ncpass\n";
                   9033:                 &update_passwd_history($uname,$udom,$umode,$action); 
1.261     foxr     9034: 	    } else {
                   9035: 		$result = "pass_file_failed_error";
                   9036: 	    }
1.91      albertel 9037: 	}
                   9038:     } elsif ($umode eq 'localauth') {
                   9039: 	{
                   9040: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     9041: 	    if($pf) {
                   9042: 		print $pf "localauth:$npass\n";
1.524     raeburn  9043:                 &update_passwd_history($uname,$udom,$umode,$action);
1.261     foxr     9044: 	    } else {
                   9045: 		$result = "pass_file_failed_error";
                   9046: 	    }
1.91      albertel 9047: 	}
                   9048:     } elsif ($umode eq 'unix') {
1.502     raeburn  9049: 	&logthis(">>>Attempt to create unix account blocked -- unix auth not available for new users.");
                   9050: 	$result="no_new_unix_accounts";
1.91      albertel 9051:     } elsif ($umode eq 'none') {
                   9052: 	{
1.223     foxr     9053: 	    my $pf = IO::File->new("> $passfilename");
1.261     foxr     9054: 	    if($pf) {
                   9055: 		print $pf "none:\n";
                   9056: 	    } else {
                   9057: 		$result = "pass_file_failed_error";
                   9058: 	    }
1.91      albertel 9059: 	}
1.543     raeburn  9060:     } elsif ($umode eq 'lti') {
                   9061:         my $pf = IO::File->new(">$passfilename");
                   9062:         if($pf) {
                   9063:             print $pf "lti:\n";
                   9064:             &update_passwd_history($uname,$udom,$umode,$action);
                   9065:         } else {
                   9066:             $result = "pass_file_failed_error";
                   9067:         }
1.91      albertel 9068:     } else {
1.390     raeburn  9069: 	$result="auth_mode_error";
1.91      albertel 9070:     }
                   9071:     return $result;
1.121     albertel 9072: }
                   9073: 
1.265     albertel 9074: sub convert_photo {
                   9075:     my ($start,$dest)=@_;
                   9076:     system("convert $start $dest");
                   9077: }
                   9078: 
1.121     albertel 9079: sub sethost {
                   9080:     my ($remotereq) = @_;
                   9081:     my (undef,$hostid)=split(/:/,$remotereq);
1.322     albertel 9082:     # ignore sethost if we are already correct
                   9083:     if ($hostid eq $currenthostid) {
                   9084: 	return 'ok';
                   9085:     }
                   9086: 
1.121     albertel 9087:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
1.368     albertel 9088:     if (&Apache::lonnet::get_host_ip($perlvar{'lonHostID'}) 
                   9089: 	eq &Apache::lonnet::get_host_ip($hostid)) {
1.200     matthew  9090: 	$currenthostid  =$hostid;
1.369     albertel 9091: 	$currentdomainid=&Apache::lonnet::host_domain($hostid);
1.556     raeburn  9092:         &set_client_info();
1.443     www      9093: #	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
1.121     albertel 9094:     } else {
                   9095: 	&logthis("Requested host id $hostid not an alias of ".
                   9096: 		 $perlvar{'lonHostID'}." refusing connection");
                   9097: 	return 'unable_to_set';
                   9098:     }
                   9099:     return 'ok';
                   9100: }
                   9101: 
                   9102: sub version {
                   9103:     my ($userinput)=@_;
                   9104:     $remoteVERSION=(split(/:/,$userinput))[1];
                   9105:     return "version:$VERSION";
1.127     albertel 9106: }
1.178     foxr     9107: 
1.447     raeburn  9108: sub get_usersession_config {
                   9109:     my ($dom,$name) = @_;
                   9110:     my ($usersessionconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   9111:     if (defined($cached)) {
                   9112:         return $usersessionconf;
                   9113:     } else {
                   9114:         my %domconfig = &Apache::lonnet::get_dom('configuration',['usersessions'],$dom);
1.525     raeburn  9115:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'usersessions'},3600);
                   9116:         return $domconfig{'usersessions'};
1.447     raeburn  9117:     }
                   9118:     return;
                   9119: }
1.200     matthew  9120: 
1.534     raeburn  9121: sub get_usersearch_config {
                   9122:     my ($dom,$name) = @_;
                   9123:     my ($usersearchconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   9124:     if (defined($cached)) {
                   9125:         return $usersearchconf;
                   9126:     } else {
                   9127:         my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$dom);
                   9128:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'directorysrch'},600);
                   9129:         return $domconfig{'directorysrch'};
                   9130:     }
                   9131:     return;
                   9132: }
                   9133: 
1.525     raeburn  9134: sub get_prohibited {
                   9135:     my ($dom) = @_;
                   9136:     my $name = 'trust';
                   9137:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   9138:     unless (defined($cached)) {
                   9139:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$dom);
                   9140:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'trust'},3600);
                   9141:         $trustconfig = $domconfig{'trust'};
                   9142:     }
                   9143:     my %prohibited;
                   9144:     if (ref($trustconfig)) {
                   9145:         foreach my $prefix (keys(%{$trustconfig})) {
                   9146:             if (ref($trustconfig->{$prefix}) eq 'HASH') {
                   9147:                 my $reject;
                   9148:                 if (ref($trustconfig->{$prefix}->{'exc'}) eq 'ARRAY') {
                   9149:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'exc'}})) {
                   9150:                         $reject = 1;
                   9151:                     }
                   9152:                 }
                   9153:                 if (ref($trustconfig->{$prefix}->{'inc'}) eq 'ARRAY') {
                   9154:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'inc'}})) {
                   9155:                         $reject = 0;
                   9156:                     } else {
                   9157:                         $reject = 1;
                   9158:                     }
                   9159:                 }
                   9160:                 if ($reject) {
                   9161:                     $prohibited{$prefix} = 1;
                   9162:                 }
                   9163:             }
                   9164:         }
                   9165:     }
                   9166:     return %prohibited;
                   9167: }
1.450     raeburn  9168: 
1.556     raeburn  9169: sub get_remote_hostable {
                   9170:     my ($dom) = @_;
                   9171:     my $result;
                   9172:     if ($clientintdom) {
                   9173:         $result = 1;
                   9174:         my $remsessconf = &get_usersession_config($dom,'remotesession');
                   9175:         if (ref($remsessconf) eq 'HASH') {
                   9176:             if (ref($remsessconf->{'remote'}) eq 'HASH') {
                   9177:                 if (ref($remsessconf->{'remote'}->{'excludedomain'}) eq 'ARRAY') {
                   9178:                     if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'excludedomain'}})) {
                   9179:                         $result = 0;
                   9180:                     }
                   9181:                 }
                   9182:                 if (ref($remsessconf->{'remote'}->{'includedomain'}) eq 'ARRAY') {
                   9183:                     if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'includedomain'}})) {
                   9184:                         $result = 1;
                   9185:                     } else {
                   9186:                         $result = 0;
                   9187:                     }
                   9188:                 }
                   9189:             }
                   9190:         }
                   9191:     }
                   9192:     return $result;
                   9193: }
                   9194: 
1.471     raeburn  9195: sub distro_and_arch {
                   9196:     return $dist.':'.$arch;
                   9197: }
                   9198: 
1.61      harris41 9199: # ----------------------------------- POD (plain old documentation, CPAN style)
                   9200: 
                   9201: =head1 NAME
                   9202: 
                   9203: lond - "LON Daemon" Server (port "LOND" 5663)
                   9204: 
                   9205: =head1 SYNOPSIS
                   9206: 
1.74      harris41 9207: Usage: B<lond>
                   9208: 
                   9209: Should only be run as user=www.  This is a command-line script which
                   9210: is invoked by B<loncron>.  There is no expectation that a typical user
                   9211: will manually start B<lond> from the command-line.  (In other words,
                   9212: DO NOT START B<lond> YOURSELF.)
1.61      harris41 9213: 
                   9214: =head1 DESCRIPTION
                   9215: 
1.74      harris41 9216: There are two characteristics associated with the running of B<lond>,
                   9217: PROCESS MANAGEMENT (starting, stopping, handling child processes)
                   9218: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
                   9219: subscriptions, etc).  These are described in two large
                   9220: sections below.
                   9221: 
                   9222: B<PROCESS MANAGEMENT>
                   9223: 
1.61      harris41 9224: Preforker - server who forks first. Runs as a daemon. HUPs.
                   9225: Uses IDEA encryption
                   9226: 
1.74      harris41 9227: B<lond> forks off children processes that correspond to the other servers
                   9228: in the network.  Management of these processes can be done at the
                   9229: parent process level or the child process level.
                   9230: 
                   9231: B<logs/lond.log> is the location of log messages.
                   9232: 
                   9233: The process management is now explained in terms of linux shell commands,
                   9234: subroutines internal to this code, and signal assignments:
                   9235: 
                   9236: =over 4
                   9237: 
                   9238: =item *
                   9239: 
                   9240: PID is stored in B<logs/lond.pid>
                   9241: 
                   9242: This is the process id number of the parent B<lond> process.
                   9243: 
                   9244: =item *
                   9245: 
                   9246: SIGTERM and SIGINT
                   9247: 
                   9248: Parent signal assignment:
                   9249:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   9250: 
                   9251: Child signal assignment:
                   9252:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
                   9253: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
                   9254:  to restart a new child.)
                   9255: 
                   9256: Command-line invocations:
                   9257:  B<kill> B<-s> SIGTERM I<PID>
                   9258:  B<kill> B<-s> SIGINT I<PID>
                   9259: 
                   9260: Subroutine B<HUNTSMAN>:
                   9261:  This is only invoked for the B<lond> parent I<PID>.
                   9262: This kills all the children, and then the parent.
                   9263: The B<lonc.pid> file is cleared.
                   9264: 
                   9265: =item *
                   9266: 
                   9267: SIGHUP
                   9268: 
                   9269: Current bug:
                   9270:  This signal can only be processed the first time
                   9271: on the parent process.  Subsequent SIGHUP signals
                   9272: have no effect.
                   9273: 
                   9274: Parent signal assignment:
                   9275:  $SIG{HUP}  = \&HUPSMAN;
                   9276: 
                   9277: Child signal assignment:
                   9278:  none (nothing happens)
                   9279: 
                   9280: Command-line invocations:
                   9281:  B<kill> B<-s> SIGHUP I<PID>
                   9282: 
                   9283: Subroutine B<HUPSMAN>:
                   9284:  This is only invoked for the B<lond> parent I<PID>,
                   9285: This kills all the children, and then the parent.
                   9286: The B<lond.pid> file is cleared.
                   9287: 
                   9288: =item *
                   9289: 
                   9290: SIGUSR1
                   9291: 
                   9292: Parent signal assignment:
                   9293:  $SIG{USR1} = \&USRMAN;
                   9294: 
                   9295: Child signal assignment:
                   9296:  $SIG{USR1}= \&logstatus;
                   9297: 
                   9298: Command-line invocations:
                   9299:  B<kill> B<-s> SIGUSR1 I<PID>
                   9300: 
                   9301: Subroutine B<USRMAN>:
                   9302:  When invoked for the B<lond> parent I<PID>,
                   9303: SIGUSR1 is sent to all the children, and the status of
                   9304: each connection is logged.
1.144     foxr     9305: 
                   9306: =item *
                   9307: 
                   9308: SIGUSR2
                   9309: 
                   9310: Parent Signal assignment:
                   9311:     $SIG{USR2} = \&UpdateHosts
                   9312: 
                   9313: Child signal assignment:
                   9314:     NONE
                   9315: 
1.74      harris41 9316: 
                   9317: =item *
                   9318: 
                   9319: SIGCHLD
                   9320: 
                   9321: Parent signal assignment:
                   9322:  $SIG{CHLD} = \&REAPER;
                   9323: 
                   9324: Child signal assignment:
                   9325:  none
                   9326: 
                   9327: Command-line invocations:
                   9328:  B<kill> B<-s> SIGCHLD I<PID>
                   9329: 
                   9330: Subroutine B<REAPER>:
                   9331:  This is only invoked for the B<lond> parent I<PID>.
                   9332: Information pertaining to the child is removed.
                   9333: The socket port is cleaned up.
                   9334: 
                   9335: =back
                   9336: 
                   9337: B<SERVER-SIDE ACTIVITIES>
                   9338: 
                   9339: Server-side information can be accepted in an encrypted or non-encrypted
                   9340: method.
                   9341: 
                   9342: =over 4
                   9343: 
                   9344: =item ping
                   9345: 
                   9346: Query a client in the hosts.tab table; "Are you there?"
                   9347: 
                   9348: =item pong
                   9349: 
                   9350: Respond to a ping query.
                   9351: 
                   9352: =item ekey
                   9353: 
                   9354: Read in encrypted key, make cipher.  Respond with a buildkey.
                   9355: 
                   9356: =item load
                   9357: 
                   9358: Respond with CPU load based on a computation upon /proc/loadavg.
                   9359: 
                   9360: =item currentauth
                   9361: 
                   9362: Reply with current authentication information (only over an
                   9363: encrypted channel).
                   9364: 
                   9365: =item auth
                   9366: 
                   9367: Only over an encrypted channel, reply as to whether a user's
                   9368: authentication information can be validated.
                   9369: 
                   9370: =item passwd
                   9371: 
                   9372: Allow for a password to be set.
                   9373: 
                   9374: =item makeuser
                   9375: 
                   9376: Make a user.
                   9377: 
1.517     raeburn  9378: =item changeuserauth
1.74      harris41 9379: 
                   9380: Allow for authentication mechanism and password to be changed.
                   9381: 
                   9382: =item home
1.61      harris41 9383: 
1.74      harris41 9384: Respond to a question "are you the home for a given user?"
                   9385: 
                   9386: =item update
                   9387: 
                   9388: Update contents of a subscribed resource.
                   9389: 
                   9390: =item unsubscribe
                   9391: 
                   9392: The server is unsubscribing from a resource.
                   9393: 
                   9394: =item subscribe
                   9395: 
                   9396: The server is subscribing to a resource.
                   9397: 
                   9398: =item log
                   9399: 
                   9400: Place in B<logs/lond.log>
                   9401: 
                   9402: =item put
                   9403: 
                   9404: stores hash in namespace
                   9405: 
1.496     raeburn  9406: =item rolesput
1.74      harris41 9407: 
                   9408: put a role into a user's environment
                   9409: 
                   9410: =item get
                   9411: 
                   9412: returns hash with keys from array
                   9413: reference filled in from namespace
                   9414: 
                   9415: =item eget
                   9416: 
                   9417: returns hash with keys from array
                   9418: reference filled in from namesp (encrypts the return communication)
                   9419: 
                   9420: =item rolesget
                   9421: 
                   9422: get a role from a user's environment
                   9423: 
                   9424: =item del
                   9425: 
                   9426: deletes keys out of array from namespace
                   9427: 
                   9428: =item keys
                   9429: 
                   9430: returns namespace keys
                   9431: 
                   9432: =item dump
                   9433: 
                   9434: dumps the complete (or key matching regexp) namespace into a hash
                   9435: 
                   9436: =item store
                   9437: 
                   9438: stores hash permanently
                   9439: for this url; hashref needs to be given and should be a \%hashname; the
                   9440: remaining args aren't required and if they aren't passed or are '' they will
                   9441: be derived from the ENV
                   9442: 
                   9443: =item restore
                   9444: 
                   9445: returns a hash for a given url
                   9446: 
                   9447: =item querysend
                   9448: 
                   9449: Tells client about the lonsql process that has been launched in response
                   9450: to a sent query.
                   9451: 
                   9452: =item queryreply
                   9453: 
                   9454: Accept information from lonsql and make appropriate storage in temporary
                   9455: file space.
                   9456: 
                   9457: =item idput
                   9458: 
                   9459: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
                   9460: for each student, defined perhaps by the institutional Registrar.)
                   9461: 
                   9462: =item idget
                   9463: 
                   9464: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
                   9465: for each student, defined perhaps by the institutional Registrar.)
                   9466: 
1.517     raeburn  9467: =item iddel
                   9468: 
                   9469: Deletes one or more ids in a domain's id database.
                   9470: 
1.74      harris41 9471: =item tmpput
                   9472: 
                   9473: Accept and store information in temporary space.
                   9474: 
                   9475: =item tmpget
                   9476: 
                   9477: Send along temporarily stored information.
                   9478: 
                   9479: =item ls
                   9480: 
                   9481: List part of a user's directory.
                   9482: 
1.135     foxr     9483: =item pushtable
                   9484: 
                   9485: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
                   9486: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
                   9487: must be restored manually in case of a problem with the new table file.
                   9488: pushtable requires that the request be encrypted and validated via
                   9489: ValidateManager.  The form of the command is:
                   9490: enc:pushtable tablename <tablecontents> \n
                   9491: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
                   9492: cleartext newline.
                   9493: 
1.74      harris41 9494: =item Hanging up (exit or init)
                   9495: 
                   9496: What to do when a client tells the server that they (the client)
                   9497: are leaving the network.
                   9498: 
                   9499: =item unknown command
                   9500: 
                   9501: If B<lond> is sent an unknown command (not in the list above),
                   9502: it replys to the client "unknown_cmd".
1.135     foxr     9503: 
1.74      harris41 9504: 
                   9505: =item UNKNOWN CLIENT
                   9506: 
                   9507: If the anti-spoofing algorithm cannot verify the client,
                   9508: the client is rejected (with a "refused" message sent
                   9509: to the client, and the connection is closed.
                   9510: 
                   9511: =back
1.61      harris41 9512: 
                   9513: =head1 PREREQUISITES
                   9514: 
                   9515: IO::Socket
                   9516: IO::File
                   9517: Apache::File
                   9518: POSIX
                   9519: Crypt::IDEA
                   9520: GDBM_File
                   9521: Authen::Krb4
1.91      albertel 9522: Authen::Krb5
1.61      harris41 9523: 
                   9524: =head1 COREQUISITES
                   9525: 
1.490     droeschl 9526: none
                   9527: 
1.61      harris41 9528: =head1 OSNAMES
                   9529: 
                   9530: linux
                   9531: 
                   9532: =head1 SCRIPT CATEGORIES
                   9533: 
                   9534: Server/Process
                   9535: 
                   9536: =cut
1.409     foxr     9537: 
                   9538: 
                   9539: =pod
                   9540: 
                   9541: =head1 LOG MESSAGES
                   9542: 
                   9543: The messages below can be emitted in the lond log.  This log is located
                   9544: in ~httpd/perl/logs/lond.log  Many log messages have HTML encapsulation
                   9545: to provide coloring if examined from inside a web page. Some do not.
                   9546: Where color is used, the colors are; Red for sometihhng to get excited
                   9547: about and to follow up on. Yellow for something to keep an eye on to
                   9548: be sure it does not get worse, Green,and Blue for informational items.
                   9549: 
                   9550: In the discussions below, sometimes reference is made to ~httpd
                   9551: when describing file locations.  There isn't really an httpd 
                   9552: user, however there is an httpd directory that gets installed in the
                   9553: place that user home directories go.  On linux, this is usually
                   9554: (always?) /home/httpd.
                   9555: 
                   9556: 
                   9557: Some messages are colorless.  These are usually (not always)
                   9558: Green/Blue color level messages.
                   9559: 
                   9560: =over 2
                   9561: 
                   9562: =item (Red)  LocalConnection rejecting non local: <ip> ne 127.0.0.1
                   9563: 
                   9564: A local connection negotiation was attempted by
                   9565: a host whose IP address was not 127.0.0.1.
                   9566: The socket is closed and the child will exit.
                   9567: lond has three ways to establish an encyrption
                   9568: key with a client:
                   9569: 
                   9570: =over 2
                   9571: 
                   9572: =item local 
                   9573: 
                   9574: The key is written and read from a file.
                   9575: This is only valid for connections from localhost.
                   9576: 
                   9577: =item insecure 
                   9578: 
                   9579: The key is generated by the server and
                   9580: transmitted to the client.
                   9581: 
                   9582: =item  ssl (secure)
                   9583: 
                   9584: An ssl connection is negotiated with the client,
                   9585: the key is generated by the server and sent to the 
                   9586: client across this ssl connection before the
                   9587: ssl connectionis terminated and clear text
                   9588: transmission resumes.
                   9589: 
                   9590: =back
                   9591: 
                   9592: =item (Red) LocalConnection: caller is insane! init = <init> and type = <type>
                   9593: 
                   9594: The client is local but has not sent an initialization
                   9595: string that is the literal "init:local"  The connection
                   9596: is closed and the child exits.
                   9597: 
                   9598: =item Red CRITICAL Can't get key file <error>        
                   9599: 
                   9600: SSL key negotiation is being attempted but the call to
1.549     raeburn  9601: lonssl::KeyFile failed.  This usually means that the
1.409     foxr     9602: configuration file is not correctly defining or protecting
                   9603: the directories/files lonCertificateDirectory or
                   9604: lonnetPrivateKey
                   9605: <error> is a string that describes the reason that
                   9606: the key file could not be located.
                   9607: 
                   9608: =item (Red) CRITICAL  Can't get certificates <error>  
                   9609: 
                   9610: SSL key negotiation failed because we were not able to retrives our certificate
                   9611: or the CA's certificate in the call to lonssl::CertificateFile
                   9612: <error> is the textual reason this failed.  Usual reasons:
                   9613: 
                   9614: =over 2
1.490     droeschl 9615: 
1.409     foxr     9616: =item Apache config file for loncapa  incorrect:
1.490     droeschl 9617: 
1.409     foxr     9618: one of the variables 
                   9619: lonCertificateDirectory, lonnetCertificateAuthority, or lonnetCertificate
                   9620: undefined or incorrect
                   9621: 
                   9622: =item Permission error:
                   9623: 
                   9624: The directory pointed to by lonCertificateDirectory is not readable by lond
                   9625: 
                   9626: =item Permission error:
                   9627: 
                   9628: Files in the directory pointed to by lonCertificateDirectory are not readable by lond.
                   9629: 
                   9630: =item Installation error:                         
                   9631: 
                   9632: Either the certificate authority file or the certificate have not
                   9633: been installed in lonCertificateDirectory.
                   9634: 
                   9635: =item (Red) CRITICAL SSL Socket promotion failed:  <err> 
                   9636: 
                   9637: The promotion of the connection from plaintext to SSL failed
                   9638: <err> is the reason for the failure.  There are two
                   9639: system calls involved in the promotion (one of which failed), 
                   9640: a dup to produce
                   9641: a second fd on the raw socket over which the encrypted data
                   9642: will flow and IO::SOcket::SSL->new_from_fd which creates
                   9643: the SSL connection on the duped fd.
                   9644: 
                   9645: =item (Blue)   WARNING client did not respond to challenge 
                   9646: 
                   9647: This occurs on an insecure (non SSL) connection negotiation request.
                   9648: lond generates some number from the time, the PID and sends it to
                   9649: the client.  The client must respond by echoing this information back.
                   9650: If the client does not do so, that's a violation of the challenge
                   9651: protocols and the connection will be failed.
                   9652: 
                   9653: =item (Red) No manager table. Nobody can manage!!    
                   9654: 
                   9655: lond has the concept of privileged hosts that
                   9656: can perform remote management function such
                   9657: as update the hosts.tab.   The manager hosts
                   9658: are described in the 
                   9659: ~httpd/lonTabs/managers.tab file.
                   9660: this message is logged if this file is missing.
                   9661: 
                   9662: 
                   9663: =item (Green) Registering manager <dnsname> as <cluster_name> with <ipaddress>
                   9664: 
                   9665: Reports the successful parse and registration
                   9666: of a specific manager. 
                   9667: 
                   9668: =item Green existing host <clustername:dnsname>  
                   9669: 
                   9670: The manager host is already defined in the hosts.tab
                   9671: the information in that table, rather than the info in the
                   9672: manager table will be used to determine the manager's ip.
                   9673: 
                   9674: =item (Red) Unable to craete <filename>                 
                   9675: 
                   9676: lond has been asked to create new versions of an administrative
                   9677: file (by a manager).  When this is done, the new file is created
                   9678: in a temp file and then renamed into place so that there are always
                   9679: usable administrative files, even if the update fails.  This failure
                   9680: message means that the temp file could not be created.
                   9681: The update is abandoned, and the old file is available for use.
                   9682: 
                   9683: =item (Green) CopyFile from <oldname> to <newname> failed
                   9684: 
                   9685: In an update of administrative files, the copy of the existing file to a
                   9686: backup file failed.  The installation of the new file may still succeed,
                   9687: but there will not be a back up file to rever to (this should probably
                   9688: be yellow).
                   9689: 
                   9690: =item (Green) Pushfile: backed up <oldname> to <newname>
                   9691: 
                   9692: See above, the backup of the old administrative file succeeded.
                   9693: 
                   9694: =item (Red)  Pushfile: Unable to install <filename> <reason>
                   9695: 
                   9696: The new administrative file could not be installed.  In this case,
                   9697: the old administrative file is still in use.
                   9698: 
                   9699: =item (Green) Installed new < filename>.                      
                   9700: 
                   9701: The new administrative file was successfullly installed.                                               
                   9702: 
                   9703: =item (Red) Reinitializing lond pid=<pid>                    
                   9704: 
                   9705: The lonc child process <pid> will be sent a USR2 
                   9706: signal.
                   9707: 
                   9708: =item (Red) Reinitializing self                                    
                   9709: 
                   9710: We've been asked to re-read our administrative files,and
                   9711: are doing so.
                   9712: 
                   9713: =item (Yellow) error:Invalid process identifier <ident>  
                   9714: 
                   9715: A reinit command was received, but the target part of the 
                   9716: command was not valid.  It must be either
                   9717: 'lond' or 'lonc' but was <ident>
                   9718: 
                   9719: =item (Green) isValideditCommand checking: Command = <command> Key = <key> newline = <newline>
                   9720: 
                   9721: Checking to see if lond has been handed a valid edit
                   9722: command.  It is possible the edit command is not valid
                   9723: in that case there are no log messages to indicate that.
                   9724: 
                   9725: =item Result of password change for  <username> pwchange_success
                   9726: 
                   9727: The password for <username> was
                   9728: successfully changed.
                   9729: 
                   9730: =item Unable to open <user> passwd to change password
                   9731: 
                   9732: Could not rewrite the 
                   9733: internal password file for a user
                   9734: 
                   9735: =item Result of password change for <user> : <result>
1.490     droeschl 9736: 
1.409     foxr     9737: A unix password change for <user> was attempted 
                   9738: and the pipe returned <result>  
                   9739: 
                   9740: =item LWP GET: <message> for <fname> (<remoteurl>)
                   9741: 
                   9742: The lightweight process fetch for a resource failed
                   9743: with <message> the local filename that should
                   9744: have existed/been created was  <fname> the
                   9745: corresponding URI: <remoteurl>  This is emitted in several
                   9746: places.
                   9747: 
                   9748: =item Unable to move <transname> to <destname>     
                   9749: 
                   9750: From fetch_user_file_handler - the user file was replicated but could not
                   9751: be mv'd to its final location.
                   9752: 
                   9753: =item Looking for <domain> <username>              
                   9754: 
                   9755: From user_has_session_handler - This should be a Debug call instead
                   9756: it indicates lond is about to check whether the specified user has a 
                   9757: session active on the specified domain on the local host.
                   9758: 
                   9759: =item Client <ip> (<name>) hanging up: <input>     
                   9760: 
                   9761: lond has been asked to exit by its client.  The <ip> and <name> identify the
                   9762: client systemand <input> is the full exit command sent to the server.
                   9763: 
                   9764: =item Red CRITICAL: ABNORMAL EXIT. child <pid> for server <hostname> died through a crass with this error->[<message>].
1.490     droeschl 9765: 
1.409     foxr     9766: A lond child terminated.  NOte that this termination can also occur when the
                   9767: child receives the QUIT or DIE signals.  <pid> is the process id of the child,
                   9768: <hostname> the host lond is working for, and <message> the reason the child died
                   9769: to the best of our ability to get it (I would guess that any numeric value
                   9770: represents and errno value).  This is immediately followed by
                   9771: 
                   9772: =item  Famous last words: Catching exception - <log> 
                   9773: 
                   9774: Where log is some recent information about the state of the child.
                   9775: 
                   9776: =item Red CRITICAL: TIME OUT <pid>                     
                   9777: 
                   9778: Some timeout occured for server <pid>.  THis is normally a timeout on an LWP
                   9779: doing an HTTP::GET.
                   9780: 
                   9781: =item child <pid> died                              
                   9782: 
                   9783: The reaper caught a SIGCHILD for the lond child process <pid>
                   9784: This should be modified to also display the IP of the dying child
                   9785: $children{$pid}
                   9786: 
                   9787: =item Unknown child 0 died                           
                   9788: A child died but the wait for it returned a pid of zero which really should not
                   9789: ever happen. 
                   9790: 
                   9791: =item Child <which> - <pid> looks like we missed it's death 
                   9792: 
                   9793: When a sigchild is received, the reaper process checks all children to see if they are
                   9794: alive.  If children are dying quite quickly, the lack of signal queuing can mean
                   9795: that a signal hearalds the death of more than one child.  If so this message indicates
                   9796: which other one died. <which> is the ip of a dead child
                   9797: 
                   9798: =item Free socket: <shutdownretval>                
                   9799: 
                   9800: The HUNTSMAN sub was called due to a SIGINT in a child process.  The socket is being shutdown.
                   9801: for whatever reason, <shutdownretval> is printed but in fact shutdown() is not documented
                   9802: to return anything. This is followed by: 
                   9803: 
                   9804: =item Red CRITICAL: Shutting down                       
                   9805: 
                   9806: Just prior to exit.
                   9807: 
                   9808: =item Free socket: <shutdownretval>                 
                   9809: 
                   9810: The HUPSMAN sub was called due to a SIGHUP.  all children get killsed, and lond execs itself.
                   9811: This is followed by:
                   9812: 
                   9813: =item (Red) CRITICAL: Restarting                         
                   9814: 
                   9815: lond is about to exec itself to restart.
                   9816: 
                   9817: =item (Blue) Updating connections                        
                   9818: 
                   9819: (In response to a USR2).  All the children (except the one for localhost)
                   9820: are about to be killed, the hosts tab reread, and Apache reloaded via apachereload.
                   9821: 
                   9822: =item (Blue) UpdateHosts killing child <pid> for ip <ip>   
                   9823: 
                   9824: Due to USR2 as above.
                   9825: 
                   9826: =item (Green) keeping child for ip <ip> (pid = <pid>)    
                   9827: 
                   9828: In response to USR2 as above, the child indicated is not being restarted because
                   9829: it's assumed that we'll always need a child for the localhost.
                   9830: 
                   9831: 
                   9832: =item Going to check on the children                
                   9833: 
                   9834: Parent is about to check on the health of the child processes.
                   9835: Note that this is in response to a USR1 sent to the parent lond.
                   9836: there may be one or more of the next two messages:
                   9837: 
                   9838: =item <pid> is dead                                 
                   9839: 
                   9840: A child that we have in our child hash as alive has evidently died.
                   9841: 
                   9842: =item  Child <pid> did not respond                   
                   9843: 
                   9844: In the health check the child <pid> did not update/produce a pid_.txt
                   9845: file when sent it's USR1 signal.  That process is killed with a 9 signal, as it's
                   9846: assumed to be hung in some un-fixable way.
                   9847: 
                   9848: =item Finished checking children                   
1.490     droeschl 9849: 
1.409     foxr     9850: Master processs's USR1 processing is cojmplete.
                   9851: 
                   9852: =item (Red) CRITICAL: ------- Starting ------            
                   9853: 
                   9854: (There are more '-'s on either side).  Lond has forked itself off to 
                   9855: form a new session and is about to start actual initialization.
                   9856: 
                   9857: =item (Green) Attempting to start child (<client>)       
                   9858: 
                   9859: Started a new child process for <client>.  Client is IO::Socket object
                   9860: connected to the child.  This was as a result of a TCP/IP connection from a client.
                   9861: 
                   9862: =item Unable to determine who caller was, getpeername returned nothing
1.490     droeschl 9863: 
1.409     foxr     9864: In child process initialization.  either getpeername returned undef or
                   9865: a zero sized object was returned.  Processing continues, but in my opinion,
                   9866: this should be cause for the child to exit.
                   9867: 
                   9868: =item Unable to determine clientip                  
                   9869: 
                   9870: In child process initialization.  The peer address from getpeername was not defined.
                   9871: The client address is stored as "Unavailable" and processing continues.
                   9872: 
                   9873: =item (Yellow) INFO: Connection <ip> <name> connection type = <type>
1.490     droeschl 9874: 
1.409     foxr     9875: In child initialization.  A good connectionw as received from <ip>.
                   9876: 
                   9877: =over 2
                   9878: 
                   9879: =item <name> 
                   9880: 
                   9881: is the name of the client from hosts.tab.
                   9882: 
                   9883: =item <type> 
                   9884: 
                   9885: Is the connection type which is either 
                   9886: 
                   9887: =over 2
                   9888: 
                   9889: =item manager 
                   9890: 
                   9891: The connection is from a manager node, not in hosts.tab
                   9892: 
                   9893: =item client  
                   9894: 
                   9895: the connection is from a non-manager in the hosts.tab
                   9896: 
                   9897: =item both
                   9898: 
                   9899: The connection is from a manager in the hosts.tab.
                   9900: 
                   9901: =back
                   9902: 
                   9903: =back
                   9904: 
                   9905: =item (Blue) Certificates not installed -- trying insecure auth
                   9906: 
                   9907: One of the certificate file, key file or
                   9908: certificate authority file could not be found for a client attempting
                   9909: SSL connection intiation.  COnnection will be attemptied in in-secure mode.
                   9910: (this would be a system with an up to date lond that has not gotten a 
                   9911: certificate from us).
                   9912: 
                   9913: =item (Green)  Successful local authentication            
                   9914: 
                   9915: A local connection successfully negotiated the encryption key. 
                   9916: In this case the IDEA key is in a file (that is hopefully well protected).
                   9917: 
                   9918: =item (Green) Successful ssl authentication with <client>  
                   9919: 
                   9920: The client (<client> is the peer's name in hosts.tab), has successfully
                   9921: negotiated an SSL connection with this child process.
                   9922: 
                   9923: =item (Green) Successful insecure authentication with <client>
1.490     droeschl 9924: 
1.409     foxr     9925: 
                   9926: The client has successfully negotiated an  insecure connection withthe child process.
                   9927: 
                   9928: =item (Yellow) Attempted insecure connection disallowed    
                   9929: 
                   9930: The client attempted and failed to successfully negotiate a successful insecure
                   9931: connection.  This can happen either because the variable londAllowInsecure is false
                   9932: or undefined, or becuse the child did not successfully echo back the challenge
                   9933: string.
                   9934: 
                   9935: 
                   9936: =back
                   9937: 
1.441     raeburn  9938: =back
                   9939: 
1.409     foxr     9940: 
                   9941: =cut

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